How to check if Discord bot user is in same voice channel before executing commands

I’m working on a Discord bot with voice features and need help with channel validation. Right now I have a working system where the bot can join voice channels through voice recognition. I also created a disconnect command that works from anywhere in the server.

Here’s my current setup:

const discord = require('discord.js-commando');

class ExitVoiceCommand extends discord.Command
{
    constructor(bot){
        super(bot,{
            name: 'exit',
            group: 'audio',
            memberName: 'exit',
            description: 'disconnects from voice channel'
        });
    }
    async run(msg, parameters)
    {
        if(msg.guild.voiceConnection)
        {
            msg.guild.voiceConnection.disconnect();
        }
        else
        {
            msg.channel.sendMessage("bot has left the channel")
        }
    }
}

module.exports = ExitVoiceCommand;

The problem is that anyone can type !exit from any text channel and the bot will leave. I want to restrict this so only users who are currently in the same voice channel as the bot can control it. How can I verify that the message author is in the same voice room before allowing the command to execute?

just check if msg.member.voice.channel matches msg.guild.me.voice.channel. if they don’t match, throw an error and skip the command.

Check if the user’s actually in the voice channel before running any voice commands. Your current code’s missing this validation - you can’t just check if a voice connection exists. I hit this same issue building my music bot last year. Created a helper function that validates voice access first, then call it at the start of every voice command. Just check if msg.member.voice.channel exists and matches msg.guild.me.voice.channel before doing anything else. Skip this and you’ll constantly have users disconnecting the bot from other channels. Super annoying for everyone. Run the validation right after the command triggers but before any voice stuff happens.

Add a check before running the disconnect logic. Grab the user’s voice channel with msg.member.voice.channel and compare it to where the bot’s currently connected:

const userVoiceChannel = msg.member.voice.channel;
const botVoiceChannel = msg.guild.me.voice.channel;

if (!userVoiceChannel || userVoiceChannel.id !== botVoiceChannel.id) {
    return msg.reply('You must be in the same voice channel as the bot to use this command.');
}

This makes sure the user’s actually in a voice channel, then checks if it’s the same one as the bot. Skip this and you’ll have people kicking the bot from random text channels, which gets old real quick.