I’ve been having this issue with my discord bot for a while where it just goes offline even though the process is still running.
I’ve tried using nohup node index.js & then disown -a and finally exit, but the bot still dies.
Note that it doesn’t die INSTANTLY, but about 30 minutes to an hour after I close my terminal, and there’s no error message in nohup.out. But when I use top, the process still running.
I’m on Ubuntu-20.04 using Google Cloud Service VM, discord.js 13.6.0, Node.js v17.9.0
And my code looks like this:
index.js
const discord = require(“discord.js”);
const allIntents = new discord.Intents(32767);
const client = new discord.Client({intents: [allIntents]});
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
require(“dotenv”).config();
client.on(“ready”, async () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setStatus(“idle”);
createSlashCommands(client);
var stats = [“hi”, “hello”];
const length = stats.length;
for (let i = 0, true, i = (i+1)%length) {
client.user.setActivity(stats[i], {type: 3});
await sleep(10000);
}
});
message.on(“messageCreate”, async (message) => {
if (client.isReady() && !message.author.bot) {
if (message.content === “t!ping”) {
message.reply({content: `Pong! ${Date.now() - message.createdTimestamp}ms`});
}
}
});
client.on(“interactionCreate”, async (interaction) => {
if (client.isReady() && !message.author.bot) {
if (interaction.commandName === “ping”) {
interaction.reply({content: `Pong! ${Date.now() - interaction.createdTimestamp}ms`});
}
}
});
client.login(process.env.mybot);
Is there any other way I can prevent my bot from going offline? Or is there something I did wrong?
The best solution that I have found and use (and it is free) is pm2
npm i pm2 -g
// navigate to the folder with your main bot.js file (in this example it is called index.js)
pm2 start index.js
// followed by
pm2 save
// Optionally you can monitor the whole server as well with
pm2-server-monit
Comes with a free dashboard as well
As for your code, I would make a couple changes
// change:
client.on(“ready”, async () => {
// to:
client.once("ready", async () => {
Also, these won't really ever be needed because if the client isn't ready, it won't capture the event
scratch this everywhere
client.isReady() &&
// Lastly, this needs to be
client.on("messageCreate"
// rather than
message.on("messageCreate"
EDIT: Do not leave the debug active in the code all the time unless you just want to. Place this in your code like shown
// prev code
require(“dotenv”).config();
// Error Logging
client.on('error', (e) => {
console.log(e)
})
client.on('warn', (e) => {
console.log(e)
})
// comment the below one out when not using it to debug
client.on('debug', (e) => {
console.log(e)
})
process.on('unhandledRejection', (error) => {
console.log('Unhandled promise rejection:', error)
})
client.once(“ready”, async () => {
// code following