Discord音乐Bot运行/play命令报Cannot read properties of undefined错误
报错根因
控制台抛出的Cannot read properties of undefined (reading 'voice')属于典型的空值读取错误,触发原因非常明确:
- 代码存在低级拼写错误:第29行写的
interaction.memeber是错误拼写,Discord.js交互对象上的服务器成员属性正确名称为interaction.member,拼写错误导致取到的值为undefined,后续读取undefined的voice属性直接触发类型错误,未捕获的错误直接造成进程崩溃退出。 - 代码执行到错误行直接中断,全程没有对斜杠命令调用响应方法(
reply/deferReply),所以Discord端会一直显示机器人处于思考状态,直到进程崩溃、交互超时。
修复方案
- 第一步:修正属性拼写错误,将代码里的
interaction.memeber替换为正确的interaction.member - 第二步:增加前置校验逻辑,提前判断执行命令的用户是否处于语音频道,避免无意义报错,同时第一时间响应斜杠命令,解决卡思考的问题
修正后的参考代码:
// 提前响应用户命令,避免触发交互超时 await interaction.deferReply(); // 校验用户是否在语音频道 const userVoiceChannel = interaction.member.voice.channel; if (!userVoiceChannel) { return interaction.followUp({ content: "请先加入一个语音频道再使用播放命令", ephemeral: true }); } const queue = await client.player.createQueue(interaction.guild); if (!queue.connection) await queue.connect(userVoiceChannel); // 后续歌曲查询、入队、播放逻辑...
内容的提问来源于stack exchange,提问作者Tyler Lanier
相关产品推荐
相关产品推荐

