1

This is the code:

let getMembers = message.guild.members.cache.filter(member => {
    return message.guild.roles.fetch('701142571623252018');
}).map(member => {
    return member.user.username;
});

It returns all members in the server, but not the members in the specific role, which it is supposed to do.

This is my full code:

    const targetRole = message.guild.roles.cache.get('701142571623252018');
    if (!targetRole) return console.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)

    const players = new Discord.MessageEmbed()
      .setColor('#6B238E')
      .setTitle("Players:")
      .setDescription(members);

    message.channel.send(players);
    //console.log(members);
Johonny
  • 151
  • 1
  • 4
  • 17

2 Answers2

2

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)
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
0

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) return console.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

const Discord = require('discord.js')
const bot = new Discord.Client();

bot.on('message', (message) => {
    const targetRole = message.guild.roles.cache.get('648157497051447317');
    if (!targetRole) return console.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')
Cipher
  • 2,702
  • 1
  • 6
  • 17