How to make a Discord bot remove messages?

Hey everyone! I’m trying to create a Discord bot that can delete messages, but I’m running into some issues. Here’s what I’ve got so far:

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

I’m using Node.js version 12.16.3. When I run this code, it doesn’t seem to work as expected. Can anyone help me figure out what I’m doing wrong or suggest a better way to implement this feature? I’d really appreciate any tips or explanations. Thanks in advance!

I’ve implemented message deletion in my Discord bots before, and I can share some insights. The code you’ve provided looks mostly correct, but there are a few things to consider:

  1. Make sure your bot has the necessary permissions in the channel to delete messages.

  2. The bulkDelete method can only delete messages that are less than 14 days old. For older messages, you’ll need to delete them individually.

  3. Consider adding a check to ensure the user invoking the command has the appropriate permissions.

Here’s a slightly modified version that might work better:

if (message.content.toLowerCase() === commandPrefix + 'cleanup') {
  if (!message.member.hasPermission("MANAGE_MESSAGES")) {
    return message.reply('You don't have permission to use this command.');
  }
  
  message.channel.messages.fetch({ limit: 50 })
    .then(messages => {
      message.channel.bulkDelete(messages)
        .then(() => {
          message.channel.send('Cleaned up messages!').then(msg => {
            msg.delete({ timeout: 5000 });
          });
        })
        .catch(error => {
          console.error('Error deleting messages:', error);
        });
    });
}

This version fetches the messages first, which can help with the 14-day limitation. It also includes a permission check and auto-deletes the confirmation message after 5 seconds. Hope this helps!

yo, i’ve messed with discord bots before. try this:

client.on(‘message’, msg => {
if (msg.content === ‘!delete’) {
msg.channel.bulkDelete(100)
.then(messages => console.log(Nuked ${messages.size} messages))
.catch(console.error);
}
});

just change the number to however many u wanna zap. make sure ur bot has perms tho

I’ve encountered similar issues when developing Discord bots. One crucial aspect you might want to consider is error handling. Your current code assumes the deletion will always succeed, which isn’t always the case.

Try wrapping your code in a try-catch block to handle potential errors more gracefully. Also, consider implementing a cooldown mechanism to prevent spam. Here’s a quick example:

const cooldowns = new Set();

if (message.content.toLowerCase() === commandPrefix + 'cleanup') {
  if (cooldowns.has(message.author.id)) return message.reply('Please wait before using this command again.');
  
  try {
    const deleted = await message.channel.bulkDelete(50, true);
    message.channel.send(`Cleaned up ${deleted.size} messages.`);
    
    cooldowns.add(message.author.id);
    setTimeout(() => cooldowns.delete(message.author.id), 30000);
  } catch (error) {
    console.error('Error:', error);
    message.channel.send('An error occurred while deleting messages.');
  }
}

This approach provides better error handling and prevents command spam. Remember to adjust the cooldown duration as needed for your specific use case.