I've recently made a Discord bot using discord.js v12 and I haven't been able to set a presence for the bot.
This is the code:
client.user.setPresence({ game: { name: '.help' }, status: 'online' });
And the error is: TypeError: Cannot read property 'setPresence' of null.
If you read the Client class docs here, you can see that the type of the user property has type ?ClientUser with ? out the front - this means that it may not be defined (it's an optional value).
If you visit the ClientUser documentation, it says it "Represents the logged in client's Discord user."
I'm guessing that if the client has not yet fully logged in, then the user property will be undefined. Call client.login(token) first, which is an asynchronous function, and then you can change the presence.
This means, using promises:
client.login(token).then((token) => {
// client.user is now defined
client.user.setPresence({
game: { name: '.help' },
status: 'online',
});
});
You may also want to query that client.user is defined either way before proceeding to prevent crashing.
I suspect the reason your existing code does not work is because if you do not set the presence in the callback for the login function, you will not yet have finished logging in by the time the rest of the code runs. The following will cause an error:
client.login(token); // bad - this is async
client.user.setPresence(...)