(Discord.js) How do i get all the members connected to the voice channels of a category?

Raphaël Scellier picture Raphaël Scellier · Jun 12, 2019 · Viewed 17.2k times · Source

So, i'm making a command called "movedebat" to move all the members connected to the voice channels of a channel category to a channel dedicated to debates.

To achieve my goal, I am trying to get the list of all the connected members, to then use a for(member in members) loop and move each one of the members.

    let debate_channel = message.guild.channels.find(c => c.id === '497910775512563742');
    let group_of_channels = message.guild.channels.find(c => c.id === '497908108803440653');
    let connected_members = message.guild.channels.filter((c => parentID === group_of_channels.id)&&(c => c.type == 2)).members;
    if(message.member.permissions.has('ADMINISTRATOR')){
        for(connected_member in connected_members){
            console.log(connected_member.id); 
            connected_member.setVoiceChannel(debate_channel)
                .then(() => console.log(`Moved ${connected_member.displayName}`))
                .catch(console.error);
        }
    }

The problem is that it doesn't work at all. I do not get any error, neither by the bot itself in discord or in the console. The only thing I get is a warning DeprecationWarning: Collection#filterArray: use Collection#filter instead, but I Googled it and people seemed to say it was not important. i think that the problematic line is the 'let connected_members(...)members;' one. I should mention that i expect to see at least 1 member id in my console, but i don't get any, that means that the for loop is not 'executed'.

Thank you for reading me, I hope someone can help ! ^^

Answer

slothiful picture slothiful · Jun 13, 2019
  • When you declare connected_members, you should use a single function in Collection.filter().

  • Collection.filter() returns another Collection, of which members is not a property. You'll have to iterate through each channel to get its members.

  • for...in "iterates over all non-Symbol, enumerable properties of an object" (MDN). In a Collection (Map), the elements aren't properties, but key-value pairs. You can use for...of instead in this context.

if (message.member.permissions.missing('ADMINISTRATOR')) return;

const channels = message.guild.channels.filter(c => c.parentID === '497908108803440653' && c.type === 'voice');

for (const [channelID, channel] of channels) {
  for (const [memberID, member] of channel.members) {
    member.setVoiceChannel('497910775512563742')
      .then(() => console.log(`Moved ${member.user.tag}.`))
      .catch(console.error);
  }
}

Side note: Use Map.get() for finding a value from a Collection by its ID.