简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM