Tech With Galvan
Back to Articles
DevelopmentMar 28, 2027 • 5 min read

Build a Discord Bot in Python (Commands, Events, and AI)

Build a Discord bot with discord.py — commands, events, embeds, and an AI chat mode. Deploy for free.

Galvan
Galvan

Founder & Creator

Introduction

Discord bots are a great way to put Python in front of a community — moderation, utilities, AI chat, and games. This post builds a bot with commands, events, embeds, and an AI mode using discord.py.

Setup

  1. Go to Discord Developer Portal → New Application.
  2. Bot tab → Add Bot → copy the token.
  3. OAuth2 → URL Generator → select bot scope + permissions (Send Messages, Read Message History, etc.).
  4. Open the generated URL to invite the bot to your server.
  5. Install: pip install discord.py

Step 1: Echo bot

import discord

TOKEN = "YOUR_BOT_TOKEN"
intents = discord.Intents.default()
intents.message_content = True   # required to read message text

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith("!hello"):
        await message.channel.send(f"Hello, {message.author.name}!")

client.run(TOKEN)

intents.message_content = True is required in discord.py 2.0+ to read message text.

Step 2: Commands with discord.ext.commands

from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.command()
async def ping(ctx):
    await ctx.send("Pong!")

@bot.command()
async def greet(ctx, name: str = "stranger"):
    await ctx.send(f"Hello, {name}!")

@bot.command()
async def add(ctx, a: int, b: int):
    await ctx.send(f"{a} + {b} = {a + b}")

bot.run(TOKEN)

discord.py converts arguments to the annotated types automatically.

Step 3: Embeds (rich messages)

import discord

@bot.command()
async def info(ctx):
    embed = discord.Embed(
        title="Bot Info",
        description="A helpful Discord bot",
        color=discord.Color.blue(),
    )
    embed.add_field(name="Version", value="1.0", inline=True)
    embed.add_field(name="Author", value="Galvan", inline=True)
    embed.set_footer(text="Tech With Galvan")
    embed.set_thumbnail(url="https://techwithgalvan.in/avatar.png")
    await ctx.send(embed=embed)

Embeds are the building blocks of rich Discord messages.

Step 4: Error handling

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send("Unknown command. Try `!help`.")
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f"Missing argument: {error.param.name}")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Bad argument type.")
    else:
        await ctx.send(f"Error: {error}")
        raise error

Step 5: Cogs (modular commands)

# cogs/fun.py
from discord.ext import commands

class Fun(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def joke(self, ctx):
        await ctx.send("Why did the Python cross the road? To import the other side.")

async def setup(bot):
    await bot.add_cog(Fun(bot))

Load in main:

import asyncio

async def main():
    async with bot:
        await bot.load_extension("cogs.fun")
        await bot.start(TOKEN)

asyncio.run(main())

Cogs keep large bots organized — one file per feature.

Step 6: AI chat mode

import openai

openai.api_key = "sk-..."

@bot.command()
async def ask(ctx, *, question: str):
    async with ctx.typing():   # shows "bot is typing..."
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You are a helpful Discord bot. Be concise."},
                {"role": "user", "content": question},
            ],
        )
        await ctx.send(response.choices[0].message.content)

ctx.typing() shows the typing indicator while the LLM thinks.

Step 7: Background tasks

from discord.ext import tasks
import datetime

@tasks.loop(minutes=60)
async def hourly_reminder():
    channel = bot.get_channel(CHANNEL_ID)
    if channel:
        await channel.send("Hourly reminder!")

@hourly_reminder.before_loop
async def before_reminder():
    await bot.wait_until_ready()

hourly_reminder.start()

Background tasks run on a schedule — great for reminders, monitoring, and periodic updates.

Step 8: Database (per-user data)

import sqlite3

def get_points(user_id):
    conn = sqlite3.connect("bot.db")
    row = conn.execute("SELECT points FROM users WHERE user_id=?", (user_id,)).fetchone()
    conn.close()
    return row[0] if row else 0

@bot.command()
async def points(ctx):
    p = get_points(ctx.author.id)
    await ctx.send(f"You have {p} points!")

Step 9: Deploy

Option A: VPS + systemd — run python bot.py as a service.

Option B: Railway/Render — push to GitHub, deploy. Free tier available.

Option C: Docker — containerize (see Docker post).

Common mistakes

  • Missing message_content intent — bot can’t read messages. Enable it in the Developer Portal AND in code.
  • Blocking the event loop — discord.py is async. Use aiohttp for HTTP, not requests.
  • No error handling — unhandled errors crash the bot. Add on_command_error.
  • Hardcoding the token — use env vars.
  • Not handling rate limits — Discord rate-limits bots. Use asyncio.sleep between bulk actions.

Key Concepts

  • discord.py = async Discord API wrapper
  • Intents = what events the bot receives
  • Commands = !command handlers with type conversion
  • Embeds = rich formatted messages
  • Cogs = modular command groups
  • Background tasks = scheduled jobs

What to Try Next

FAQ

discord.py vs nextcord vs py-cord?

discord.py is the original and most popular. nextcord and py-cord are forks that added features during a period when discord.py was unmaintained. In 2026, discord.py is active again and is the default choice.

Can I run a bot for free?

Yes — Discord’s API is free. Hosting: Railway/Render free tiers, or a $5 VPS. The bot itself costs nothing.

How do I handle slash commands?

discord.py supports slash commands (application commands):

@bot.tree.command(name="ping", description="Check latency")
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message("Pong!")

Register with await bot.tree.sync() on startup. Slash commands are the modern Discord UX.