Search code examples
node.jsdiscord.jsrolesmember

Discord.js Get all members that have a specific role


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' ]

Solution

  • 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.