Chaurka Noyan
Chaurka Noyan

Reputation: 3

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

Upvotes: 0

Views: 6181

Answers (3)

lefrost
lefrost

Reputation: 581

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();

Upvotes: 0

Worthy Alpaca
Worthy Alpaca

Reputation: 1245

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}!`);

Upvotes: 0

amit177
amit177

Reputation: 56

The reason you are getting undefined is because fetch() is an asynchronous function, meaning it is completed in the background, and once it is completed, the callback then is called.

You can't put it outside the then() block because then your code will execute before fetch() finished and updated the variable with a result, in addition to that, the totalOnline variable is created inside that block, so it wouldn't work outside of it either way, since it's a local variable inside that scope.

This article might make it easier to understand: https://www.freecodecamp.org/news/async-await-javascript-tutorial/

You can use the additional needed information inside that scope. For example:

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 ${msg.guild.name}!`);
});

Upvotes: 1

Related Questions