LittleSpace Network Developers
Sign in

Running your bot 24/7

While you’re building, running the bot from a terminal is fine. When people start relying on it, run it somewhere that stays on.

#Keep it running with PM2

PM2 restarts your bot if it crashes and starts it again after the computer reboots.

Terminal
npm install -g pm2
pm2 start bot.js --name my-bot --node-args="--env-file=.env"
pm2 save

Useful commands:

Terminal
pm2 logs my-bot      # see what it's printing
pm2 restart my-bot   # after you change the code
pm2 stop my-bot

To start it when the computer boots, run pm2 startup and follow what it prints. On Windows, use the pm2-installer package instead.

#Where to run it

Any computer that stays on works: a spare PC, a Raspberry Pi, or a small cloud server. A bot that answers commands for one community uses very little, often under 60 MB of memory.

#Logging

Print the important things so you can see what happened when something goes wrong:

JavaScript
bot.on('ready', () => console.log(`ready in ${bot.guilds.size} communities`));
bot.on('commandError', (err, msg) => console.error('command failed', msg.content, err));
bot.on('error', (err) => {
  console.error(err);
  process.exit(1); // let PM2 restart it
});

#Keep the token out of your code

Load it from .env and add .env to .gitignore. If it ever ends up somewhere public, reset it in User Settings → Applications right away.