Get Guild Members And Filter Them (discord.js)
Solution 1:
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}!`);
});
Solution 2:
What you could do instead of using fetch()
is just assign a variable to the member collection.
// v12let allmembers = message.guild.members.cache;
// v11let 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}!`);
Post a Comment for "Get Guild Members And Filter Them (discord.js)"