Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  42] [ 2]  / answers: 1 / hits: 24789  / 7 Years ago, sat, december 23, 2017, 12:00:00

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.



How would I do this?


More From » node.js

 Answers
286

Each Message has an author property that represents a User. Each User has a bot property that indicates if the user is a 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);
});
}

[#55605] Tuesday, December 19, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yisroels

Total Points: 256
Total Questions: 94
Total Answers: 102

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;