Romam Paul
Romam Paul

Reputation: 11

'DiscordAPIError: Unknown Message' when deleting message upon a reaction

I'm trying to make a menu in JavaScript with my Discord.js bot. So far everything works perfectly, except when I apply the reaction that removes the message. The message gets deleted, but this error is spammed in the console:

DiscordAPIError: Unknown Message

I checked in other areas and was careful to delete the message only once, but even so, I get the impression that the bot is attempting to delete it several times. I've also tried return to try to stop the code, and put a timer to the delete method. None of these attempts have resolved the error.

This is the code I'm using:

message.channel.send(exampleEmbed2).then(sentEmbed => {

    sentEmbed.react('🔚');  
    sentEmbed.react('✅');
    sentEmbed.react('❌');

    client.on('messageReactionAdd', (reaction, user) => {

        if (!user.bot && reaction.emoji.name === '🔚') {
            sentEmbed.delete();
        }

    });
});

Upvotes: 1

Views: 2664

Answers (1)

slothiful
slothiful

Reputation: 5623

As Gruntzy has explained...

...with this code, everytime someone reacts to any message with 🔚, this runs your code.

As opposed to attaching another listener to a nested messageReactionAdd event, use Reaction Collectors. These are meant for this purpose and will only fire upon reactions on the message you attach them to.

Consider this example which uses the promise-based version of a collector (see Message.awaitReactions())...

message.channel.send(exampleEmbed2)
  .then(async sentEmbed => { // Somewhat awkward to switch to async/await here, but much cleaner.
    await sentEmbed.react('🔚');
    await sentEmbed.react('✅');
    await sentEmbed.react('❌');

    const filter = (reaction, user) => ['🔚', '✅', '❌'].includes(reaction.emoji.name) && user.id === message.author.id
    const [reaction] = await sentEmbed.awaitReactions(filter, { maxMatches: 1 });
//        ^^^^^^^^^^
//  This is a destructuring
//  assignment. It takes the
//  first (and only) element
//  from the Collection/Map.

    if (reaction.emoji.name === '🔚') await sentEmbed.delete();
//  Do stuff with the other reactions...
  })
  .catch(console.error);

Upvotes: 2

Related Questions