简体   繁体   English

每当添加反应时,如何执行代码块? (discord.js)

[英]How do I execute a block of code whenever a reaction is added? (discord.js)

I'm trying to create a bot that counts how many of a certain reaction('⚪') there are to a message within a time frame.我正在尝试创建一个机器人来计算在一个时间范围内对消息有多少特定反应('⚪')。 I also want to be able to skip the remaining time by reacting to a separate emoji('X').我还希望能够通过对单独的表情符号('X')做出反应来跳过剩余时间。 I'm having trouble implementing the second part.我在实施第二部分时遇到了麻烦。 Here is my code:这是我的代码:

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

I was thinking I could somehow throw an error if the 'X' is reacted to, to direct the code directly to the catch statement without waiting for the time to expire.我在想,如果对“X”做出反应,我可能会以某种方式抛出错误,将代码直接指向 catch 语句,而无需等待时间到期。 I tried putting it in the filter, but it was unsuccessful.我尝试将其放入过滤器中,但没有成功。 Does anyone have a solution?有没有人有办法解决吗? Thanks!谢谢!

You'll need to use a reaction collector , which is what awaitReactions uses internally.您需要使用一个反应收集器,这是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;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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