versity
versity

Reputation: 29

Problems with deleting messages that were fetched

Trying to delete messages from a certain user, but nothing happens:

bot.js
client.on("message", (message) => {
            if (message.content === '$deleteuser') {

                message.channel.fetchMessages({limit: 10}).then(collected => { //collected is a Collection
                    collected.forEach(msg => {
                        if (message.author.id === '474851505908875266') {
                            message.delete(0);
                        }


                    });
                });
            }

        });

Upvotes: 0

Views: 124

Answers (1)

slothiful
slothiful

Reputation: 5623

First of all, your issue arises from your mistaken use of message instead of msg inside your forEach() callback (as @Gruntzy has pointed out). As declared, message is the message parameter of your event, while msg is the message of the forEach()'s iteration. Therefore, when you use message inside the callback, you're interacting with the original event message.

Secondly, your code would cause a rate limit to occur because of the separate Message.delete() calls. Use TextChannel.bulkDelete().

Improved code:

client.on('message', async message => {
  if (message.content === '$deleteuser') {
    try {
      const toDelete = [];

      const fetched = await message.channel.fetchMessages({ limit: 10 });
      fetched.forEach(msg => {
        if (msg.author.id === '474851505908875266') toDelete.push(msg.id);
      });

      await message.channel.bulkDelete(toDelete);
    } catch(err) {
      console.error(err);
    }
  }
});

Upvotes: 1

Related Questions