Discord.js通过响应消息来添加角色

问题描述

以下代码无法正常工作。我希望用户对一个复选标记做出反应,然后在控制台中记录一些内容。取而代之的是,该机器人会自行激活该功能,然后该功能便不再被调用。

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");
        });
    });

});

解决方法

可能是因为反应收集器是在message.react()方法执行完成之前创建的,从而导致其自身激活。您可以使用async/awaitthen()回调来确保反应已完成,或者只需添加一行以确保用户不是您的收集器过滤器中的漫游器即可。

// 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');
   });
 });

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...