【问题标题】:How to make a raw event run only once如何使原始事件只运行一次
【发布时间】:2021-06-29 08:17:13
【问题描述】:

我有一个原始事件:

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));
                }
            });
        });

当添加一个反应时,此事件会不断发送垃圾邮件,我想制作它,因此如果您做出反应,它将运行一次。我该怎么做?

【问题讨论】:

  • 确保彼此之间没有多个事件!

标签: discord.js


【解决方案1】:

您不应使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2022-07-06
    相关资源
    最近更新 更多