有没有办法对使用discord.js发送的每条消息做出反应

时间:2019-07-08 15:12:28

标签: discord discord.js

我想使用机器人通过discord.js f对通道中的每条消息做出反应。我有一个表情符号竞赛频道,我想在其中的每条帖子上都显示✅和✖反应 ofc,清除了所有不必要的邮件,以便有50条邮件

2 个答案:

答案 0 :(得分:1)

const emojiChannelID = 'ChannelIDHere';
client.on('ready', async () => {
  try {
    const channel = client.channels.get(emojiChannelID);
    if (!channel) return console.error('Invalid ID or missing channel.');

    const messages = await channel.fetchMessages({ limit: 100 });

    for (const [id, message] of messages) {
      await message.react('✅');
      await message.react('✖');
    }
  } catch(err) {
    console.error(err);
  }
});
client.on('message', async message => {
  if (message.channel.id === emojiChannelID) {
    try {
      await message.react('✅');
      await message.react('✖');
    } catch(err) {
      console.error(err);
    }
  }
});

在这段代码中,您会注意到我使用的是for...of循环而不是Map.forEach()。其背后的原因是后者将仅调用方法并继续前进。这将导致任何被拒绝的诺言 not 被捕获。我还使用了async/await样式,而不是then()链,这很容易造成混乱。

答案 1 :(得分:0)

根据https://discord.js.org/#/docs/main/stable/class/TextChannel

您可以使用fetchMessages  从特定渠道获取所有邮件,然后该渠道返回Message

的集合

然后,您可以使用.react函数通过对该消息集合进行迭代并在每个消息集合上调用.react来将您的反应应用于此消息集合。

编辑:

channelToFetch.fetchMessages()
    .then(messages => {
        messages.tap(message => {
            message.react(`CHARACTER CODE OR EMOJI CODE`).then(() => {
              // Do what ever or use async/await syntax if you don't care 
                 about Promise handling
            })
        })
    })