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
Your mistake might be a simple confusion with the id numbers. The number in your code is different then the number in your question
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.