Discord机器人无法连接语音频道 更换新连接方法后仍未生效
修复方案
- 核心调用逻辑错误:
@discordjs/voice新版库不存在connection.play()方法,你沿用了旧版语音库的调用逻辑,需按照新版规范先创建音频播放器、生成音频资源,再将播放器绑定到语音连接上。 - 搜索逻辑缺陷:
videoFinder中的判断条件写为videoResult.videos.length > 1,仅当搜索结果至少2个时才返回内容,仅1个匹配结果时会直接返回null,需修改为>= 1。 - 依赖缺失:需确认已安装音频必要依赖
@discordjs/opus(或轻量版opusscript)、ffmpeg-static,否则无法完成音频编码输出。 - 网关意图未开启:需要在Discord开发者后台的机器人设置页,开启
GUILD_VOICE_STATES网关意图,否则机器人无法获取语音频道状态,无法完成连接。 - 拼写错误:返回结果里的
redults为笔误,修正为results。
修复后完整代码如下:
const ytdl = require('ytdl-core'); const ytSearch = require('yt-search'); // 提前引入@discordjs/voice所需方法 const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice'); module.exports = { name: 'play', description: '', async execute(message, args){ const voiceChannel = message.member.voice.channel; if (!voiceChannel) return message.channel.send('你需要先进入一个语音频道'); const permissions = voiceChannel.permissionsFor(message.client.user); if (!permissions.has('CONNECT')) return message.channel.send('你没有执行该操作的权限'); if (!permissions.has('SPEAK')) return message.channel.send('你没有执行该操作的权限'); if (!args.length) return message.channel.send('你需要附带搜索关键词或视频链接'); const connection = joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator }); // 创建音频播放器 const player = createAudioPlayer(); // 播放器订阅语音连接 connection.subscribe(player); const videoFinder = async (query) => { const videoResult = await ytSearch(query); // 修正判断条件 return (videoResult.videos.length >= 1) ? videoResult.videos[0] : null; } const video = await videoFinder(args.join('')); if (video){ const stream = ytdl(video.url, {filter: 'audioonly', highWaterMark: 1<<25}); // 生成音频资源 const resource = createAudioResource(stream); // 播放器播放资源 player.play(resource); // 监听播放结束事件 player.on(AudioPlayerStatus.Idle, () => { connection.destroy(); voiceChannel.leave(); }); await message.reply(`正在播放:***${video.title}***`) } else { message.channel.send('未找到匹配的视频结果'); } } }
内容的提问来源于stack exchange,提问作者Demon
相关产品推荐
相关产品推荐

