[SOLVED] How to delete messages EFFICIENTLY with Discord bot


I want have a Discord Music Bot that when it leaves the voice channel it clears the text channel from commands and logs. But the problem is that it takes too much time (up to 1-3 mins). I have seen other that other bots are able to do the same in much lower time, so how can I make my code better?

Here is my code, that it does work, but I would like to make the bot delete messages faster:

} else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
        const channel = msg.channel;
        const messageManager = channel.messages;
        messageManager.fetch({ limit: 100 }).then((messages) => {
             messages.forEach((message) => {
                 if ((message.author.id == 0123456789) || (message.content.startsWith(PREFIX))) {  
        if (guildMap.has(mapKey)) {
            let val = guildMap.get(mapKey);
            if (val.voice_Channel) val.voice_Channel.leave()
            if (val.voice_Connection) val.voice_Connection.disconnect()
            if (val.musicYTStream) val.musicYTStream.destroy()

        } else {
            msg.reply("Cannot leave because not connected.")


Discord.js has a feature to prune a large number of messages.

First, you fetch all messages in the channel up to a certain point (e.g. the latest 100 messages), then filter them depending on your criteria.
Afterwards, you use channel.bulkDelete(messages) to immediately delete all of them.
This only works for messages younger than 14 days sadly, but it’s much more efficient than manually deleting them.
The code could look somewhat like this:

//fetch 100 most recent messages
channel.messages.fetch({limit: 100}).then(messages => {
    //filter the messages to only delete messages by a certain user
    messages = messages.filter(m => m.author.id === useridhere)

    //bulk delete the messages


Answered By – Aci

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *