Search code examples
javascriptcollectionsdiscorddiscord.js

List all users with a specific role with DiscordJS


I already checked here but this unfortunately doesn't seem to help in my case. I am trying to list all members in a server that have the role with id 'roleID'. I get that role like so:

const guild = await client.guilds.fetch(guildID);
const role = await guild.roles.fetch(roleID);

However, whenever I try to print the roles.member property, I get an empty collection, and trying to map it out returns an empty array

console.log(role.members);
>>Collection(0) [Map] {}
console.log(role.members.map(users => users.user.tag));
>>[]

And I am absolutely stumped as to why. I know the ID is definitely correct since printing out the role lists all the correct information, and I used roleID to successfully assign the role to a few users in the server.

And yes, I triple checked, there are definitely users in the server that have the role


Solution

  • Weirdly enough what seems to fix this issue on my side is not adding the GuildMembers intent, but adding the GuildPresences intent.

    I don't know why that happens since this intent is unrelated, but you could try it as a solution to your problem.

    You also need to make sure that you enabled this intent at https://discord.com/developers/applications -> Bot -> Enable Presence Intent

    Image for reference: https://i.sstatic.net/1sYiK.png