我正在尝试制作一个机器人,它可以在频道中获取以前的机器人消息,然后删除它们。我目前使用此代码,在输入!clearMessages
时删除频道中的所有消息:
if (message.channel.type == 'text') {
message.channel.fetchMessages().then(messages => {
message.channel.bulkDelete(messages);
messagesDeleted = messages.array().length; // number of messages deleted
// Logging the number of messages deleted on both the channel and console.
message.channel.send("Deletion of messages successful. Total messages deleted: "+messagesDeleted);
console.log('Deletion of messages successful. Total messages deleted: '+messagesDeleted)
}).catch(err => {
console.log('Error while doing Bulk Delete');
console.log(err);
});
}
我希望机器人只能从该频道中的所有机器人消息中获取消息,然后删除这些消息。
我该怎么做?
答案 0 :(得分:2)
每个Message
都有author
property代表User
。每个User
都有bot
property,表示用户是否是机器人。
使用该信息,我们可以使用messages.filter(msg => msg.author.bot)
过滤掉非机器人消息的消息:
if (message.channel.type == 'text') {
message.channel.fetchMessages().then(messages => {
const botMessages = messages.filter(msg => msg.author.bot);
message.channel.bulkDelete(botMessages);
messagesDeleted = botMessages.array().length; // number of messages deleted
// Logging the number of messages deleted on both the channel and console.
message.channel.send("Deletion of messages successful. Total messages deleted: " + messagesDeleted);
console.log('Deletion of messages successful. Total messages deleted: ' + messagesDeleted)
}).catch(err => {
console.log('Error while doing Bulk Delete');
console.log(err);
});
}