简体   繁体   中英

Discord.js check if bot is in a voice channel

I have a question: I want to check if the Bot is on a channel in msg.guild. I have a command ?checkchannel that replies whether or not the bot is on a voice channel of said guild. If the bot is on one it should reply: "Is on a voice channel" and if he is not he should reply he isn't.

Thank you.

It's really simple, try this:

// If the bot is not connected to a voice channel, the 'channel' object should be 'undefined'
if(msg.guild.voice.cannel)
  {
    msg.channel.send(`I'm in a voice channel!`);
  }
else
  {
    console.log(`I'm not in a voice channel!`);
  }

Note:

This only checks the channel of the message , not if the bot is connected to any voice channel on the server!

If you want to check, if he's connected to any voice channel you should check out Viriatos answer

Edit:

You can also reduce Vitiaro's answer to a single line:

msg.guild.channels.cache.some(channel => (channel.type === 'voice' && channel.members.has(Client.user.id)) ? msg.channel.send('It is on a voice channel') : msg.channel.send('It is not on a voice channel')

But you have to decide for yourself whether this is clearer or not.


References:

If I understood correctly and you want to check whether the bot is in any voice channel of the guild corresponding to msg.guild :

if(msg.guild.channels.cache.some(channel => (channel.type === 'voice' && channel.members.has(Client.user.id)) {
    msg.channel.send('It is on a voice channel'); // Replies on the same channel the command was sent to
}
else {
    msg.channel.send('It is not on a voice channel');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM