Documentation / Learn to write a bot / Run the bot 24/7
- Find a server
A cheap VPS or a bot hosting service.
- Start it with pm2
pm2 runs the bot in the background and restarts it if it crashes.
pm2 start index.js --name my-bot - Catch errors
Keep the bot from crashing with try/catch and error events.
This is exactly how Aegis runs too: a Node.js program kept running on a server with pm2.
Keep it running with pm2
Copy your project to the server, run npm install, create your .env file and start the bot with pm2.
npm install -g pm2
pm2 start index.js --name my-bot
pm2 logs my-bot # live logs
pm2 restart my-bot # after you change the code
pm2 save && pm2 startup # start the bot again when the server rebootsDo not crash on errors
Wrap the work in try/catch so an error in one command does not take the whole bot down, and catch unexpected errors too.
client.on(Events.InteractionCreate, async (interaction) => {
try {
// ... command code
} catch (error) {
console.error(error);
const reply = { content: "Something went wrong.", flags: MessageFlags.Ephemeral };
if (interaction.replied || interaction.deferred) await interaction.followUp(reply);
else await interaction.reply(reply);
}
});
process.on("unhandledRejection", (error) => console.error("Unhandled error:", error));Security
- Token
- Keep it only in .env; never put it in code, a screenshot or GitHub.
- Least permissions
- Give your bot only the permissions it needs. Not every bot needs the Administrator permission.
- Check permissions
- For commands like ban and kick, check the permissions of the person who used the command with interaction.memberPermissions.
What's next?
On the next page, the Code area, you can try what you learned in the browser. For more, the official discord.js guide (discordjs.guide) is a very good resource.