Salah
Salah

Reputation: 953

Discord bot get number of users in all channels

Im not good with javascript but i have been trying to get count number of users in all voice channels. For example: if 2 users in 'voice channel 1' and 1 user in 'voice channel 2' I want to print number 3 in console which is all users in voice channels.

var Count;
for(Count in bot.users.array()){
   var User = bot.users.array()[Count];
   console.log(User.username);
}

This code print all members(online/offline) name in console, But i don't know how to get number of only users in voice channels.

Upvotes: 0

Views: 8595

Answers (2)

Ahmet Gokpinar
Ahmet Gokpinar

Reputation: 11

If you don't want to use this inside an event but use in an embed,message etc; here is my solution. I used @slothiful 's solution but made a bit change.

// I used my "message" property. You can change it with yours.
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;

for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;

message.channel.send(count);

Upvotes: 0

slothiful
slothiful

Reputation: 5623

You can filter (Collection.filter()) all the channels in the guild (Guild.channels) to retrieve a Collection of only voice channels. Then, you can iterate through each channel and add the number of members connected to it to the count.

// Assuming 'newMember' is the second parameter of the event.
const voiceChannels = newMember.guild.channels.filter(c => c.type === 'voice');
let count = 0;

for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;

console.log(count);

Upvotes: 2

Related Questions