Skip to content Skip to sidebar Skip to footer

Code Returns All Members And Not The Members In The Role

This is the code: let getMembers = message.guild.members.cache.filter(member => { return message.guild.roles.fetch('701142571623252018'); }).map(member => { return me

Solution 1:

That's because your filter function is not returning whether the member has the role or not: it's returning a Promise which should resolve into a Role, which is interpreted as true and so everything passes the filter.

You don't actually need to fetch the role, since you only need to check if that ID is one of the roles from of the member: to do that you can use GuildMember.roles.cache.has(), which will return whether the roles collection has a role with that ID.

Here's how you can do it:

message.guild.members.cache.filter(member => member.roles.cache.has('701142571623252018'))
  .map(member => member.user.username)

Solution 2:

You can use filter and method collection.some for check if member has role.

bot.on('message', (message) => {
    const targetRole = message.guild.roles.cache.get('ROLE ID');
    if (!targetRole) returnconsole.log('No role found')
    const members = message.guild.members.cache.filter((member) => member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)
});

V2

constDiscord = require('discord.js')
const bot = newDiscord.Client();

bot.on('message', (message) => {
    const targetRole = message.guild.roles.cache.get('648157497051447317');
    if (!targetRole) returnconsole.log('No role found')
    const members = message.guild.members.cache.filter((member) => member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)
    console.log(members)
});

bot.login('TOKEN HERE')

Post a Comment for "Code Returns All Members And Not The Members In The Role"