how to locate the voice chat that the discord bot is connected to

13,048

It's fairly easy to do. All you need to do is grab the bot's voiceChannel and the user's voiceChannel (if he is in one) and check if they are the same.

Below you can find some example code. Give it a try and let me know how it goes.

async run(message, args)
{
  // If the client isn't in a voiceChannel, don't execute any other code
  if(!message.guild.voiceConnection)
  {
    return;
  }

  // Get the user's voiceChannel (if he is in one)
  let userVoiceChannel = message.member.voiceChannel;

  // Return from the code if the user isn't in a voiceChannel
  if (!userVoiceChannel) {
    return;
  }

  // Get the client's voiceConnection
  let clientVoiceConnection = message.guild.voiceConnection;

  // Compare the voiceChannels
  if (userVoiceChannel === clientVoiceConnection.channel) {
    // The client and user are in the same voiceChannel, the client can disconnect
    clientVoiceConnection.disconnect();
    message.channel.send('Client has disconnected!');
  } else {
    // The client and user are NOT in the same voiceChannel
    message.channel.send('You can only execute this command if you share the same voiceChannel as the client!');
  }
}
Share:
13,048

Related videos on Youtube

SwaggZ ReYan
Author by

SwaggZ ReYan

Updated on June 04, 2022

Comments

  • SwaggZ ReYan
    SwaggZ ReYan almost 2 years

    I am making a discord bot that is being activated by voice recognition, im at the very beginning right now im making him join a voice channel (which is working), and im trying to make a command to make him leave.

    const commando = require('discord.js-commando');
    
    class LeaveChannelCommand extends commando.Command
    {
        constructor(client){!
            super(client,{
                name: 'leave',
                group: 'music',
                memberName: 'leave',
                description: 'leaves a voice channel'
            });
        }
        async run(message, args)
        {
            if(message.guild.voiceConnection)
            {
                message.guild.voiceConnection.disconnect();
            }
            else
            {
                message.channel.sendMessage("seccessfully left")
            }
        }
    }
    
    module.exports = LeaveChannelCommand;

    right now you can type !leave from anywhere in the server and the bot leaves, i want to make it possible to control him only from the same voice channel, what should i do

    • Gilles Heinesch
      Gilles Heinesch about 5 years
      Sorry, I don't get what is your question. You want to control the bot from leaving the voice channel in the same voice channel? Can you explain this and I will help you! :-)
  • MacroController
    MacroController over 3 years
    After discord.js v12 (possibly before), it's not message.member.voiceChannel anymore, but message.member.voice.channel, see [stackoverflow.com/a/58329645/7245246]