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
2 Answers
Reset to default 4This 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
版权声明:本文标题:javascript - How to get all users with a role in Discord.js in a array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744222561a2595938.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论