Discord.js音乐机器人.play命令报Cannot read property 'voice' of undefined求助
问题排查与修复方案
根因定位
报错Cannot read property 'voice' of undefined是参数传递顺序不匹配导致的:
play.js中execute方法定义的参数顺序为:async execute(client, message, args, cmd, Discord)- 命令处理器中调用
execute时的传参顺序为:.execute(message, args, client, Discord)
参数顺序错位后,play.js里的message变量实际接收到的是args数组,访问message.member自然返回undefined,读取voice属性就触发了报错。同时代码还漏传了cmd参数,会导致后续命令匹配逻辑失效。
修复步骤
1. 修正命令处理器的传参顺序
修改命令处理器中的execute调用代码,把参数顺序和play.js的定义对齐,同时补上cmd参数:
// 替换原有的execute调用代码 try { // 补充await捕获异步抛出的错误,同时对齐参数顺序、补传cmd参数 await client.commands.get(command).execute(client, message, args, command, Discord); } catch (error) { console.error(error); message.reply(`Si è verificato un errore durante l'esecuzione del comando...`); }
2. 优化play.js冗余判断(可选)
现有代码中同时写了if (voice_channel != null)和if (!voice_channel)逻辑重复,可简化为:
const voice_channel = message.member.voice.channel; // 直接统一判断用户是否在语音频道 if (!voice_channel) { return message.reply("Devi essere in un canale vocale."); }
3. 其他注意事项
- 当前音量调整逻辑是全局生效的,会同时修改所有服务器的播放音量,建议把音量参数放到每个服务器的
queue_constructor对象中单独存储 - 如果你后续升级到Discord.js v13及以上版本,语音相关逻辑需要替换为
@discordjs/voice库,原有voice_channel.join()方法会失效
内容的提问来源于stack exchange,提问作者maiku
相关产品推荐
相关产品推荐

