Implementing Hibernate Mode for a Discord bot using discord.js

I am attempting to create a hibernation feature for my Discord bot that allows it to appear online without responding to messages. Below is the code I’ve attempted:

let settings = JSON.parse(fs.readFileSync('config.json')); // Checking if hibernate mode is activated
if (settings.hibernate === true) {
    client.user.setPresence({ status: 'idle' });
    client.user.setActivity('Bot is in hibernation');
    console.log('Currently hibernating');
    return;
} else {
    client.user.setPresence({ status: 'online' });
    client.user.setActivity('');
    console.log('No longer in hibernation');
}

I’ve placed this code outside my message event listener, inside bot.once('ready', () => {}, but I encounter an error saying “cannot read property ‘setPresence’ of null.” My objective is to ensure that during hibernation, the bot goes idle and shows a status message indicating it’s hibernating, while also avoiding message handling. Any suggestions on how to achieve this?

Hey Alex! Make sure the bot’s client object is properly logged in before setting presence. You might be running client.user.setPresence too early. Try placing your presence code inside client.once('ready', () => {} to ensure the bot’s ready before you set status and activity. This should fix the error.

I’ve worked with a similar setup before, and it seems like it may also help to wrap your status and logging code in a conditional check for client.user being non-null. This way, you can guard against trying to access setPresence if the client connection hasn’t fully initialized. Additionally, make sure that your bot token is correct and that the bot has permissions to modify its presence. Sometimes, it’s easy to overlook these configuration details, especially if you’re running the bot in a new environment or server.