You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discordjs v13搭配@discordjs/voice实现connect命令运行报错求助

错误原因

你遇到的TypeError: Cannot read properties of undefined (reading 'createAudioPlayer')报错,本质是@discordjs/voice模块没有被正确加载:

  1. 该模块是discord.js v13及以上版本独立拆分的语音功能包,不包含在discord.js核心包中,未主动安装就会导入为undefined
  2. 若已经安装,大概率是版本和你当前使用的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:54:07