'client.user.setActivity found as null? (Node.js)

I am trying to set the activity of my Discord bot as a "game" however the examples I've found online haven't helped at all.

client.user.setActivity("what the bot is playing");

Does not work at all, it gives me this error stating that I am trying to find something that is null (non-existent... in non programming terms)

TypeError: Cannot read properties of null (reading 'setActivity')
at Object.<anonymous> (/home/runner/DiscordBot/index.js:46:13)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47


Solution 1:[1]

You're probably trying to change the bot's status before it's online. Try putting it inside of the ready event instead.

client.on("ready", () => {
    client.user.setActivity("what the bot is playing");
});

Solution 2:[2]

Hello there madman12 ?

There are various syntaxes and functions that are better.

Simply you could do this:

//Make sure to define client and Discord.
client.on("ready", () => {
client.user.setPresence({ status: 'dnd' }) //Could also be "online" or "invisible" or even "idle"
const activities = [
    `${client.guilds.cache.size} Servers`, //How many servers bot is in
    `${client.channels.cache.size} Channels`, //How many channels do those servers have
    `${client.guilds.cache.reduce((a, b) => a + b.memberCount, 0)} Users`, //How many users are on those servers
    `custom add anything if you want or delete` //If you want more add , and then `custom2` and so on.
];
let i = 0;
setInterval(() => client.user.setActivity(`x!help | ${activities[i++ % activities.length]}`, { type: 'PLAYING' }), 10000); 
//Could also change to "WATCHING", "LISTENING" and "STREAMING" and you can also change the time for it to change to the next activity, warning: under 10000(10 seconds) will result in being rate limited.
//Output: Playing: x!help | 20 servers, after 10 sec: Playing: x!help | 5000 users and so on.
});
client.login("token")

Hope this helped :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 779804
Solution 2 Brandon Torreglosa