How to host a discord.py bot

To host a discord.py bot, run the script on an always-on machine with the token in an environment variable and dependencies in a requirements.txt. A small bot usually fits in 256 MB of RAM.

Updated 5 min read

Learning objectives

After reading this article you will be able to:

  • Write a production-ready discord.py 2.x bot
  • Prepare requirements.txt and environment variables for deployment
  • Verify the bot is online and fix the most common errors
On this page

A discord.py bot is a Python script that opens a connection to the Discord Gateway and keeps running. Hosting it means deciding where that process lives, so it stays active when you close your editor or shut down your computer.

This guide covers the whole path: code, dependencies, token, deployment and verification. The examples use the discord.py 2.x API; check the current release on PyPI.

requirements.txtbot.pypip installpython bot.pydiscord.pylibraryBotprocessDISCORD_TOKENenvironmentvariablePython environment, always onDiscordGateway
Upload bot.py and requirements.txt, set DISCORD_TOKEN in the environment and start with python bot.py; the process connects to the Gateway.

What do you need before hosting?#

How do you write a discord.py bot that runs in production?#

Create a virtual environment and install the library:

bash
python3 -m venv .venv
source .venv/bin/activate   # on Windows: .venv\Scripts\activate
pip install -U discord.py

Now bot.py (discord.py 2.x). It uses a slash command, which does not need the privileged message_content intent, and reads the token from the environment:

python
import os

import discord
from discord.ext import commands


class MyBot(commands.Bot):
    async def setup_hook(self) -> None:
        # Registers the slash commands with Discord on startup
        await self.tree.sync()


intents = discord.Intents.default()
bot = MyBot(command_prefix=commands.when_mentioned, intents=intents)


@bot.event
async def on_ready() -> None:
    print(f"Online as {bot.user}")


@bot.tree.command(name="ping", description="Shows the bot latency")
async def ping(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(f"Pong! {round(bot.latency * 1000)} ms")


bot.run(os.environ["DISCORD_TOKEN"])

Two details matter for hosting. First, os.environ["DISCORD_TOKEN"] raises KeyError if the variable is missing, which is good: the bot refuses to start with incomplete configuration. Second, bot.run() already sets up logging and blocks until the process ends, so you need no loop and no asyncio.run.

Syncing commands on every startup is fine for a small bot. If you restart often, run the sync only when your commands change.

When do I need the message_content intent?#

Only if the bot reads message text, as with prefix commands (!ping). The discord.py quickstart, which replies to $hello, notes in a comment that the example "requires the 'message_content' intent" and turns it on with intents.message_content = True. It is a privileged intent: turn it on in the Bot tab of the Developer Portal, under Privileged Gateway Intents, and in your code too. Enabling only one side is not enough. Above 100 servers, the documentation warns that using privileged intents requires bot verification.

How do you declare dependencies?#

The host needs to know what to install. Create a requirements.txt in the project root, next to bot.py:

text
discord.py>=2.7,<3

If the bot plays audio in voice channels, the documentation tells you to install the extra: discord.py[voice]. Pin any other library you use (database drivers, HTTP clients) the same way. Generate the list from your environment with pip freeze > requirements.txt once everything works.

How do you pass the token without hardcoding it?#

Use an environment variable. In a terminal on Linux and macOS:

bash
export DISCORD_TOKEN="paste_your_token_here"
python3 bot.py

In PowerShell: $env:DISCORD_TOKEN="paste_your_token_here". If you use a local .env file, never commit it: add it to .gitignore. The concept, and why it exists, is covered in what are environment variables. If the token leaks, reset it in the Developer Portal; the old one stops working immediately.

How do you put the bot online?#

On any host the steps are the same: upload bot.py and requirements.txt, set DISCORD_TOKEN, and start with python bot.py. What changes is who keeps the process alive:

Where Survives your PC shutting down? What you maintain
Your computer No Everything, and the bot dies with the machine
VPS Yes OS, updates, supervisor (systemd, Docker)
Bot hosting platform Yes The code and the memory

On a VPS, run the bot under systemd with Restart=always or in a Docker container with --restart unless-stopped, as the 24/7 guide shows. Running python bot.py in an SSH session is not enough: the process dies when the session closes. To understand what happens with your PC, read Discord bot offline when the PC is off. The general idea of sending code to run on another machine is in what is deployment.

How do you check that the bot works?#

  1. Read the startup logs. You should see the line Online as BotName.
  2. In the server, check that the bot shows as online in the member list.
  3. Type /ping and confirm the reply. Slash commands can take a moment to appear; if they do not, restart your Discord client.
  4. Kill the process and see whether the host brings it back. Without that, "24/7" is wishful thinking.

What common errors take a discord.py bot down?#

  • discord.errors.LoginFailure: Improper token has been passed. The token is wrong, has stray spaces or was reset. Copy it again from the Developer Portal and check the variable.
  • discord.errors.PrivilegedIntentsRequired. The code asks for a privileged intent (such as message_content) that is not enabled in the portal. Enable it or remove it from the code.
  • ModuleNotFoundError: No module named 'discord'. Dependencies were not installed in the environment where the bot runs. Check requirements.txt.
  • KeyError: 'DISCORD_TOKEN'. The variable was not set on the host.
  • A file named discord.py. The documentation warns: do not name your script discord.py, because it conflicts with the library. Use bot.py.
  • A bot that dies on low RAM. The process is killed when memory runs out. See the full list in why a Discord bot goes offline.
  • Slow replies or failures from too many requests. See the Discord 429 error.

How to do this on Square Cloud#

On Square Cloud, your bot.py runs in an isolated container with the Python runtime, always on and with no sleep mode. Automatic restart is on by default for dashboard deploys and brings the bot back when the process exits with an error. You deploy it yourself: ZIP upload in the dashboard, the CLI, GitHub (a push deploys) or the VS Code extension. At start, the platform installs dependencies with pip install -r requirements.txt. discord.py works like any other Gateway library, with sharding and voice, and FFmpeg is available in the container.

The token goes in as an application environment variable, in the dashboard, the API or the CLI; the change applies on the next restart, with no rebuild. The squarecloud.app configuration file is optional: the dashboard generates it on deploy with runtime, memory and main file, and writing it at the project root is the alternative. Logs appear in real time in the dashboard, the CLI and the mobile app.

All plans are paid and billed in reais. Hobby costs R$12.49 per month, with 1 GB of RAM shared across your applications and a 256 MB minimum per background application, such as a bot. See the details on Discord bot hosting.

Bot hosting

Keep your bot online 24/7 with automatic restarts

Learn more

FAQs

Which Python version does discord.py require?

Check the minimum version in the official discord.py documentation. For a new project, use a Python version that still receives security updates.

Do I need the message_content intent for my bot to work?

Only if the bot reads message text, for example with prefix commands. Slash commands do not need it. It is a privileged intent: enable it in the Developer Portal and in your code.

Can I host a discord.py bot on my own PC?

You can for testing, but the bot goes offline whenever the computer shuts down, sleeps or loses internet. To stay online around the clock, use a machine that never turns off, such as a VPS or a hosting platform.

How do I pass the bot token without putting it in the code?

Set an environment variable such as DISCORD_TOKEN and read it with os.environ in Python. The token stays out of your repository and you can change it without editing code.

Next articleHow to host a WhatsApp bot 24/7To keep a WhatsApp bot running 24/7, run the process on an always-on server and keep its session on disk. See working code for Baileys and the official Cloud API.