反应事件discord.js



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

这是我当前的代码:

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

问题是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,则可以获取消息。现在,您既有消息作者,也有做出反应的用户,所以您可以比较他们的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);
});

尝试这样做:

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

最新更新