John
John

Reputation: 59

Bulk delete messages by user in Discord.js

I want to delete all the messages posted by a particular user. So far I have:

async function clear() {
    let botMessages;
    botMessages = await message.channel.fetch(708292930925756447);
    message.channel.bulkDelete(botMessages).then(() => {
        message.channel.send("Cleared bot messages").then(msg => msg.delete({timeout: 3000}))
    });
}
clear();

There seems to be an issue with passing botMessages to bulkDelete(), it wants an array or collection but apparantly botMessages isn't an array or collection.

How would I give botMessages to bulkDelete, or am I going about this totally wrong?

Upvotes: 1

Views: 5570

Answers (1)

Syntle
Syntle

Reputation: 5174

message.channel.fetch() fetches the channel the message is sent to, not the messages in that channel.

You need to fetch a certain amount of messages and filter it so you're only getting messages sent by your bot then pass them to bulkDelete()

message.channel.messages.fetch({
    limit: 100 // Change `100` to however many messages you want to fetch
}).then((messages) => { 
    const botMessages = [];
    messages.filter(m => m.author.id === BOT_ID_HERE).forEach(msg => botMessages.push(msg))
    message.channel.bulkDelete(botMessages).then(() => {
        message.channel.send("Cleared bot messages").then(msg => msg.delete({
            timeout: 3000
        }))
    });
})

Upvotes: 5

Related Questions