discordjs v13搭配@discordjs/voice实现connect命令运行报错求助
错误原因
你遇到的TypeError: Cannot read properties of undefined (reading 'createAudioPlayer')报错,本质是@discordjs/voice模块没有被正确加载:
- 该模块是discord.js v13及以上版本独立拆分的语音功能包,不包含在discord.js核心包中,未主动安装就会导入为undefined
- 若已经安装,大概率是版本和你当前使用的discord.js版本不兼容
修复方案
1. 安装必要依赖
在项目根目录执行以下命令安装语音相关依赖:
npm install @discordjs/voice @discordjs/opus opusscript
其中@discordjs/opus和opusscript是语音编码依赖,避免后续播放音频时出现编码类报错。
2. 修复参数传递不匹配问题
你在connect.js中定义的execute函数接收(interaction, client)两个参数,但在index.js的interactionCreate事件中调用时仅传入了interaction,需要修改index.js对应代码:
// 原代码 await command.execute(interaction); // 修改后 await command.execute(interaction, client);
3. 修复测试阶段的无效代码
你当前createAudioResource传入空字符串,后续执行播放时会触发报错,若仅测试机器人加入语音频道的功能,可暂时注释掉音频播放器相关代码:
// 注释以下内容即可 // const player = voiceDiscord.createAudioPlayer(); // const resource = voiceDiscord.createAudioResource(''); // player.play(resource); // connection.subscribe(player);
后续需要播放音频时,再将空字符串替换为实际的音频文件路径或媒体流地址。
4. 补充交互回复
discord要求斜杠命令必须在3秒内给出回复,否则会提示交互失败,建议你补充两处回复:
- 用户未加入语音频道时,将
interaction.channel.send改为await interaction.reply('请先加入一个语音频道!') - 成功加入频道后,添加
await interaction.reply(已成功加入语音频道 <#${channel.id}>)
内容的提问来源于stack exchange,提问作者Niuoduab
相关产品推荐
相关产品推荐

