Newbie...
Newbie...

Reputation: 149

Discord bot not getting all of the members

I want to make a command which tells me the total amount of users in the servers the bot is in. I searched on how to make it and found this:

const users = await client.users.cache.size

But when I use it the bot tells me it's serving only one user.

Upvotes: 1

Views: 277

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23161

client.users is all of the User objects that have been cached at any point, mapped by their IDs.

I don't think there is a single method or property to get the total number of members of every server the bot is in. You could probably iterate over the guilds the client is currently handling and fetch the members instead.

The following should work:

async function getTotalNumberOfMembers(client) {
  const guilds = client.guilds.cache;
  let numberOfMembers = 0;

  // resolves once members from every guild is fetched
  await Promise.all(
    guilds.map(async (guild) => {
      const members = await guild.members.fetch();
      numberOfMembers += members.size;
    }),
  );

  return numberOfMembers;
}

// ...

const total = await getTotalNumberOfMembers(client);
console.log(total);

Edit: Yes, you can also use the .memberCount property:

function getTotalNumberOfMembers(client) {
  const guilds = client.guilds.cache;
  let numberOfMembers = 0;

  guilds.each((guild) => {
    numberOfMembers += guild.memberCount;
  });

  return numberOfMembers;
}

const total = getTotalNumberOfMembers(client);

Upvotes: 2

Related Questions