COdeingNinja
COdeingNinja

Reputation: 387

How to get all users with a role in Discord.js in a array

I am trying to get all the members with a certain role. For example, there is role of gurdian in my discord server with a id of 872029521484873779. I want a list of all the users Name in a array who have gurdian as a role in my server. My code is as below

let nameList= msg.guild.roles.cache.get('role_id').members.map(m=>m.user.tag);

However, In result it only returns one user in the nameList whereas as there are 9 users with the role assigned to them. What am I doing wrong here which is bringing me only 1 user not the rest of 9 users in a list in array. I am new to discord.js

Upvotes: 2

Views: 6139

Answers (2)

3061LRTAGSPKJMORMRT
3061LRTAGSPKJMORMRT

Reputation: 108

This is happening because the members aren't cached. So you only see 1 person logging because only 1 person is in the cache. To fix this, you can fetch all members by doing msg.guild.members.fetch(), then use msg.guild.roles.cache.get("roleid").members.map(m => m.user.tag) to get the real output. Please do note that you will need the GUILD_MEMBERS intent if you are on v13.

Fetching members from the guild will store them in cache. So when you do do role.members, you get the members who have this role.

If you don't fetch members, then the info won't be accurate. Discord.js stores users in cache. This happens whenever someone sends a message, updates their profile or anything about themselves WHILE the bot is online. So if you restart your bot, no one will be in the cache.

Why is fetch different from cache?

Fetch gets the info directly from discord, while cache is checking if the user is stored locally. When you fetch members, they are automatically stored in the cache as well.

Upvotes: 4

yotamolenik
yotamolenik

Reputation: 56

Your mistake might be a simple confusion with the id numbers. The number in your code is different then the number in your question

Upvotes: 3

Related Questions