Reputation: 7
so i haven't been coding for quite a long time and when i was reading the Discord.js Guide, i didn't saw how i can get the total amount of Users where my Bot is in.
Because apparently since V13/V14 client.users.cache.size
is not working because the Bot Logs only 1 Person.
I have currently this in my Upgraded Bot Version (from djs V12).
client.once("ready", () => {
//console.log('The Blax Beta is online! ')
console.log(`I'm currently on ${client.guilds.cache.size} Servers with ${client.users.cache.size} people.`)
const activities = [
`with ${client.users.cache.size} people.`,
"music.",
"with my Owner.",
` | Version ${client.BotVersion}`,
`on ${client.guilds.cache.size} Servers.`,
`/help`
];
setInterval(() => {
const randomIndex = Math.floor(Math.random() * (activities.length - 1));
const newActivity = activities[randomIndex];
client.user.setActivity(newActivity);
}, 10000);
client.user.setActivity(` | Version ${client.BotVersion}`)
});
Thanks to whoever can help me.
Upvotes: 0
Views: 338
Reputation: 726
Before I start, double check to make sure you have the GuildMembers intent enabled - in the Discord Developers dashboard AND in your code.
As you figured out, client.users.cache doesn't actually cache all users your bot is in a guild with (you can imagine how large that object would be for a bot like dank memer).
One way to calculate this is by going through each of the guilds your bot is in and using the guild's memberCount
property, which is just a plain integer with the number of users. Unfortunately, since it's just a number, you can't filter out bots from memberCount
. If you're fine with that then this code should do the trick:
const guilds = client.guilds.cache;
var totalUsers = 0;
guilds.forEach((guild) => {
totalUsers += guild.memberCount;
});
console.log(totalUsers);
However, if you don't want to include bots in the user count (I like to do this because my bots are in a lot of Discord bot listing website guilds, so there are thousands of bots that my bot is in the same guild with) you can do a similar thing but fetch all the members in each guild.
But, even if your bot is only in a few dozen servers, it can still take a very long time to fetch that many users, so I like using an array of promises and the Promise.all
function to do this.
Example:
const guilds = client.guilds.cache;
const promiseArr = [];
guilds.forEach(guild => {
// push a promise that resolves with the number of members in the server
promiseArr.push(new Promise(async (resolve, _reject) => {
// fetches the members in the guild
var members = await guild.members.fetch();
members = members.filter(m => !m.user.bot);
resolve(members.size);
}));
});
// calls every promise and returns them into an array
var results = await Promise.all(promiseArr);
// this function takes all the numbers in the array and adds them into a single number
var totalUsers = results.reduce((prevVal, currVal) => prevVal + currVal);
console.log(totalUsers);
Upvotes: 1