【问题标题】:Reaction event discord.js反应事件 discord.js
【发布时间】:2021-06-21 21:37:57
【问题描述】:

我正在尝试用我的机器人制作右舷代码,其他一切都运行良好。但我正试图让机器人忽略实际消息作者的反应。

这是我当前的代码:

client.on('messageReactionAdd', (reaction_orig, message, user) => {
  if (message.author.id === reaction_orig.users.id) return

  manageBoard(reaction_orig)
})

它返回以下错误:

if (message.author.id === reaction_orig.users.id) return;
                   ^
TypeError: Cannot read property 'id' of undefined

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    尝试这样做:

    client.on('messageReactionAdd', (reaction, user) => {
        if (!reaction.message.author.id === user.id){
            //Do whatever you like with it
            console.log(reaction.name)
        }
    });
    

    注意:消息必须被缓存。为此,您需要这样做

    Client.channels.cache.get("ChannelID").messages.fetch("MessageID");
    

    我猜你正在使用 discord.js v12

    【讨论】:

      【解决方案2】:

      问题是messageReactionAdd有两个参数;消息反应为第一个,应用表情符号的用户为第二个。当你写reaction_orig, message, user 时,reaction_orig 是反应(这是正确的),但message 是反应的用户,因为它是第二个参数。 user 变量将是 undefined

      另一个问题是reaction_orig.users 返回一个没有id 属性的ReactionUserManager。幸运的是,user 已经传递给您的回调,因此您可以使用它的 ID。

      另外,reaction_orig 有一个 message 属性,这是此反应所指的原始消息,因此您可以从中获取其作者的 ID。

      您可以将您的代码更改为此工作:

      client.on('messageReactionAdd', (reaction_orig, user) => {
        if (reaction_orig.message.author.id === user.id) {
          // the reaction is coming from the same user who posted the message
          return;
        }
      
        manageBoard(reaction_orig);
      });
      

      但是,上面的代码仅适用于缓存消息,即在机器人连接后发布的消息。对旧消息做出反应不会触发 messageReactionAdd 事件。如果您还想听取对旧消息的反应,则需要在实例化客户端时启用 MESSAGECHANNELREACTION 的部分结构,如下所示:

      const client = new Discord.Client({
        partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
      });
      

      您可以检查消息是否被缓存,例如检查其author 属性是否不是null。如果是null,你可以fetch the message。现在,您拥有消息作者和做出反应的用户,因此您可以比较他们的 ID:

      // make sure it's an async function
      client.on('messageReactionAdd', async (reaction_orig, user) => {
        // fetch the message if it's not cached
        const message = !reaction_orig.message.author
          ? await reaction_orig.message.fetch()
          : reaction_orig.message;
      
        if (message.author.id === user.id) {
          // the reaction is coming from the same user who posted the message
          return;
        }
        
        // the reaction is coming from a different user
        manageBoard(reaction_orig);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-08
        • 2021-02-07
        • 2021-01-28
        • 2021-12-30
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        相关资源
        最近更新 更多