How to remove messages using a Discord bot?

Hey everyone! I’m trying to set up a Discord bot that can delete messages, but I’m running into some issues. I’ve written a simple code snippet, but it’s not working as expected. Here’s what I’ve got so far:

if (message.content.toLowerCase() === commandPrefix + 'purge') {
    message.channel.bulkDelete(100)
        .then(() => {
            message.channel.send('Cleaned up 100 messages!');
        })
        .catch(error => {
            console.error('Error purging messages:', error);
        });
}

I’m using Node.js version 12.16.3. Can anyone help me figure out what I’m doing wrong or suggest a better way to implement this feature? Thanks in advance for any advice!

I’ve implemented message deletion in my Discord bot and can share some insights. Your code looks close, but there are a few things to consider:

Make sure your bot has the necessary permissions in the channel.

The bulkDelete method can only remove messages that are less than 14 days old.

It’s good practice to limit the number of messages deleted to avoid rate limits.

Here’s a slightly modified version that’s worked well for me:

if (message.content.toLowerCase().startsWith(commandPrefix + 'purge')) {
    const amount = parseInt(message.content.split(' ')[1]) || 100;
    message.channel.bulkDelete(Math.min(amount, 100), true)
        .then(deleted => {
            message.channel.send(`Deleted ${deleted.size} messages.`).then(msg => {
                msg.delete({ timeout: 3000 });
            });
        })
        .catch(console.error);
}

This allows specifying the number of messages to delete and handles errors more gracefully. Hope this helps!

hey mate, i had similar issues. make sure ur bot has ‘Manage Messages’ permission. also, bulkDelete only works for msgs < 14 days old. try adding a check for that. and maybe add a confirmation step b4 deleting, like:

if (confirm) {
  // deletion code here
}

hope this helps!

Having worked with Discord bots extensively, I can offer some advice on message deletion. While the provided code is a good start, there are a few improvements you can make for better functionality and error handling.

First, ensure your bot has the ‘Manage Messages’ permission in the channel. This is crucial for message deletion operations.

Secondly, consider adding a check for the number of messages to delete. Discord’s API limits bulk deletions to 100 messages at a time, so you might want to implement a loop for larger purges.

Lastly, it’s wise to add a confirmation step before deleting messages to prevent accidental data loss. This could be a simple yes/no reaction or a time-limited confirmation message.

Remember to handle potential errors gracefully and provide feedback to users on the operation’s success or failure.