限制用户对消息的反应

时间:2020-03-15 06:32:41

标签: javascript discord.js

我正在为JavaScript中的Discord构建一个简单的 投票机器人 ,现在,我正在尝试实现每位用户对一条消息的最大反应次数。

例如,假设我们为民意测验问题提供以下选项:

问题?

  1. 选项A

  2. 选项B

  3. 选项C

  4. 选项D

  5. 选项E

每个“选项”都是对机器人发出的消息的反应,我想确保用户 不能对做出反应 em> 3

  • 我的思路是让messageReactionAdd听众 然后,当用户对4th time做出反应时,删除最后一个 反应,并向他发送“您已投票3 times”之类的消息, 请删除再次投票的反应。”
  • 不过,我仍然试图在对象之间导航以找到 总反应计数每个用户我可以找到总反应计数 每个表情符号,但这不是我所需要的。

有人可以给我一些见解吗?

编辑

用于发送消息的代码:

Embed = new Discord.MessageEmbed()
                .setColor(0x6666ff)
                .setTitle(question)
                .setDescription(optionsList);

                message.channel.send(Embed).then(messageReaction => {

                for (var i = 0; i < options.length; i++){
                    messageReaction.react(emojiAlphabet[i][0]);
                }

                message.delete().catch(console.error);
              });

1 个答案:

答案 0 :(得分:2)

尝试一下:

const {Collection} = require('discord.js')

// the messages that users can only react 3 times with
const polls = new Set()
// Collection<Message, Collection<User, number>>: stores how many times a user has reacted on a message
const reactionCount = new Collection()

// when you send a poll add the message the bot sent to the set:
polls.add(message)

client.on('messageReactionAdd', (reaction, user) => {
  // edit: so that this does not run when the bot reacts
  if (user.id === client.user.id) return

  const {message} = reaction

  // only do the following if the message is one of the polls
  if (polls.has(message)) {
    // if message hasn't been added to collection add it
    if (!reactionCount.get(message)) reactionCount.set(message, new Collection())
    // reaction counts for this message
    const userCount = reactionCount.get(message)
    // add 1 to the user's reaction count
    userCount.set(user, (userCount.get(user) || 0) + 1)

    if (userCount.get(user) > 3) {
      reaction.users.remove(user)
      // <@!id> mentions the user (using their nickname if they have one)
      message.channel.send(`<@!${user.id}>, you've already voted 3 times, please remove a reaction to vote again.`)
    }
  }
})

client.on('messageReactionRemove', (reaction, user) => {
  // edit: so that this does not run when the bot reacts
  if (user.id === client.user.id) return

  const {message} = reaction
  const userCount = reactionCount.get(message)
  // subtract 1 from user's reaction count
  if (polls.has(message)) userCount.set(user, reactionCount.get(message).get(user) - 1)
})