我知道我无法使用漫游器删除超过100个,但是我可以重新启动脚本来删除更多吗?
这是我当前的代码:
const CLEAR_MESSAGES = '!clearmessages';
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'mytoken';
bot.on('ready', () => {
console.log('!clearmessages to run...');
bot.on('message', message => {
if (message.content == CLEAR_MESSAGES) {
if (message.channel.type == 'text') {
message.channel.fetchMessages()
.then(messages => {
message.channel.bulkDelete(messages);
messagesDeleted = messages.array().length;
message.channel.sendMessage("Number of deleted messages: "+messagesDeleted);
console.log('Number of deleted messages: '+messagesDeleted)
})
.catch(err => {
console.log('error.');
console.log(err);
});
}
}
});
});
bot.login(token);
答案 0 :(得分:0)
的确,bulkDelete()
一次不能删除100条以上的消息,但是只要有剩余,您就可以检查和删除消息。当邮件的时间超过两周时,您需要一个一个地删除它们。
您可以使用递归异步函数,该函数将一直运行直到没有剩余消息为止。请记住,通过这种方式,您将删除所有频道中的消息。
bot.on('message', async message => {
if (message.content == CLEAR_MESSAGES) {
let messagesDeleted = await clearChannel(message.channel);
message.channel.sendMessage("Number of deleted messages: " + messagesDeleted);
console.log('Number of deleted messages: ' + messagesDeleted)
}
});
async function clearChannel(channel, n = 0, old = false) {
let collected = await channel.fetchMessages();
if (collected.size > 0) {
if (old) {
for (let msg of collected.array()) {
await msg.delete();
n++;
}
} else {
let deleted = await channel.bulkDelete(100, true);
if (deleted.size < collected.size) old = true;
n += deleted;
}
return n + await clearChannel(channel, old);
} else return 0;
}
答案 1 :(得分:-1)
类似的操作将重复该循环4次,每次删除50条消息
let msgs = 0;
bot.on('ready', () => {
console.log('!clearmessages to run...');
bot.on('message', async message => {
if (message.content == CLEAR_MESSAGES) {
for (let index = 0; index <= 3; index++) {
if (message.channel.type == 'text') {
await message.channel.fetchMessages()
.then(async messages => {
await message.channel.bulkDelete(messages);
messagesDeleted = messages.array().length;
msgs = msgs + messagesDeleted;
})
.catch(err => {
console.log('error.');
console.log(err);
});
}
}
console.log(`Total number of messages deleted ${msgs}`);
message.channel.sendMessage(`Total number of messages deleted ${msgs}`);
}
});
});