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

如何实现Discord Bot在消息收到表情反应后发送消息?

实现Discord机器人监听历史消息表情反应并发送新消息

嘿,当然可以实现这个功能啦!不过看你目前的代码里有几个逻辑和语法问题,我来帮你梳理下正确的实现思路和代码:

首先,先说说你现有代码里的问题:

  • do-while循环的语法错误,括号位置不对,而且这种循环写法根本没法监听表情反应(循环会直接执行,不会等待用户操作)
  • 没有监听Discord的表情反应事件,机器人根本感知不到用户加了表情
  • 现在Discord.js v12及以上版本已经废弃RichEmbed,取而代之的是MessageEmbed
  • anotherembed + 1这种写法不成立,Embed对象不能直接和数字拼接

接下来是正确的实现步骤和代码:

1. 先正确初始化Discord客户端

(假设你用的是Discord.js v14,v12/v13写法类似,仅部分API有细微差异)

const { Client, GatewayIntentBits, MessageEmbed } = require('discord.js');
const prefix = '!'; // 替换成你的机器人前缀

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMessageReactions // 必须开启这个intent才能监听表情反应
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

2. 实现!list命令并保存目标消息引用

我们需要把发送的初始Embed消息存起来,这样后续才能识别用户是对这条消息加了反应:

// 用变量存储需要监听反应的消息(多服务器场景建议用Map区分不同服务器的消息)
let targetMessage = null;

client.on('messageCreate', async (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const cmd = message.content.slice(prefix.length);

  if (cmd === 'list') { 
    const embed = new MessageEmbed()
      .addField("List", "Content");
    
    // 发送消息并保存引用
    targetMessage = await message.channel.send({ embeds: [embed] });

    const tipEmbed = new MessageEmbed()
      .addField("提示", "点击✅表情即可触发后续消息!");
    await message.channel.send({ embeds: [tipEmbed] });
  }
});

3. 监听表情反应事件,触发后发送新消息

client.on('messageReactionAdd', async (reaction, user) => {
  // 忽略机器人自己的反应
  if (user.bot) return;
  // 检查是否是我们要监听的目标消息,且表情是✅
  if (reaction.message.id === targetMessage?.id && reaction.emoji.name === "✅") {
    const responseEmbed = new MessageEmbed()
      .addField("Message", "List has been completed!");
    await reaction.message.channel.send({ embeds: [responseEmbed] });
    
    // 如果只想触发一次,可以在这里把targetMessage设为null
    // targetMessage = null;
  }
});

// 登录你的机器人
client.login('你的机器人Token');

额外说明

  • 如果需要监听机器人重启前发送的历史消息反应,要启用partial机制,初始化客户端时加上partials: ['MESSAGE', 'CHANNEL', 'REACTION']
  • 多服务器场景下,建议用Map<string, Message>存储不同服务器的目标消息,避免不同服务器的消息互相干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:58:53