1
votes

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?

1

1 Answers

5
votes

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);
    });
}