For a project, I need to export the total number of members of a Discord server list. Is there a way to get this number without accessing the server? So far I've tried something with what I've found on various forums but I get an error: Cannot read properties of undefined (reading 'memberCount')
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const token = 'MyToken';
client.login(token);
client.on('ready', async () => {
let myGuild = await client.guilds.cache.get('798982176502054933');
let memberCount = myGuild.memberCount;
console.log(memberCount);
});
client.guilds.cache.get('798982176502054933') doesn't return a promise as it is a collection so you don't have to use await with it.
let myGuild = client.guilds.cache.get('798982176502054933');
let memberCount = myGuild.memberCount;
console.log(memberCount);
a better approach for this is to use the .fetch(id) function. this code waits for the fetch to find the guild then will console log the guild member count. if your bot cant find the server it will throw an error.
client.on('ready', async () => {
await client.guilds.fetch('798982176502054933')
.then(myGuild => {
console.log(myGuild.memberCount)
})
});