admin管理员组

文章数量:1399903

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

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

Share Improve this question edited Nov 10, 2021 at 12:47 Ghost Ops 1,7342 gold badges14 silver badges23 bronze badges asked Nov 10, 2021 at 10:39 COdeingNinjaCOdeingNinja 3871 gold badge6 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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

本文标签: javascriptHow to get all users with a role in Discordjs in a arrayStack Overflow