問題描述
我正在嘗試制作一個機器人來獲取頻道中以前的機器人消息,然后將它們刪除.我目前有這段代碼,當輸入 !clearMessages
時,它會刪除頻道中的所有消息:
I am trying to make a bot that fetches previous bot messages in the channel and then deletes them. I have this code currently that deletes all messages in the channel when !clearMessages
is entered:
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);
});
}
我希望機器人僅從該頻道中的所有機器人消息中獲取消息,然后刪除這些消息.
I would like the bot to only fetch messages from all bot messages in that channel, and then delete those messages.
我該怎么做?
推薦答案
每個 Message
有一個 author
屬性,表示 用戶
.每個 User
都有一個 bot
屬性 表示如果用戶是機器人.
Each Message
has an author
property that represents a User
. Each User
has a bot
property that indicates if the user is a bot.
使用該信息,我們可以使用 messages.filter(msg => msg.author.bot)
過濾掉不是機器人消息的消息:
Using that information, we can filter out messages that are not bot messages with 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);
});
}
這篇關于從機器人 Discord.js 獲取機器人消息的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!