Search code examples
javascriptnode.jsdiscorddiscord.js

How do you get a random voice channel ID?


I am making a discord chatbot, but something I would like it to do is to join a random voice channel. I have tried the following from a different example, but you need to specify a channel ID. Which doesn’t suit my needs.

const channel = message.guild.channels.get('voiceChannelID'); 

I've also tried this from Check if a channel is a voice channel but it also requires a specific channel ID.

const channelObject = message.guild.channels.cache.get('channel id here'); // Gets the channel object
if (channelObject.type === 'voice') return; // Checks if the channel type is voice 

It would be greatly appreciated if you could answer with some code that would find a random voice channel.


Solution

  • You can fetch all channels, filter them by their type and use Collection#random() to pick a random one from the returned collection:

    let channels = await message.guild.channels.fetch();
    let voiceChannels = channels.filter(ch => ch.type === 'GUILD_VOICE');
    let randomVoiceChannel = voiceChannels.random();
    

    Please note that in discord.js v13, VoiceChannel#type is GUILD_VOICE instead of voice. For more info see this answer.


    Update: If you're using discord.js v12, you can use the following:

    let channels = message.guild.channels.cache;
    let voiceChannels = channels.filter((ch) => ch.type === 'voice');
    let randomVoiceChannel = voiceChannels.random();
    

    ... and it's probably time to upgrade :)