DiscordJS执行!reactionrole命令出现UnhandledPromiseRejectionWarning报错
问题排查与修复方案
核心错误原因
- 拼写错误:在
reactionrole.js文件中,获取Live Notifs和Giveaways角色的代码里,误将message.guild.roles.cache写成了message.guild.role.cache(缺少了表示复数的s),访问不存在的role属性下的cache会直接抛出异常。你的execute是异步函数,没有添加错误捕获逻辑,异常没有被处理就触发了未处理Promise拒绝的报错。 - 次要问题:调用
messageEmbed.react()是异步操作,你没有添加await也没有捕获错误,如果emoji无效、机器人没有添加反应的权限也会触发Promise拒绝;同时没有对找不到的角色做空值判断,如果服务器不存在对应名称的角色,后续调用变量也会出错。
修复后的reactionrole.js代码
module.exports = { name: 'reactionrole', description: "Sets up reaction roles", async execute(message, args, Discord, client) { try { const channel = '796928981047705602'; // 统一使用roles复数,增加空值判断 const uploadNotifs = message.guild.roles.cache.find(role => role.name === "Upload Notifs"); const liveNotifs = message.guild.roles.cache.find(role => role.name === "Live Notifs"); const giveNotifs = message.guild.roles.cache.find(role => role.name === "Giveaways"); if (!uploadNotifs || !liveNotifs || !giveNotifs) { return message.reply('服务器中不存在所需的通知角色,请先检查角色配置'); } // 代码中添加反应需要用原生unicode字符,不要用客户端冒号快捷格式 const uploadNotifsEmoji = '🔔'; const liveNotifsEmoji = '🔴'; const giveNotifsEmoji = '🥳'; let embed = new Discord.MessageEmbed() .setColor('#e42643') .setTitle('Choose what to be notified for!') .setDescription('Select the types of notifications you want to recieve.\n\n' + `${uploadNotifsEmoji} for Upload Notifications\n` + `${liveNotifsEmoji} for Livestream Notifications\n` + `${giveNotifsEmoji} for Giveaway Notifications`); let messageEmbed = await message.channel.send(embed); // 异步操作加await按顺序添加反应 await messageEmbed.react(uploadNotifsEmoji); await messageEmbed.react(liveNotifsEmoji); await messageEmbed.react(giveNotifsEmoji); } catch (err) { console.error('执行reactionrole命令出错:', err); message.reply('执行命令时出现错误,请检查机器人权限配置').catch(console.error); } } }
额外优化建议
建议给命令处理器的execute调用全局添加try/catch逻辑,避免单个命令出错导致整个进程抛出未处理拒绝警告。
内容的提问来源于stack exchange,提问作者Matthew Hayward
相关产品推荐
相关产品推荐

