You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Discord机器人的消息制作Reaction Collector(反应收集器)

Reaction Collector 问题修复方案

修正后完整代码

import { ICommand } from 'wokcommands'
import { Message, MessageEmbed, MessageReaction, User } from 'discord.js'

export default {
    category: 'Testing',
    description: 'Tests the collector system',
    hidden: true,

    // 给回调添加async标识支持await语法
    callback: async ({ message, channel }) => {
        const answerUsernameEmbed = new MessageEmbed()
        .setTitle('Please confirm this action')
        .setColor('#1be730')
        // 等待消息发送完成,拿到机器人发送的消息实例
        const newMessage = await message.reply({
            embeds: [answerUsernameEmbed]
        })
        // 给机器人自己的消息加反应
        await newMessage.react('👍')

        const filter = (r: MessageReaction, user: User) => {
            return user.id === message.author.id
        }

        // 收集器绑定到机器人发送的消息上,而非用户的触发消息
        const collector = newMessage.createReactionCollector({
            filter,
            max: 1,
            time: 1000 * 10,
        })

        collector.on('collect', reaction => {
            console.log(reaction.emoji.name)
        })
        
        collector.on('end', collected => {
            if (collected.size === 0) {
                const badCollector = new MessageEmbed()
                .setTitle('You did not react in time...')
                .setColor('#ff0000')
                message.reply({
                    embeds: [badCollector]
                })
                return
            }

            let text = 'Collected:\n\n'
            // 修复变量命名冲突,不要和外层的message变量重名
            collected.forEach((reaction) => {
                text += `${reaction.emoji.name}\n`
            })

            message.reply(text)
        })
    }
} as ICommand

修改说明

  • 回调函数添加async标识,支持await异步操作,避免嵌套then的作用域问题
  • 用await直接接收机器人发送的消息实例newMessage,无需在then回调里处理逻辑,所有同级作用域都可以访问该变量
  • 反应收集器绑定到机器人发送的newMessage上,只会收集该消息下的用户反应
  • 修复原代码end事件中遍历collected时的变量命名错误:原代码把遍历到的反应对象命名为message,和外层用户触发命令的message变量冲突,是将收集器放入promise内部时报错的核心原因
  • 给newMessage.react也添加await,确保反应添加成功后再启动收集器,逻辑更严谨

内容的提问来源于stack exchange,提问作者PrezOfTheUnitedIdiots

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:09:01