Discord.JS - Moving users in Discord to your VC using roles

Viewed 96

I'm trying to move all users from a VC with a specific role, for example: !summon @role

With that, all users with that specific role should come to the VC where the user typed that command

At the moment my code looks like this:

else if (command === 'summon') {
                    const channel = message.member.voice.channel;
                    message.guild.members.cache.forEach(member => {
                        member.voice.setChannel(channel);
                    });
                    message.channel.send(`${message.author} users moved to your channel!`);
                }

At the moment i'm moving all users, however I only want users with the informed role

I tried to use:

                    message.mentions.roles.forEach(member => {
                        member.setChannel(channel);
                    });

But without success... can someone help me with this problem?

1 Answers

You can try replacing

message.guild.members.cache.forEach(member => {
    member.voice.setChannel(channel);
});

with

message.guild.members.cache.forEach(member => {
    if(member.roles.cache.has(message.mentions.roles.first()) {
        member.voice.setChannel(channel);
    }
}

Since member.roles.cache is a Collection it has a function .has. We take the first role mention from the message using message.mentions.roles.first() and check if it exists in the user's current roles using member.roles.cache.has(). If the user does have the first role mentioned in the message, the function returns true and we can move the to the specified channel. Hope this helps, don't forget about https://discord.js.org/#/docs for some documentation, can be quite useful .

Related