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.
CodePudding user response:
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.
CodePudding user response:
I've had to grab all of the channels and filter out the voice channels before, so I just grabbed that code and flipped it around and added some random to it.
What I did:
let channels = Array.from(message.guild.channels.cache.keys());
const c = channels.filter(v => interaction.guild.channels.resolve(v).isVoice() == true);
const index = Math.floor(Math.random() * c.length);
const randomVoiceChannel = c[index];
The first line grabs all of the channels in the server.
The 2nd line removes the non-voice channels.
And finally the last 2 lines generate a random index from the array and outputs a value.
...
const randomVoiceChannel = Array.from(interaction.guild.channels.cache.keys()).filter(v => interaction.guild.channels.resolve(v).isVoice() == true)[Math.floor(Math.random() * Array.from(interaction.guild.channels.cache.keys()).filter(v => interaction.guild.channels.resolve(v).isVoice() == true).length)];
nifty 1-liner (please dont use this its incredibly unreadable i just thought it was funny)