'Get guild members and filter them (Discord.js)
i'm new to Discord.js, and trying to make server info command like on the picture below. I'm stuck in the moment where i need to get all guild members and filter them by current status and bot property. I read https://discordjs.guide/popular-topics/common-questions.html and it says that i need to fetch all guild members:
msg.guild.members.fetch().then(fetchedMembers => {
const totalOnline = fetchedMembers.filter(member => member.presence.status === 'online');
msg.channel.send(`There are currently ${totalOnline.size} members online in this guild!`);
});
My command is sent as an embed, and i'm adding filtered members count into a variable, and then this value inserting into a embed field. If i send embed to a channel right inside then() block, it's working, embed fields are added correctly. But i need to add another information about guild, such as channels count, owner, region etc. If i create fields out of then(), instead of the count i get undefined.
P.S. sorry for my poor English, i'm not a native speaker
Solution 1:[1]
What you could do instead of using fetch() is just assign a variable to the member collection.
// v12
let allmembers = message.guild.members.cache;
// v11
let allmembers = message.guild.members;
Once you have that, you can filter it and put it into an embed or message etc.
const totalOnline = allmembers.filter(member => member.presence.status === 'online');
message.channel.send(`There are currently ${totalOnline.size} members online in ${message.guild.name}!`);
Solution 2:[2]
Answer for discord.js v13:
let members = (await guild.members.fetch())
.filter(m => m._roles.includes(ROLE_ID));
let member_ids = members.map(m => m.user.id);
let member_count = members.size();
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 | Worthy Alpaca |
| Solution 2 | lefrost |
