Reputation: 113
I have been making a music discord bot and I wanted to check if the user is in the same voice channel as the bot.
I tried the following but it didn't work:
let voiceBot = client.voice.connections.channel;
const voiceChannel = msg.member.voice.channel;
if(!voiceBot == voiceChannel)
return msg.channel.send('you need to be in the same channel as the bot!')
Upvotes: 1
Views: 2130
Reputation: 23189
As voice.connections
is a collection of connections, you can use the .some()
method to iterate over these connections and check if any of the connection's channel has the same channel.id
as the member.voice.channelID
.
The .some()
method will return true
if the member and the bot is in the same channel, false
otherwise. So you can use it like this:
const inSameChannel = client.voice.connections.some(
(connection) => connection.channel.id === msg.member.voice.channelID
)
if (!inSameChannel)
return msg.channel.send('You need to be in the same channel as the bot!')
Upvotes: 1
Reputation: 183
client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id);
This will loop through the list of voice channels that the bot is currently in and check the channel id against the id of the message author's current voice channel. It will return the channel object, or undefined
if nothing is found. You can use it inside of an if statement if you just want to check the ids:
if (!client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id)) {
console.log("The member isn't in a shared voice channel!");
};
Or define it as a constant and get other information from it:
const vc = client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id);
if (vc) { //If the channel is valid
console.log(`The voice channel id is: ${vc.channel.id}`);
} else { //If the channel is undefined
console.log("The member isn't in a shared voice channel!");
};
Upvotes: 1