【问题标题】:How do I execute a block of code whenever a reaction is added? (discord.js)每当添加反应时,如何执行代码块? (discord.js)
【发布时间】:2020-07-16 20:37:34
【问题描述】:

我正在尝试创建一个机器人来计算在一个时间范围内对消息有多少特定反应('⚪')。我还希望能够通过对单独的表情符号('X')做出反应来跳过剩余的时间。我在实施第二部分时遇到了麻烦。这是我的代码:

const filter = (reaction) => ['⚪'].includes(reaction.emoji.name)*/;
            MSG.awaitReactions(filter, { //MSG is the message that reactions are added to
                max: 20,
                time: 180000,
                errors: ['time'],
            })
                .then(collected => {
                    message.channel.send("Too many people.");
                })
                .catch(collected => {
                    var reaction = collected.first();
                    playerNum = reaction.count - 1;
                })

我在想,如果对“X”做出反应,我可以以某种方式抛出错误,将代码直接指向 catch 语句,而无需等待时间到期。我尝试将其放入过滤器中,但没有成功。有没有人有办法解决吗?谢谢!

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    您需要使用reaction collector,这是awaitReactions 在内部使用的。

    // Same filter but include ❌
    const filter = ({emoji}) => ['⚪', '❌'].includes(emoji.name);
    
    // Create the collector
    const collector = MSG.createReactionCollector(filter, {
      max: 20,
      time: 180000,
    });
    
    // collect is emitted every time someone reacts
    collector.on('collect', ({emoji}) => {
      // Stop the collector on ❌
      if (emoji.name === '❌') collector.stop();
    });
    
    // end is emitted:
    // when there are 20 reactions (limit)
    // after 3 minutes (time) or
    // when the collector is manually stopped (user by default)
    collector.on('end', (collected, reason) => {
      if (reason === 'limit') message.channel.send('Too many people.');
      else {
        const reaction = collected.first();
        playerNum = reaction.count - 1;
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 2021-01-03
      • 2017-03-02
      • 2018-11-11
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多