Search code examples
javascriptnode.jsdiscord.jsbots

Is there a way to connect a specific Discord.js client to a voice channel?


I'm trying to make a distributed music-playing bot for a single guild/server. This involves a single bot taking in commands from the server members and assigning "loudspeaker" bots to their channels. I currently have a working Discord.js v14 bot that is equipped with doing other things. In its index.html page, I'm able to log in several other "loudspeaker" bot clients after I log in the main bot, and that works fine (the loudspeakers show up as online in the user list).

In an ideal world, I'd like to be able to make a specific bot join a voice channel with loudspeakerClient.voice.join(voiceChannel); or something and have it play music, but that simple of a solution doesn't seem to exist. According to their official voice guide, I have to create a connection and an adapter. Doing the function listed at the top of the page (with a few edits to fit my code)

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
});

causes the main bot to connect to the voice channel. There's no option to select what client to connect through this method. Is there any way to specify a client when performing this function?


Solution

  • So it appears the 'voiceAdapterCreator' is a thing defined by the client that the discord/voice modules uses to connect to channels.

    In this case, you'd want to additionally fetch the guild using whichever client you want to join...

    Let's say there's clientMain, clientA, clientB, etc... and the clients are mapped via a simple obj called 'clientMap': {channelMainId: clientMain, channelAId: clientA, etc...}:

    var thisClient = clientMap[interaction.member.voice.channel.id]
    var channel = await thisClient.channels.fetch(channel.id) // Make sure you add the 'async' keyword to the function
    const { joinVoiceChannel } = require('@discordjs/voice');
    const connection = joinVoiceChannel({
          channelId: channel.id,
          guildId: channel.guild.id,
          adapterCreator: channel.guild.voiceAdapterCreator // Should be referring to the correct client
    });