Open your hosting company

Enzonic for Resellers

Open your hosting company

How to host a discord.py bot for your community

Move a discord.py bot off your PC: cogs layout, requirements.txt, secret tokens, intents and command sync, crash loops, logging, updates and memory.

Enzonic teamUpdated 6 minute read

A discord.py bot that runs in your terminal is a great start. A bot that runs for your community every hour of every day is a different thing: it has to install its own dependencies, start without you, keep its token secret, survive restarts and tell you what went wrong when it breaks.

This guide covers running a discord.py bot on a server for your own community or project. It assumes you have a working bot and know basic Python. If you want to sell bot hosting instead, read how to start a discord.py bot hosting business.

Organize the project with cogs

discord.py has a built-in way to split a bot into modules: cogs, loaded as extensions. A layout that works well on a server:

my-bot/
  bot.py              (creates the bot, loads cogs, runs it)
  requirements.txt
  .env                (the token; never committed)
  .gitignore
  cogs/
    moderation.py
    tickets.py
    fun.py
  data/
    bot.db            (SQLite, if you use it)

Each cog is a class with its commands and listeners. Besides keeping files readable, cogs let you reload one part of the bot while it runs, which is handy when a community is mid-event and you need to fix one command without a full restart.

In discord.py 2.x, loading extensions is asynchronous, and the right place to do it is setup_hook:

import os
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

class MyBot(commands.Bot):
    async def setup_hook(self):
        for name in ("moderation", "tickets", "fun"):
            await self.load_extension(f"cogs.{name}")

bot = MyBot(command_prefix="!", intents=intents)

token = os.environ.get("DISCORD_TOKEN")
if not token:
    raise SystemExit("DISCORD_TOKEN is not set")

bot.run(token)

requirements.txt is how the server knows what to install

On your computer you installed packages one by one. The server has nothing. A requirements.txt file lists every package your bot needs, so the server can install them all with pip install -r requirements.txt.

Good habits:

  • Work in a virtual environment at home (python -m venv .venv), so pip freeze lists only what this bot uses rather than everything on your computer.
  • Pin versions you have tested, for example discord.py==2.x.y with the exact version you run. Unpinned packages can update under you on the next install and break the bot on a restart you did not plan.
  • Do not upload the virtual environment. It contains paths and compiled files specific to your machine. Upload the file, install on the server.
  • List extras explicitly. If your bot plays audio, install discord.py[voice], which pulls in PyNaCl, and make sure FFmpeg is available on the host.

Check that the server's Python version matches what you developed on, or is at least supported by every package. discord.py documents its minimum Python version, and you can find releases at python.org.

Keep the token secret

The bot token is the bot's password. Never put it in bot.py, never paste it in a screenshot or a support chat, and never commit it. Read it from an environment variable, as in the example above.

On a server with a file manager, a .env file next to bot.py (listed in .gitignore) plus the python-dotenv package is a simple pattern:

from dotenv import load_dotenv
load_dotenv()

The same rule applies to every other secret the bot uses: database passwords, API keys for game stats, webhook URLs. If a token leaks, reset it at discord.com/developers before doing anything else.

Intents and application commands

Intents decide which events your bot receives. Message Content, Server Members and Presence are privileged intents: you must enable them in the Developer Portal and in code. If your prefix commands do nothing on the server, check intents.message_content first. Request only what you use, since members and presence data also increase memory use.

Application commands (slash commands) live in bot.tree and must be synced with Discord with await bot.tree.sync(). Two practical rules:

  1. For a community bot, sync to your own guild while developing; guild commands appear right away. Global commands can take time to show up.
  2. Do not sync automatically on every startup. Add an owner-only command that syncs when you change commands. A bot stuck in a crash loop that syncs on every boot can run into rate limits.

Do not block the event loop

discord.py runs everything on one asyncio event loop. If one command calls something slow and synchronous, such as time.sleep, a blocking HTTP library or a big file operation, the whole bot freezes until it finishes. Long enough, and the gateway connection drops.

  • Use await asyncio.sleep() instead of time.sleep().
  • Use an async HTTP client (discord.py already depends on aiohttp).
  • For unavoidable blocking work, run it in a thread with await asyncio.to_thread(func, args).

This one habit fixes a large share of "my bot randomly stops responding" reports.

Restarts and crash loops

Expect restarts: after updates, after machine maintenance, after you press the button. A crash loop is when the bot fails during startup over and over. Typical causes:

  • The token variable is missing, so bot.run fails to log in.
  • A package from requirements.txt failed to install, so an import raises.
  • A cog fails to load because of a syntax error or a missing file.
  • The SQLite file path is relative to the wrong working directory.

Stop the server, scroll to the first traceback after startup and fix that. In cogs, catch errors per command with an error handler so that one broken command replies with a message instead of filling the log with noise.

Logging that shows up

When Python's output is not attached to a terminal, it buffers print output. On a hosted console that means logs can arrive late or vanish when the process crashes. Fix it by running unbuffered: start with python -u bot.py, or set the environment variable PYTHONUNBUFFERED=1.

Better still, use the logging module. discord.py 2.x sets up a basic log handler when you call bot.run, so library messages (connections, rate limits, reconnects) appear automatically. Add your own logger for commands:

import logging
log = logging.getLogger("bot")
log.info("Ticket opened in %s", channel.id)

Log IDs and actions, not message contents. You need enough to debug, not a copy of your members' conversations.

Memory and resource limits

A hosted bot has a memory limit. discord.py caches guilds, channels, roles and, with the members intent, members. A bot for one community uses little. Memory that climbs steadily for days usually means your own code keeps adding to a list or dict that is never trimmed, such as a cooldown table or a message log.

Heavy imports matter too. Data or image libraries can use more memory at import than the rest of your bot combined. If you only need them for one command, consider whether a lighter library does the job.

Updating without breaking things

  1. Back up the server, including data/, before changing anything.
  2. Upload changed files.
  3. If requirements.txt changed, reinstall packages.
  4. If commands changed, run your sync command once.
  5. Restart and watch for the ready message.

For a major discord.py upgrade, read the migration notes and test on a second bot application in a test server first. The move to version 2 changed extension loading and other APIs, and old tutorials still show the old way.

Running it through your own panel with Enzonic for Resellers

If you run bots or game servers for a community, Enzonic for Resellers gives you a branded panel for them. Opening a site is free, and panel-only mode serves just sign-in and the customer panel, with no storefront, which fits a community that does not sell anything.

You get a live console with power controls and CPU, memory and disk stats, a file manager and SFTP, backups (also scheduled), scheduled tasks and subusers so a co-admin or developer can help without your password. With Enzonic for Resellers, discord.py bots runs on Enzonic nodes in Europe, North America and Asia and on your own Pterodactyl or Pelican Wings nodes, so you can sell it without running any hardware. You can also connect your own Pterodactyl Wings or Pelican Wings machine and run the bot there. Servers you grant on Enzonic nodes have their base price charged monthly from your credits.

The same approach works for any Python project; see how to host a Python app for your community. If you run other languages too, the guides for Go and Java cover their differences. Open a site when you are ready.

Frequently asked questions

Why does my discord.py bot work locally but not on the server?

Usually one of three things: a package missing from requirements.txt, a different Python version, or the token environment variable not set on the server. The first traceback in the console tells you which.

Why are my print statements not showing in the console?

Python buffers output when it is not attached to a terminal. Run with python -u or set PYTHONUNBUFFERED=1, or switch to the logging module.

How often should I sync slash commands?

Only when you add, remove or change commands. Syncing on every startup is unnecessary and can hit rate limits, especially if the bot restarts repeatedly.

Can my discord.py bot play music on a hosted server?

Yes, if the voice extras and FFmpeg are installed and the server has enough CPU. Install discord.py[voice], confirm FFmpeg is present and test with one channel before inviting the bot everywhere.

#discord#discord-py#bots#python