'Discord.js update cache to pull all members that have role
Currently having issues pulling all members that have a certain role. I can currently pull a list of names but only those that are cached currently. If i leave my bot running for a few hrs it will pull more but it never pulls all members that have that role. Ive read a few different things about using the .fetch() command but still no dice.
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES,
Intents.FLAGS.GUILD_MEMBERS
]
});
msg.channel.send('exporting all members with delcared role');
msg.guild.roles.fetch('guildId');//cache roles i think?
let role = msg.guild.roles.cache.find(r => r.name === 'Sysadmins');
msg.guild.members.fetch('roleId');//cache members i think?
let list = msg.guild.roles.cache.get(roleID).members.map(m => m.nickname)
console.log(role);
console.log(list);
The console.log(); returns my nickname as expected but only mine and i know there are at least 10 others with this role.
Other questions similar that I have already tried:
Solution 1:[1]
Since you're giving the fetch() method a String argument, only the user matched with that String will be fetched, more like a get(). Also, the fetch() method returns a Promise, which means the method must be awaited to actually recieve the data.
Your fetch() method should look like this:
await msg.guild.members.fetch();
This way you tell Node.js it must wait until you recieve the data promised before continue.
Solution 2:[2]
It's close, but much simpler, with 3 lines
await msg.guild.members.fetch() // fetch all members and cache them
const role = msg.guild.roles.cache.get("id") // get role from cache by ID (roles are always cached)
const list = role.members.map(m => m.nickname) // map members by nickname
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DanLop |
| Solution 2 | MrMythical |
