discord.js v13石头剪刀布命令用户反应不生效问题求解
问题原因与解决方案
核心原因:discord.js v13 网关意图与部分结构配置缺失
discord.js v13 开始要求开发者显式声明所有需要使用的网关事件意图,且未缓存的消息、反应类事件需要开启部分结构(Partials)才能触发,你没有配置对应参数的情况下,机器人无法接收用户添加反应的事件,因此awaitReactions无法收集到有效反应,最终触发超时逻辑。
修复步骤
1. 调整客户端初始化配置
在你创建client实例的代码处,添加GUILD_MESSAGE_REACTIONS意图和对应的部分结构配置,示例如下:
const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, // 接收服务器消息反应事件的必填意图 ], partials: ['MESSAGE', 'REACTION'] // 兼容未缓存的消息、反应事件触发 });
2. 修复你原有代码中的语法&逻辑错误
你的代码还存在以下可运行问题:
- 引入的discord变量大小写不统一,你代码开头引入的是小写
discord,后续创建Embed时写的是大写Discord,会抛出未定义错误 - 结果Embed的内容写反,把机器人的选择填到了用户选择的字段中
setTitle方法只支持1个参数,多余传入的表情参数不会生效- 代码开头的
You lost! :confused:")是残留的无效代码,需要补全youLostEmbed的定义
修正后的完整命令代码如下:
const discord = require('discord.js'); // 补全你缺失的相关Embed定义 const youLost = new discord.MessageEmbed() .setDescription("You lost! :confused:") .setColor(colors.COLOR); const youWin = new discord.MessageEmbed() .setDescription("You win! :tada:") .setColor(colors.COLOR); const resultTie = new discord.MessageEmbed() .setDescription("Tie! :neutral_face:") .setColor(colors.COLOR); const noResponse = new discord.MessageEmbed() .setDescription("Choose a reaction to play Rock Paper Scissors!") .setColor(colors.COLOR); const cancelled = new discord.MessageEmbed() .setDescription(":x: Cancelled! You failed to respond in time!") .setColor(colors.COLOR); module.exports = { name: "rps", aliases: [], async execute(client, message, args) { const msg = await message.channel.send({ embeds: [noResponse] }); // 批量添加反应避免顺序混乱 await Promise.all([ msg.react("🪨"), msg.react("✂️"), msg.react("📰") ]); const filter = (reaction, user) => { return ['🪨', '✂️', '📰'].includes(reaction.emoji.name) && user.id === message.author.id; } const choices = ['🪨', '✂️', '📰']; const botChoice = choices[Math.floor(Math.random() * choices.length)]; try { const collected = await msg.awaitReactions({ filter, max: 1, time: 20000, errors: ['time'] }); const userReaction = collected.first(); const result = new discord.MessageEmbed() .setTitle(`Results: ${userReaction.emoji.name} vs ${botChoice}`) .addField("Your choice:", userReaction.emoji.name) .addField("Bot's choice:", botChoice) .setColor(colors.COLOR); await msg.edit({ embeds: [result] }); if ((botChoice === "🪨" && userReaction.emoji.name === "✂️") || (botChoice === "✂️" && userReaction.emoji.name === "📰") || (botChoice === "📰" && userReaction.emoji.name === "🪨")) { return message.channel.send({ embeds: [youLost] }); } else if (botChoice === userReaction.emoji.name) { return message.channel.send({ embeds: [resultTie] }); } else { return message.channel.send({ embeds: [youWin] }); } } catch (err) { return message.channel.send({ embeds: [cancelled] }); } } }
内容的提问来源于stack exchange,提问作者QuaBot
相关产品推荐
相关产品推荐

