Log inSign up

Keeping a discord.py bot online on your own server

Create a bot in the Discord developer portal, copy its token into a root owned env file, install discord.py in a virtual environment under a dedicated system user, and start the script with a systemd unit that has Restart=always. The bot only makes outgoing connections, so no inbound port needs to be opened, and journalctl -u discordbot -f shows its log live.

Topic: Python · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What does a Discord bot need from the server?

Very little: Python 3.8 or newer, a steady outbound internet connection and enough memory for your code. A discord.py bot keeps a websocket open to the Discord gateway and calls the HTTP API for replies, so nothing has to listen on a public port. A small plan runs a bot for many servers comfortably; music bots that stream audio and bots that load large data sets are the ones that need more CPU and RAM. Python ships on every image, and our Python and pip guide lists the version on each one. Log in as your sudo user (see first SSH session) and update the system before you start.

How do you create the bot account and token?

Open the Discord developer portal, create a new application, then go to the Bot page and press Reset Token to reveal the token once. Copy it straight into a password manager, because anyone holding it fully controls the bot. On the same page decide which privileged gateway intents you need:

  • Message Content if the bot reads ordinary chat messages, for example prefix commands like !help.
  • Server Members if it tracks joins or the member list.
  • Presence only if it really uses online status.

Slash commands work without any privileged intent, which is why new bots usually rely on them. To invite the bot, open OAuth2, pick the bot and applications.commands scopes, choose minimal permissions and open the generated URL while logged in as a server admin.

How do you prepare a user and virtual environment?

A dedicated system account without a login shell keeps the bot separated from your own user and from other services.

# Ubuntu and Debian
sudo apt update
sudo apt install -y python3-venv python3-pip git

# Rocky Linux 9 and AlmaLinux 9
sudo dnf install -y python3.12 python3.12-pip git

sudo useradd --system --create-home --home-dir /opt/discordbot --shell /usr/sbin/nologin discordbot
sudo -u discordbot python3 -m venv /opt/discordbot/.venv      # Rocky and Alma: python3.12
sudo -u discordbot /opt/discordbot/.venv/bin/pip install --upgrade pip
sudo -u discordbot /opt/discordbot/.venv/bin/pip install -U discord.py
sudo -u discordbot /opt/discordbot/.venv/bin/python -c "import discord; print(discord.__version__)"

The last line should print a 2.x version. If your bot needs voice, install discord.py[voice] and the system ffmpeg package as well.

What does a minimal bot script look like?

This bot registers one slash command and reads its token from the environment. Save it as /opt/discordbot/bot.py and set the owner with sudo chown discordbot: /opt/discordbot/bot.py.

import logging
import os

import discord
from discord import app_commands

logging.basicConfig(level=logging.INFO)


class Bot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()


bot = Bot()


@bot.event
async def on_ready():
    logging.info("Logged in as %s (%s)", bot.user, bot.user.id)


@bot.tree.command(name="ping", description="Check that the bot answers")
async def ping(interaction: discord.Interaction):
    ms = round(bot.latency * 1000)
    await interaction.response.send_message(f"Pong in {ms} ms")


bot.run(os.environ["DISCORD_TOKEN"], log_handler=None)

Commands are synced once in setup_hook, not on every reconnect, which avoids hitting rate limits. Passing log_handler=None lets the basicConfig call above decide the format, and everything ends up in the journal. If you prefer prefix commands, use discord.ext.commands.Bot and enable intents.message_content = True together with the switch in the portal.

How do you keep the token out of the code?

Store it in a file readable only by root and by the bot group, and let systemd load it. The token then never lands in Git, in shell history or in a process listing.

sudo install -m 640 -o root -g discordbot /dev/null /etc/discordbot.env
sudo nano /etc/discordbot.env
DISCORD_TOKEN=paste-the-token-here

Keep a .gitignore entry for any local .env you use while developing, and reset the token in the portal at once if it ever appears in a commit or a screenshot. The environment variables guide explains other ways to pass settings.

How do you run the bot as a systemd service?

Create /etc/systemd/system/discordbot.service. The unit restarts the bot after a crash or a reboot and limits what the process may touch.

[Unit]
Description=Discord bot (discord.py)
After=network-online.target
Wants=network-online.target

[Service]
User=discordbot
Group=discordbot
WorkingDirectory=/opt/discordbot
EnvironmentFile=/etc/discordbot.env
ExecStart=/opt/discordbot/.venv/bin/python bot.py
Restart=always
RestartSec=5
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/opt/discordbot

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now discordbot
systemctl status discordbot
journalctl -u discordbot -f

A line such as Logged in as MyBot#1234 means the bot is connected. Type /ping in your server to confirm the command works end to end. ProtectHome=true is safe because the bot lives under /opt; if it writes a SQLite file, keep that file inside /opt/discordbot.

Does the firewall need changes?

No inbound rule is required. Leave SSH open, keep everything else closed, and the bot still works because it starts all its connections itself.

# Ubuntu and Debian
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status

# Rocky and Alma
sudo firewall-cmd --list-all

Only if you add a web dashboard or a webhook endpoint do you need port 80 or 443, ideally behind Nginx or Caddy with HTTPS. The SSH keys and hardening tutorial is worth doing first, since a bot server holds a valuable token.

How do you update the bot and discord.py?

Pull your code, upgrade packages inside the venv and restart the unit. Pin your dependencies so an upgrade only happens when you choose.

cd /opt/discordbot
sudo -u discordbot git pull
sudo -u discordbot .venv/bin/pip install -U -r requirements.txt
sudo systemctl restart discordbot
journalctl -u discordbot -n 30

Read the discord.py changelog before a minor version jump, and keep operating system updates running with automatic security updates.

How do you troubleshoot a bot that will not start?

  • LoginFailure: Improper token: the token was reset or copied with spaces; paste it again into /etc/discordbot.env.
  • PrivilegedIntentsRequired: the code asks for an intent that is switched off in the portal.
  • Slash command missing: global commands can take a short while to appear; for testing, sync to one guild with tree.copy_global_to(guild=...) and tree.sync(guild=...).
  • Restart loop: journalctl -u discordbot -n 50 shows the traceback; a missing package or a syntax error is the usual cause.
  • Messages arrive empty: the message content intent is off.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A1-1one or two text bots1 vCPU, 1 GB RAM, 25 GB NVMe$3.60/mo$43.20 for 12 months
A1-2several bots or a bot with a database1 vCPU, 2 GB RAM, 50 GB NVMe$7.20/mo$43.20 for 6 months
A2-4music bot with audio streaming2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months

Questions about Host a Python Discord bot

Can one server host several bots?

Yes. Give each bot its own user, venv, env file and unit file, such as discordbot-music.service and discordbot-mod.service, so you can restart and update them separately.

Do I need sharding?

Not for small and medium bots. Discord requires sharding once a bot is in 2,500 guilds; below that a single connection is fine. discord.py offers AutoShardedClient when you get there.

Is it better to run the bot in Docker?

Either works. systemd is simpler for one script, while Docker helps when the bot brings a database or many system libraries. See containerising a Python app for the Docker route.

How do I store data for the bot?

SQLite with aiosqlite is enough for settings and small counters. For heavier use, run PostgreSQL on the same server and connect with an async driver such as asyncpg.

Which of the 32 cities suits a bot?

Latency to Discord barely matters for text bots. Pick a city close to you for comfortable SSH sessions; voice bots benefit from being near their listeners. See the cities list.