discord.js - 如何使原始事件只运行一次

标签 discord.js

我有一个原始事件:

this.on('raw', packet => {
            if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
            const channel = this.channels.cache.get(packet.d.channel_id);
            if (channel.messages.cache.has(packet.d.message_id)) return;
            channel.messages.fetch(packet.d.message_id).then(message => {
                const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
                const reaction = message.reactions.cache.get(emoji);
                if (reaction) reaction.users.cache.set(packet.d.user_id, this.users.cache.get(packet.d.user_id));
                if (packet.t === 'MESSAGE_REACTION_ADD') {
                    this.emit('messageReactionAdd', reaction, this.users.cache.get(packet.d.user_id));
                }
                if (packet.t === 'MESSAGE_REACTION_REMOVE') {
                    this.emit('messageReactionRemove', reaction, this.users.cache.get(packet.d.user_id));
                }
            });
        });

当添加一个 react 时,此事件会不断发送垃圾邮件,我想这样做,如果您使用react,它就会运行一次。我该怎么做?

最佳答案

您不应使用 discord.js 版本 12 之后的原始事件。因为当您的机器人增长时会出现一些问题。

而是按照官方 Discord.js 指南中的说明使用 Partials

const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.on('messageReactionAdd', async (reaction, user) => {
    // When we receive a reaction we check if the reaction is partial or not
    if (reaction.partial) {
        // If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
        try {
            await reaction.fetch();
        } catch (error) {
            console.error('Something went wrong when fetching the message: ', error);
            // Return as `reaction.message.author` may be undefined/null
            return;
        }
    }
    // Now the message has been cached and is fully available
    console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
    // The reaction is now also fully available and the properties will be reflected accurately:
    console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
});

来源和更多信息:https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages

关于discord.js - 如何使原始事件只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66919652/

相关文章:

javascript - 消息嵌入 : Cannot read property 'client' of undefined

javascript - Discord.js : reaction. message.guild.members.find 不是函数

javascript - 为用户添加 channel 权限

javascript - Discord JS(机器人存在)

discord - 是否可以在一条消息中发送多个 RichEmbeds

javascript - 在创建不和谐机器人时遇到 .disconnect() 问题

javascript - 获取提供旧数据的变量

javascript - 如何修复机器人在 DM 中请求 id,JavaScript 中的 discord bot

javascript - 如何使用discord.js获取用户当前的语音 channel ?

javascript - DiscordAPI错误: Unknown Message