【问题标题】:Add Users Who React To Reaction To Embed将对反应做出反应的用户添加到嵌入
【发布时间】:2021-08-02 23:35:37
【问题描述】:

试图制作一个机器人,当用户点击反应时,discord id 会进入嵌入字段,如果他们取消点击或点击另一个表情符号,他们最终会进入该字段。这将用于投票机器人,一旦一定数量的用户单击“是”或“否”,将做出接受用户或拒绝用户的决定。有什么帮助吗?

exports.run = async (client, message, args) => {
  message.delete({ timeout: 100 });
  if (!args[0]) return message.reply('You need to supply the question');

  let embed = new Discord.MessageEmbed()
    .setTitle(args.join(' '))
    .setDescription('Poll created by ' + message.author.tag)
    .addField('Status', 'Voting is currently open.')
    .setColor('#ffd700')
    .attachFiles(new Discord.MessageAttachment('https://i.imgur.com/QUmbq9o.png', 'thumbnail.png'))
    .setThumbnail('attachment://thumbnail.png')
    .setFooter('Bot created by James (Rock)₇₇₇');

  message.channel.send(embed).then(async msg => {
    await msg.react('????');
    await msg.react('????');
    await msg.react('????');
    await msg.react('????️');

    const threshold = 6;

    async function stop(result) {
      collector.stop();

      const newEmbed = new Discord.MessageEmbed(msg.embeds[0]);

      newEmbed.title = newEmbed.title + ' [CLOSED]';
      newEmbed.fields[0] = { name: 'Status', value: 'Voting is now closed.\n' + result };
      newEmbed.setThumbnail('attachment://thumbnail.png');
      await msg.edit(newEmbed);

      msg.reactions.removeAll();
    }

    async function update() {
      const newEmbed = new Discord.MessageEmbed(embed);

      const userYes = (votes['????'].size === 0)? '-' : [...votes['????']];
      const userNo = (votes['????'].size === 0)? '-' : [...votes['????']];
      const userUnsure = (votes['????'].size === 0)? '-' : [...votes['????']];

      newEmbed.addFields(
        { name: `User Yes (${votes['????'].size}/${threshold})`, value: userYes, inline: true },
        { name: `User No (${votes['????'].size}/${threshold})`, value: userNo, inline: true },
        { name: 'User Unsure', value: userUnsure, inline: true }
      );

      await msg.edit(newEmbed);

      if (votes['????'].size >= threshold) {
        await stop('This answer is good enough to get accepted and an upvote.');
        // do something
      } else if (votes['????'].size >= threshold) {
        await stop('This answer is not good enough to get accepted and an upvote.');
        // do something
      }
    }

    const votes = {
      '????': new Set(),
      '????': new Set(),
      '????': new Set(),
      '????️': new Set()
    };

    update();

    const collector = msg.createReactionCollector((reaction, user) => !user.bot , { dispose: true });

    collector.on('collect', async (reaction, user) => {
      if (['????', '????', '????', '????️'].includes(reaction.emoji.name)) {
        const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));

        for (const userReaction of userReactions.values()) {
          if (userReaction.emoji.name !== reaction.emoji.name || reaction.emoji.name === '????️') {
            userReaction.users.remove(user.id);
            votes[userReaction.emoji.name].delete(user);
          }
        }

        votes[reaction.emoji.name].add(user);
      } else {
        reaction.remove();
      }

      update();
    });

    collector.on('remove', (reaction, user) => {
      votes[reaction.emoji.name].delete(user);

      update();
    });
  });

};

module.exports.help = {
  name: "poll"
}

【问题讨论】:

  • 它们最终进入内联字段是什么意思
  • 点击赞许的用户会被放入一个嵌入中,显示那里的每个人用户名投票赞许,或者如果您点击赞许,您的用户名会在该字段中弹出。
  • 您遇到了什么错误?根据您的问题,我无法理解实际问题是什么
  • 嵌入弹出反应弹出,但我希望它输入在频道中点击嵌入内反应的用户名。

标签: node.js discord.js


【解决方案1】:

您可以阅读 discord.js 指南中有关反应收集器的 this 页面,它会告诉您您需要知道的一切。您可以阅读this 了解有关 .createReactionCollector() 方法的更多信息。

制作反应收集器后,有多种方法可以实现您想要的,但我相信最简单的方法如下所示:

message.channel.send('your_message_here')
  .then(async function(message) {
    await message.react('?');
    await message.react('?');
    await message.react('?‍');

    const filter = (reaction, user) => {
      return ['?', '?', '?‍'].includes(reaction.emoji.name) && user.id === ogauthor
    }
    
    const collector = message.createReactionCollector(filter)
    
    collector.on('collect', (reaction, user) => {
      async function collect() {
        if (!user.bot) {
          if (reaction.emoji.name === '?') {
            //code here
          }
          //repeat this for the rest of your reactions
          reaction.users.remove(user.id) //you can remove the reaction once they react to it and their name is added.
        }
      }
      collect()
    });
  })

一个问题是它会永远运行,所以你应该给它添加一个计时器。

【讨论】:

  • 所以我知道您可以收集做出反应的用户,但我如何将其称为嵌入?我试图达到的目标是这样的i.gyazo.com/83fb7d7e810919ea77cf2abf21635546.gif,但用于投票目的。所以你键入命令嵌入弹出说像在部落中投票用户是或否这样就像如果我点击“?”我的名字会显示在那个嵌入中,如果有人点击?那么名字会出现在不同的字段中。也许在第一个字段旁边。
  • @JamesLewis 您可以存储人们的姓名,并在他们做出反应后编辑该字段的值。 Dorian349's answer 几乎解释了您需要了解的内容。
【解决方案2】:

对于这种情况,您可以使用Reaction Collectors 来听取反应并根据它列出它们。

我已经编写了下面的代码,它按预期工作:

message.delete({ timeout: 100 });
if (!args[0]) return message.reply('You need to supply the question');

let embed = new Discord.MessageEmbed()
   .setTitle(args.join(' '))
   .setDescription('Poll created by ' + message.author.tag)
   .setColor('#ffd700')
   .setThumbnail("https://i.imgur.com/QUmbq9o.png")
   .addFields({name: "User Yes", value: 'None'}, {name: "User No", value: 'None'}, {name: "User Hum", value: 'None'})
   .setFooter("Bot created by James (Rock)₇₇₇");


message.channel.send(embed).then(async msg => {
    await msg.react('?');
    await msg.react('?');
    await msg.react('?');
    const filter = (reaction, user) => {
        return ["?", "?", "?"].includes(reaction.emoji.name);
    };

    const collector = await msg.createReactionCollector(filter);

    collector.on('collect', (reaction, user) => {

      const reactionsList = ["?", "?", "?"];
      const fieldTitle = ["User Yes", "User No", "User Hum"];

      var reactions = reaction.message.reactions.cache.array();

      for(var reactionID in reactions) {
        for (var i = 0; i < reactionsList.length; i++) {
          if(reactionsList[i] === reaction.emoji.name){
            let fieldDescription = user.id + "\n";
             var users = reactions[reactionID].users.cache.array();
             for(var userID in users){
               if(users[userID].id === client.user.id || users[userID].id === user.id) continue;
               fieldDescription += users[userID].id + "\n";
             }
             embed.spliceFields(i, 1, {name: fieldTitle[i], value: fieldDescription})
          }
        }
      }

      msg.edit(embed);

    });
})

【讨论】:

    【解决方案3】:

    我稍微修改了您的代码并添加了代码来跟踪投票、编辑嵌入并检查投票何时达到阈值。

    演示

    代码

    message.delete({ timeout: 100 });
    if (!args[0]) return message.reply('You need to supply the question');
    
    let embed = new Discord.MessageEmbed()
      .setTitle(args.join(' '))
      .setDescription('Poll created by ' + message.author.tag)
      .addField('Status', 'Voting is currently open.')
      .setColor('#ffd700')
      .attachFiles(new Discord.MessageAttachment('https://i.imgur.com/QUmbq9o.png', 'thumbnail.png'))
      .setThumbnail('attachment://thumbnail.png')
      .setFooter('Bot created by James (Rock)₇₇₇');
    
    message.channel.send(embed).then(async msg => {
      await msg.react('?');
      await msg.react('?');
      await msg.react('?');
      await msg.react('?️');
    
      const threshold = 1;
    
      async function stop(result) {
        collector.stop();
    
        const newEmbed = new Discord.MessageEmbed(msg.embeds[0]);
    
        newEmbed.title = newEmbed.title + ' [CLOSED]';
        newEmbed.fields[0] = { name: 'Status', value: 'Voting is now closed.\n' + result };
        newEmbed.setThumbnail('attachment://thumbnail.png');
        await msg.edit(newEmbed);
    
        msg.reactions.removeAll();
      }
    
      async function update() {
        const newEmbed = new Discord.MessageEmbed(embed);
    
        const userYes = (votes['?'].size === 0)? '-' : [...votes['?']];
        const userNo = (votes['?'].size === 0)? '-' : [...votes['?']];
        const userUnsure = (votes['?'].size === 0)? '-' : [...votes['?']];
    
        newEmbed.addFields(
          { name: `User Yes (${votes['?'].size}/${threshold})`, value: userYes, inline: true },
          { name: `User No (${votes['?'].size}/${threshold})`, value: userNo, inline: true },
          { name: 'User Unsure', value: userUnsure, inline: true }
        );
    
        await msg.edit(newEmbed);
    
        if (votes['?'].size >= threshold) {
          await stop('This answer is good enough to get accepted and an upvote.');
          // do something
        } else if (votes['?'].size >= threshold) {
          await stop('This answer is not good enough to get accepted and an upvote.');
          // do something
        }
      }
    
      const votes = {
        '?': new Set(),
        '?': new Set(),
        '?': new Set(),
        '?️': new Set()
      };
    
      update();
    
      const collector = msg.createReactionCollector((reaction, user) => !user.bot , { dispose: true });
    
      collector.on('collect', async (reaction, user) => {
        if (['?', '?', '?', '?️'].includes(reaction.emoji.name)) {
          const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
    
          for (const userReaction of userReactions.values()) {
            if (userReaction.emoji.name !== reaction.emoji.name || reaction.emoji.name === '?️') {
              userReaction.users.remove(user.id);
              votes[userReaction.emoji.name].delete(user);
            }
          }
    
          votes[reaction.emoji.name].add(user);
        } else {
          reaction.remove();
        }
    
        update();
      });
    
      collector.on('remove', (reaction, user) => {
        votes[reaction.emoji.name].delete(user);
    
        update();
      });
    });
    

    【讨论】:

    • 兄弟由于某种原因我收到了一个错误。当我执行显示不和谐的代码时,cmd 提示符中没有定义。
    • 您是否在文件的最顶部添加了const Discord = require('discord.js');
    • 是的,我已经更新了我的代码以完全匹配我所拥有的!
    • 你需要const Discord = require('discord.js');在你的文件的最顶部。
    • 我明白了兄弟!非常感谢:)
    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2022-01-04
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多