Search code examples
javascriptnode.jsdiscorddiscord.js

Member counter is not updating members count discord.js


I created a member counter, but it is not updating. it's stuck on 80585. When I want to update it, I need to restart the bot.

My code:

client.on("ready", async() => {

    let servercount = await client.guilds.cache.reduce((a,b) => a+b.memberCount, 0 );
    
    const activities = [
        `${servercount} People👤 !`,
        `d!help`
    ]
    setInterval(() => {
        const status = activities[Math.floor(Math.random()*activities.length)];
        client.user.setPresence({ status: "online", activities : [{name : `${status}` , type : "WATCHING",}]});
    }, 120000);
});

I am using discord.js v13 and node.js v16enter image description here


Solution

  • When I want to update it, I need to restart the bot.

    And therein is the issue with your code. Look at the let servercount line. Specifically, look at where it is in your code. The member count is only updating when the bot starts up, because you are only getting the member count when the bot starts up. To fix that particular issue, just move that line into the interval:

    client.on("ready", async() => {
    
        setInterval(async () => {
    
            let servercount = await client.guilds.cache.reduce((a,b) => a+b.memberCount, 0 );
        
            const activities = [
                `${servercount} People👤 !`,
                `d!help`
            ]
    
            const status = activities[Math.floor(Math.random()*activities.length)];
            client.user.setPresence({ status: "online", activities : [{name : `${status}` , type : "WATCHING",}]});
        }, 120000);
    });
    

    This should at least fix the member count not being updated. However, the member count may still not be up-to-date even after this fix. You need to fetch the member collection of each guild in order to always get accurate numbers.