如何指定特定Discord.js客户端连接语音频道?
如何在Discord.js v14中指定特定客户端调用joinVoiceChannel?
问题描述
我正在为单个Discord服务器开发分布式音乐播放机器人,设计逻辑是主机器人接收指令,分配“扬声器”机器人到对应频道。目前已经实现了在index.html中登录多个“扬声器”机器人客户端,且它们都能正常显示在线状态。
原本想通过类似loudspeakerClient.voice.join(voiceChannel);的方式让指定机器人加入语音频道播放音乐,但这个方案行不通。按照Discord.js官方语音指南,需要用以下代码创建连接和适配器:
const channel = interaction.member.voice.channel; const { joinVoiceChannel } = require('@discordjs/voice'); const connection = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, adapterCreator: channel.guild.voiceAdapterCreator });
但这段代码会让主机器人连接语音频道,而JoinVoiceChannelOptions里没有指定客户端的选项,请问有没有办法执行该函数时指定特定的客户端?
解决方案
要让指定的“扬声器”机器人调用joinVoiceChannel,核心是使用该客户端实例对应的guild对象的voiceAdapterCreator,而不是主机器人获取到的guild对象。具体步骤如下:
- 首先,把所有登录的“扬声器”客户端存储在一个可索引的结构中,方便快速查找目标客户端:
// 用对象存储客户端,key可以是机器人ID或自定义标识 const speakerClients = { speaker001: clientInstance1, speaker002: clientInstance2 };
- 通过标识找到目标客户端,再获取该客户端对应的服务器
guild对象:
// 替换成你的目标客户端标识和服务器ID const targetSpeaker = speakerClients.speaker001; const targetGuild = targetSpeaker.guilds.cache.get('你的服务器ID');
- 获取要加入的语音频道,调用
joinVoiceChannel时传入目标客户端guild的voiceAdapterCreator:
const { joinVoiceChannel } = require('@discordjs/voice'); const targetChannel = targetGuild.channels.cache.get('目标语音频道ID'); const connection = joinVoiceChannel({ channelId: targetChannel.id, guildId: targetGuild.id, // 关键:使用目标客户端绑定的服务器适配器 adapterCreator: targetGuild.voiceAdapterCreator });
原理是voiceAdapterCreator是绑定到特定客户端的服务器实例上的,用哪个客户端的guild对象的适配器,就会让哪个客户端发起语音连接。
内容的提问来源于stack exchange,提问作者CombustibleToast
相关产品推荐
相关产品推荐

