【问题标题】:Bot replying multiple times when triggered by reaction机器人在被反应触发时多次回复
【发布时间】:2020-09-06 01:36:23
【问题描述】:

现在我正在制作一个不和谐机器人(discord.js 版本 12)。

它是这样工作的:

  • 有人发送和侮辱
  • 如果侮辱包含在列表中(存储在 insultes.json),机器人会发送消息并添加反应
  • 如果我们添加相同的反应,机器人会发送另一条消息

我面临的问题是,如果我继续添加反应,机器人会继续回复 2、3、4 次等等:每次 (n) 我检查它回复的 n+1 条消息的反应。

这是代码:

bot.on('message', message => {
  const insulte = require('./insultes.json');

  for (let p = 0; p < insulte.length; p++) {
    // Check if the insult is in the list and make sure it's not from the bot itself
    if (message.content.toLowerCase().includes(insulte[p]) && message.author.id !== "711337757435363468") {
      message.channel.send("First message").then(messageReaction => {
        messageReaction.react("➡️");
      });

      bot.on('messageReactionAdd', (reaction, user) => {
        if (reaction.emoji.name === "➡️" && user.id !== "711337757435363468") {
          message.channel.send("Additional message");
        }
      });
    }
  }
});

【问题讨论】:

    标签: node.js discord.js


    【解决方案1】:

    我认为您的问题来自您使用 bot.on('messageReactionAdd', ... 的事实:这意味着每次运行该部分代码时,代码都会添加另一个侦听器,该侦听器会与您之前使用的侦听器相加。

    此外,当添加对任何消息的反应时,该代码将触发,而不仅仅是您发送的消息。

    根据您的问题,我不明白机器人是否应该在您每次点击该消息的反应时回复一条消息,或者只执行一次然后忽略该消息。我假设是后者。

    这是我的看法:

    bot.on('message', message => {
      const insults = require('./insultes.json')
    
      if (insults.some(i => message.content.toLowerCase().includes(i)) && message.author.id !== "711337757435363468") {
        message.channel.send("First message").then(myMsg=> {
          myMsg.react("➡️");
    
          let reactionFilter = (reaction, user) => reaction.emoji.name === '➡️' && user.id !== "711337757435363468"
          myMsg.awaitReactions(reactionFilter, { max: 1 }).then(() => {
            myMsg.channel.send('Additional message')
          })
        });
      }
    })
    

    如您所见,我使用Array.some() 来检查消息中是否有任何侮辱,而不是for 循环。我正在使用Message.awaitReactions() 获取第一反应并做出回应:之后,机器人将忽略对该消息的任何其他反应,但仍会对其他人起作用。

    如果有什么不清楚或不起作用,请随时告诉我:)

    【讨论】:

    • 这是 100% 的工作 非常感谢你帮助我! :D
    • @Drakeu0909 我很高兴听到这个消息!在 Stack Overflow 中,当一个答案解决了您的问题时,您可以通过单击左侧的勾号来接受它:这样您的问题将被标记为已回答,因此每个人都会知道他们不需要发布另一个答案;)
    • 好的,但我还有一个问题,我希望在触发反应时发送消息,但只能由消息作者(发送侮辱的人)发送
    • 别担心我找到了
    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 2022-10-30
    • 2023-04-07
    • 2021-09-14
    • 2019-05-29
    • 2020-03-27
    • 2013-08-13
    • 1970-01-01
    相关资源
    最近更新 更多