Host a discord.py bot, step by step
A Python bot that runs on your PC is quickly written. For it to run around the clock as well, it needs a few changes. This guide shows them on a small discord.py bot.
The project
Two files are enough to start: bot.py and requirements.txt.
# requirements.txt
discord.py>=2.7,<3
The bot
# bot.py
import asyncio
import os
import signal
import discord
from discord import app_commands
class Bot(discord.Client):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.default())
self.tree = app_commands.CommandTree(self)
async def setup_hook(self) -> None:
# Shut down cleanly on a restart or a new version.
try:
asyncio.get_running_loop().add_signal_handler(
signal.SIGTERM, lambda: asyncio.create_task(self.close())
)
except NotImplementedError:
pass # Not available on Windows; stop with Ctrl+C there.
# Sync commands only when you want to, not on every start.
if os.environ.get("SYNC_COMMANDS") == "1":
await self.tree.sync()
print("Commands synced")
bot = Bot()
@bot.tree.command(name="ping", description="Replies with Pong")
async def ping(interaction: discord.Interaction) -> None:
await interaction.response.send_message("Pong!")
@bot.event
async def on_ready() -> None:
print(f"Online as {bot.user}")
token = os.environ.get("DISCORD_TOKEN")
if not token:
raise SystemExit("DISCORD_TOKEN is missing")
bot.run(token)
What matters here for running all the time:
- The token comes from the environment. It never belongs in the code or in the repo.
- Commands are not synced on every start. Discord limits how often you can do that. Set
SYNC_COMMANDS=1once when a command has changed, and remove it afterwards. - The bot shuts down cleanly. On a
SIGTERM, which comes with every restart and every new version, it closes the connection to Discord instead of just breaking off.
With discord.Intents.default() you get everything except the privileged intents. If you need the content of messages, set intents.message_content = True and switch the intent on in the Discord Developer Portal.
Option 1: Dockerfile
FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd --create-home bot
USER bot
CMD ["python", "bot.py"]
PYTHONUNBUFFERED=1 makes every line appear in the logs at once. Without it, Python collects the output and sends it in blocks, and after a crash exactly the last lines are missing.
Option 2: init.sh
Without a Dockerfile, EStage builds with an init.sh on Ubuntu. It runs once at build time and installs what your bot needs:
#!/bin/sh
set -e
apt-get update
apt-get install -y --no-install-recommends python3 python3-venv
python3 -m venv /app/.venv
/app/.venv/bin/pip install --no-cache-dir -r /app/requirements.txt
As the start command you enter in the dashboard:
/app/.venv/bin/python -u bot.py
The -u has the same effect as PYTHONUNBUFFERED=1. When to use which option is in the guide Dockerfile or init.sh.
Testing on your PC
python -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
DISCORD_TOKEN=your-token SYNC_COMMANDS=1 python bot.py
On Windows you activate the environment with .venv\Scripts\activate and set the variables with set.
Bringing it online on EStage
- Connect the repo or push to our Git address.
- Create a secret:
DISCORD_TOKEN. For the first start alsoSYNC_COMMANDS=1as a variable, and remove it afterwards. - Assign memory: 256 MB is enough for a bot like this.
- Push.
Online as ...appears in the logs.
Data that stays
For small amounts of data, SQLite in /data is enough; it survives restarts and is backed up every night:
import sqlite3
db = sqlite3.connect("/data/bot.db")
db.execute("CREATE TABLE IF NOT EXISTS points (user_id INTEGER PRIMARY KEY, n INTEGER NOT NULL)")
def give_points(user_id: int, n: int) -> None:
db.execute(
"INSERT INTO points VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET n = n + excluded.n",
(user_id, n),
)
db.commit()
If several services share the data, such as the bot and a leaderboard on your page, use your account’s PostgreSQL database through DATABASE_URL, for example with asyncpg.
Common questions
Why don't my print statements show up in the logs?
Python buffers output when it does not go to a terminal. Set the environment variable PYTHONUNBUFFERED=1 or start with python -u, and every line arrives at once.
Do I need a virtual environment in the container?
With the official Python image, no; you install with pip directly. With init.sh on Ubuntu, yes, because the system Python there does not accept packages through pip.
Does voice work, music or recordings?
Yes, with discord.py[voice] and the system packages it needs, such as ffmpeg, in the image. Plan more memory for it, usually 512 MB or more.