rezizdigus
rezizdigus

Reputation: 13

(Discord.js) Select a random user from voice channel

I'm trying to make a bot for voice applications for my server. I want it to have a command that picks a random user from a voice channel. I tried to do it in a few different ways, but none of them have worked, please help.

(edit) Here is my not pretty code

else if (args[0].toLowerCase() === 'pick') {
    const GuildMember = message.guild.members;

    const channels = message.guild.channels.filter(c => c.ID === config.voiceChannel && c.type === 'voice');

    const toCheck = Discord.Collection.array(channels.members);

    message.reply(message.author + ', now pick ' + toCheck.random());
}
message.delete().catch(O_o=>{});

(another edit) This is an error i'm getting "TypeError: Discord.Collection.array is not a function"

Upvotes: 0

Views: 2206

Answers (2)

rezizdigus
rezizdigus

Reputation: 13

Tarazed, thanks for your answer it helped me to figure it out.

For people that want to pick a random person from a voice channel too, here is the code that you can put in you command:

const GuildMember = message.guild.members;

const channel = message.guild.channels.get('voiceChannelID'); //replace voiceChannelID with your voice Channel ID

let toCheck = channel.members;

message.reply('a random person: ' + toCheck.random());

Upvotes: 0

Tarazed
Tarazed

Reputation: 2665

Your error is telling you that you are not using Collecion.array() properly. It looks as though you are trying to use it as a constructor or factory method, but it's a converter function. It needs an existing collection to work.

Secondly, your filter method will return a collection. Since you are filtering by an ID, it should be a collection of 1, but still a collection. Collections do not have a members property so channels.members is undefined. You need to extract the first (and what should be only) channel from the collection.

Fortunately, all of this can be handled by replacing a single line. You don't even need to convert it to an array because VoiceChannel.members is also a collection, and Collection has a random function of it's own.

const toCheck = channels.first().members;

On another note, because you are filtering the channel by it's unique ID, filtering by c.type is redundant. It will always be a voice channel unless you misconfigured config.voiceChannel.

Update It also occured to me after posting that you could use this instead of your filter:

const channel = message.guild.channels.get(config.voiceChannel);

This returns the single channel, rather than a collection, by ID and is better because you aren't iterating over the collection and it simplifies the code. If you do this you don't need to use the changed line above at all, remove that line and use the following:

message.reply(message.author + ', now pick ' + channel.members.random()); 

Upvotes: 1

Related Questions