natbox.io

Guides / Discord bot

Host a Discord bot 24/7

About 10 minutes. Nano is enough for most bots. Ubuntu or Debian commands.

A Discord bot only makes outgoing connections to Discord, so it needs no forwarded ports at all. It works perfectly on a NAT VPS.

1. Install your bot (Python example)

apt update && apt install -y python3-venv git
useradd -r -m -d /opt/bot bot
sudo -u bot git clone https://github.com/you/your-bot /opt/bot/app   # or copy your files there
cd /opt/bot/app
sudo -u bot python3 -m venv venv
sudo -u bot venv/bin/pip install -r requirements.txt

For Node.js, install nodejs and npm instead and run npm ci.

2. Keep the token out of your code

echo "DISCORD_TOKEN=your-token-here" > /opt/bot/bot.env
chown bot: /opt/bot/bot.env && chmod 600 /opt/bot/bot.env

3. Run it as a service

Save as /etc/systemd/system/bot.service:

[Unit]
Description=Discord bot
After=network-online.target
Wants=network-online.target

[Service]
User=bot
WorkingDirectory=/opt/bot/app
EnvironmentFile=/opt/bot/bot.env
ExecStart=/opt/bot/app/venv/bin/python bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl daemon-reload && systemctl enable --now bot
journalctl -u bot -f

The bot now starts on boot and restarts within 5 seconds if it crashes. To update: pull the new code, then systemctl restart bot.

Good to know