Home > Blockchain >  Discord.js Get all members that have a specific role
Discord.js Get all members that have a specific role

Time:09-24

I'm trying to get all members that have a specific role. Whenever I run the command I get only myself and the bot (if the bot has the role), but I have 4 other people in the server with the same role and none of them shows up. If I fetch all members they show up fine.

Anyone know why this happens?

Code:

client.on('message', message => {
    if (message.content === prefix   'add') {
        let list = client.guilds.cache.get("889906947711701022");
        let role1 = list.roles.cache.get('890636907904639027').members.map(m => m.user.id);
        console.log(role1);
    }
});

Console log:

[ '227896530835603458' ]

CodePudding user response:

You could try out this:

let list = message.guild.members.cache.filter(m => m.roles.cache.get('890636907904639027'));
// console.log(list);

The list should have all guild members that have the role.

CodePudding user response:

Try fetching all the members, your current output is only cached members.

client.on('message', async message => {
    if (message.content === prefix   'add') {
        let list = client.guilds.cache.get("889906947711701022");

        try {
           await list.members.fetch();

           let role1 = list.roles.cache.get('890636907904639027').members.map(m => m.user.id);
           console.log(role1);
        } catch (err) {
           console.error(err);
        }
    }
});

You'll need to have the GuildMember's intent enabled.

  • Related