How to build a Discord bot in Python: from the token to slash commands

You create the application, invite the bot, write slash commands in discord.py 2.7.1 and run it in a container that comes back on its own after a reboot.

What you will do

You will build a bot with two slash commands: /ping answers only the person who asked, and /server shows an embed with the server name, member count and creation date in the reader's time zone. The code is split into cogs, so you add more commands in separate files.

At the end the bot runs in a container that comes back on its own after a reboot or a crash.

Level
beginner
Code
Python
Steps
9 steps
  1. Portal Application and token A bot in the Discord Developer Portal.
  2. OAuth2 Invite The bot and applications.commands scopes.
  3. discord.py Slash commands A cog with /ping and /server, an embed.
  4. Docker A bot that restarts itself A container with restart: always.

What you need

  • A Discord account and a test server of your own

    On the test server you need the Manage Server permission to invite the bot. You copy the server ID after enabling developer mode in Discord's settings.

  • Python 3.8 or newer

    discord.py 2.7.1 requires Python 3.8 or newer. The container in the example uses Python 3.12.

  • A place for the token

    The bot token gives full control of the bot. Keep it in an environment variable or an .env file outside the repository. If it leaks, reset it in the portal.

  • A server or VPS for production

    A bot has to run all the time, so in production you do not run it on your own computer. A small VPS with Docker is enough.

What is what in the Developer Portal

FieldWhereWhat for
Application IDGeneral InformationThe application ID, needed in the invite link.
TokenBot > Reset TokenThe bot's password to the Discord gateway. Shown once.
Privileged IntentsBotMembers, presence, message content. This bot does not need them.
OAuth2 URL GeneratorOAuth2The invite link with scopes and permissions.

Step by step

Each step with commands to copy. The list on the left shows where you are.

01

Create the application and the bot

In the Discord Developer Portal click New Application and give it a name. In the Bot tab click Reset Token and copy the token: the portal shows it only once.

Slash commands need no privileged intents. Do not enable Message Content, Server Members or Presence until the bot really reads message content or the member list.

Discord Developer Portal

TokenBot > Reset Token
The bot's password to the Discord gateway. Shown once.
Privileged IntentsBot
Members, presence, message content. This bot does not need them.
02

Invite the bot to your server

In OAuth2 > URL Generator tick the bot and applications.commands scopes, and below only the permissions the bot uses. For this bot Send Messages and Embed Links are enough. Open the generated link and pick your test server.

Without the applications.commands scope slash commands will not appear on the server, even if the bot is in the member list.

Discord Developer Portal

Application IDGeneral Information
The application ID, needed in the invite link.
OAuth2 URL GeneratorOAuth2
The invite link with scopes and permissions.
03

Set up the project and install discord.py

A separate virtual environment and a pinned library version protect you from an update on the server changing the bot's behaviour without you knowing.

bash
Command
mkdir bot && cd botpython3 -m venv .venvsource .venv/bin/activatepip install "discord.py==2.7.1"mkdir cogs
04

Write the bot's main file

commands.Bot has a built-in command tree (self.tree). In setup_hook, which runs once before connecting, you load cogs and sync commands. copy_global_to copies the commands to one server, where they show up at once, instead of waiting for global commands to propagate.

bot.py
import osimport discordfrom discord.ext import commandsGUILD_ID = int(os.environ["GUILD_ID"])class Bot(commands.Bot): def __init__(self) -> None: super().__init__(command_prefix="!", intents=discord.Intents.default()) async def setup_hook(self) -> None: await self.load_extension("cogs.server") guild = discord.Object(id=GUILD_ID) self.tree.copy_global_to(guild=guild) synced = await self.tree.sync(guild=guild) print(f"Synced commands: {len(synced)}")bot = Bot()@bot.eventasync def on_ready() -> None: print(f"Logged in as {bot.user} (ID {bot.user.id})")if __name__ == "__main__": bot.run(os.environ["DISCORD_TOKEN"])
05

Add the commands in a cog

A cog is a class with commands, loaded by load_extension. The description in the decorator is what users see in Discord. ephemeral=True means only the person who typed the command sees the reply.

discord.utils.format_dt turns a date into a <t:...:D> tag that every reader sees in their own time zone. You can build the same tag in our Discord timestamp generator.

cogs/server.py
import discordfrom discord import app_commandsfrom discord.ext import commandsclass Server(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot @app_commands.command(name="ping", description="Checks whether the bot responds") async def ping(self, interaction: discord.Interaction) -> None: delay = round(self.bot.latency * 1000) await interaction.response.send_message(f"Pong, {delay} ms", ephemeral=True) @app_commands.command(name="server", description="Basic information about the server") @app_commands.guild_only() async def server(self, interaction: discord.Interaction) -> None: guild = interaction.guild embed = discord.Embed(title=guild.name, color=0x1679FA) embed.add_field(name="Members", value=str(guild.member_count)) embed.add_field(name="Created", value=discord.utils.format_dt(guild.created_at, "D")) await interaction.response.send_message(embed=embed)async def setup(bot: commands.Bot) -> None: await bot.add_cog(Server(bot))
06

Run the bot

You pass the token and server ID as environment variables. After start-up the bot prints the number of synced commands and its name. Type / on the test server: /ping and /server should be on the list.

bash
export DISCORD_TOKEN="token-from-the-bot-tab"export GUILD_ID="123456789012345678"python bot.py
07

Answer within 3 seconds, even when the work takes longer

Discord requires the first response to an interaction within 3 seconds, otherwise the interaction token expires and the user sees an error. When a command takes longer, call defer first and send the result through followup: the token stays valid for 15 minutes.

cogs/report.py
@app_commands.command(name="report", description="A report that takes a while to compute")async def report(self, interaction: discord.Interaction) -> None: await interaction.response.defer(thinking=True) # reply within 3 seconds result = await compute_report() # you can work here for up to 15 minutes await interaction.followup.send(result)
08

Run the bot in a container

A container with restart: always comes back after a server reboot and after the bot crashes. The token reaches the container from an .env file that is not in the image or the repository.

Dockerfile, docker-compose.yml
# DockerfileFROM python:3.12-slimWORKDIR /appRUN pip install --no-cache-dir "discord.py==2.7.1"COPY . .CMD ["python", "-u", "bot.py"]# docker-compose.ymlservices: bot: build: . restart: always env_file: .env
09

Switch to global commands

When the bot should work on many servers, sync the tree without the guild parameter. Global commands take longer to propagate than those of a single server, so stay with the test server while you develop.

bot.py
async def setup_hook(self) -> None: await self.load_extension("cogs.server") synced = await self.tree.sync() # global commands, on every server with the bot print(f"Synced commands: {len(synced)}")

How to check it works

We loaded the guide's code in an environment with discord.py 2.7.1, without connecting to Discord: the cog loaded and the command tree had exactly /ping and /server with their descriptions. format_dt for 6 October 2026, 12:00 UTC produced the tag <t:1791288000:D>.

Run with a real token, the console shows the number of synced commands and the bot's name.

Environment
discord.py 2.7.1, without connecting to Discord
Result
Cog loaded, exactly /ping and /server in the tree

What you should see

  • After start-up the console shows "Synced commands: 2" and the bot's name.
  • /ping replies with the latency in milliseconds, visible only to whoever asked.
  • /server shows an embed with the name, member count and creation date.
  • After docker compose up -d and a server reboot, the bot comes back by itself.
python, discord.py 2.7.1
Command
python -c "import discord; print(discord.__version__)"
Output
2.7.1
Command
python test_tree.py
Output
[('ping', 'Checks whether the bot responds'), ('server', 'Basic information about the server')]<t:1791288000:D>
  1. 1-2
    The library version

    The environment has discord.py 2.7.1, the version the guide is written for.

  2. 3-5
    The command tree

    The cog loaded and the tree holds exactly /ping and /server with their descriptions.

  3. 6
    The date in the embed

    format_dt for 6 October 2026, 12:00 UTC gives the tag <t:1791288000:D>, which Discord shows in the reader's time zone.

From our code

How it looks in our project

The same layout runs in the bot we use to watch mailboxes and answer slash commands. It has three cogs, admin, stats and a message browser, loaded in setup_hook exactly as in the guide.

One difference: GUILD_ID is optional. With it the commands go to one server at once; without it the bot syncs them globally. At the end setup_hook starts the mail-checking loop in the background, which runs alongside command handling.

Hand the bot over when it has to talk to a panel, a store or a game, handle payments or run on many servers. What drives the price is covered in how much a custom Discord bot costs, and the scope of our offer on the Discord bots page.

Custom Discord bots: tickets, roles, verification
A Discord server with the bot's welcome in an embed and role buttons
a bot of the kind we build for Discord servers: a welcome in an embed and role buttons
mail_bot.py
class MailBot(commands.Bot): def __init__(self): super().__init__(command_prefix="!", intents=discord.Intents.default()) self._last_check: dict[str, float] = {} async def setup_hook(self): await self.load_extension("cog_admin") await self.load_extension("cog_stats") await self.load_extension("cog_browser") if GUILD_ID: guild = discord.Object(id=GUILD_ID) self.tree.copy_global_to(guild=guild) synced = await self.tree.sync(guild=guild) else: synced = await self.tree.sync() names = ", ".join(f"/{c.name}" for c in synced) print(f"[sync] {len(synced)} commands: {names}") asyncio.create_task(self._mail_loop())

Common errors

Symptom, cause and fix, with the number of the step where the error shows up.

StepSymptomCauseFix
06 LoginFailure: Improper token has been passed A mistyped token, or one reset in the portal. Reset the token in the Bot tab and paste it into .env again.
02 The commands do not show up on the server No applications.commands scope in the invite, or global commands that have not propagated yet. Re-invite the bot with both scopes and sync to the test server with copy_global_to.
07 "The application did not respond" after a command No response within 3 seconds. Call interaction.response.defer() first and answer through followup.
04 PrivilegedIntentsRequired at start-up The code enables the members or message_content intent, which is not ticked in the portal. Enable the intent in the Bot tab, or remove it from the code if the bot does not need it.
04 403 Missing Access during sync The bot is not on the server with that GUILD_ID, or the ID is wrong. Check the server ID in developer mode and invite the bot to that server.

Frequently asked questions

The questions that come up with this setup.

discord.py or another library?
In Python choose discord.py: it is mature, has official slash command examples and actively released versions. If you prefer JavaScript, you can build the same layout in discord.js.
How much does running a bot cost?
Discord charges nothing for a bot. You pay for the server it runs on. A small bot like the one in this guide uses few resources and fits on the smallest VPS next to other services.
Where do I host a Discord bot so it runs 24/7?
On a small VPS with Docker. A container with restart: always comes back after a server reboot and after the bot crashes, so you do not run it on your own computer.
Can I build and run a Discord bot in Python for free?
Building it, yes, and running it almost. discord.py is free and Discord charges nothing for a bot, you only pay for the server it runs on.
Can the bot read messages in channels?
Yes, but it needs the privileged Message Content intent, which you enable in the portal. An app that fewer than 10,000 users can see enables this intent itself in the Developer Portal; above that number you have to apply for access. Slash commands do not need it.
How do I add another command?
Add a method with the @app_commands.command decorator to an existing cog, or create a new file in cogs and load it in setup_hook. After a restart the bot syncs the tree with the new command.

Sources

The documentation and specifications we compared the commands with.

Other guides

Tools

  • Discord timestampsA Discord timestamp shows every reader a date in their own time zone. Pick a date and get all seven formats with a preview and countdown. Free, no account.
  • Bot invite linkGenerate a Discord bot invite link: paste your client ID, pick OAuth2 scopes and permissions and copy the URL. Free, in your browser, no account.
  • Discord permissions calculatorDiscord permissions calculator: tick permissions and get the permissions integer (bitfield) for a role or bot invite. Free, runs in your browser.
  • Discord snowflakeA Discord snowflake is a 64-bit ID with its creation time inside. Paste an account, server, channel or message ID and read the date. Free, in your browser.

Glossary terms

Tell us what you want to build.

A free quote comes back within an hour during working hours. You talk to the person who writes the code.