简体   繁体   中英

Discord.js add role by reacting to message

The following code wont work as I expected. I want a User to react with a checkmark and then log something in the console. Instead of that the bot activates the function by itself and then the function never gets called again.

client.once('ready', () => {

    console.log('Ready!');

    const exampleEmbed = <unimportant>;

    client.channels.cache.get("771041812638728235").send(exampleEmbed).then((message) => {
        message.react('✅');
        message.createReactionCollector(r => r.emoji.name == '✅')
        .on('collect', r => {
            console.log("nice");
        });
    });

});

It might be because the reaction collector is created before the message.react() method finishes executing, causing it to activate on itself. You could either use async/await or a then() callback to make sure the reaction has finished, or simply add a line making sure the user is not a bot in your collector filter.

// method 1:
client.channels.cache
 .get('771041812638728235')
 .send(exampleEmbed)
 .then(async (message) => {
  //   ^^^^^
  // make sure the function is async
  await message.react('✅');
  message
   .createReactionCollector((r) => r.emoji.name == '✅')
   .on('collect', (r) => {
    console.log('nice');
   });
 });


// method 2:
client.channels.cache
 .get('771041812638728235')
 .send(exampleEmbed)
 .then(message) => {
  // .then() callback
  message.react('✅').then(() =>
  message
   .createReactionCollector((r) => r.emoji.name == '✅')
   .on('collect', (r) => {
    console.log('nice');
   }););
 });


// method 3:
client.channels.cache
 .get('771041812638728235')
 .send(exampleEmbed)
 .then((message) => {
  message.react('✅');
  message
   // make sure the user who reacted isn't a bot
   .createReactionCollector((r, u) => r.emoji.name == '✅' && !user.bot)
   .on('collect', (r) => {
    console.log('nice');
   });
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM