Docs

discord bot

๐Ÿค– Discord Bot

A feature-rich Discord bot demonstrating async Python, command handling, database storage, and scheduled tasks.

๐ŸŽฏ Learning Objectives

  • โ€ขAsync/Await Patterns - Non-blocking event handling
  • โ€ขCommand Framework - Parsing and dispatching commands
  • โ€ขEvent-Driven Architecture - Responding to Discord events
  • โ€ขDatabase Integration - Persistent storage with SQLite
  • โ€ขTask Scheduling - Background jobs and reminders
  • โ€ขError Handling - Graceful error recovery

Features

  • โ€ขCustom command prefix and help system
  • โ€ขUser reminders with natural time parsing
  • โ€ขPolls with reaction voting
  • โ€ขUser statistics tracking
  • โ€ขModeration commands (kick, ban, mute)
  • โ€ขFun commands (8ball, roll, quote)
  • โ€ขScheduled announcements
  • โ€ขPersistent settings per server

๐Ÿš€ Quick Start

1. Create Discord Application

  1. โ€ขGo to Discord Developer Portal
  2. โ€ขClick "New Application" and give it a name
  3. โ€ขGo to "Bot" section and click "Add Bot"
  4. โ€ขCopy the bot token
  5. โ€ขEnable "Message Content Intent" under Privileged Gateway Intents

2. Install Dependencies

cd 04_discord_bot
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
pip install -r requirements.txt

3. Configure

cp .env.example .env
# Edit .env and add your bot token

4. Run the Bot

python -m bot

5. Invite Bot to Server

Use this URL (replace CLIENT_ID):

https://discord.com/api/oauth2/authorize?client_id=CLIENT_ID&permissions=8&scope=bot

๐Ÿ“ Project Structure

04_discord_bot/
โ”œโ”€โ”€ bot/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ __main__.py       # Entry point
โ”‚   โ”œโ”€โ”€ client.py         # Main bot client
โ”‚   โ”œโ”€โ”€ config.py         # Configuration
โ”‚   โ”œโ”€โ”€ database.py       # SQLite database
โ”‚   โ”œโ”€โ”€ cogs/
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ admin.py      # Admin commands
โ”‚   โ”‚   โ”œโ”€โ”€ fun.py        # Fun commands
โ”‚   โ”‚   โ”œโ”€โ”€ moderation.py # Mod commands
โ”‚   โ”‚   โ”œโ”€โ”€ reminders.py  # Reminder system
โ”‚   โ”‚   โ”œโ”€โ”€ polls.py      # Poll system
โ”‚   โ”‚   โ””โ”€โ”€ stats.py      # Statistics
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ embeds.py     # Discord embeds
โ”‚       โ”œโ”€โ”€ checks.py     # Permission checks
โ”‚       โ””โ”€โ”€ time_parser.py # Parse time strings
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ test_bot.py
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ README.md

๐ŸŽฎ Commands

General

CommandDescription
!helpShow help message
!pingCheck bot latency
!infoServer information
!userinfo @userUser information

Reminders

CommandDescription
!remind 1h Do homeworkSet a reminder
!remind listList your reminders
!remind cancel <id>Cancel a reminder

Polls

CommandDescription
!poll "Question?" "Opt1" "Opt2"Create a poll
!quickpoll Is this cool?Yes/No poll

Fun

CommandDescription
!8ball <question>Magic 8-ball
!roll 2d6Roll dice
!quoteRandom quote
!choose opt1 opt2 opt3Random choice

Moderation (Admin only)

CommandDescription
!kick @user [reason]Kick a user
!ban @user [reason]Ban a user
!mute @user [duration]Mute a user
!clear 10Delete messages

๐Ÿ”‘ Key Concepts

Cog System (Modular Commands)

from discord.ext import commands

class Fun(commands.Cog):
    """Fun commands for entertainment."""

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def roll(self, ctx, dice: str = "1d6"):
        """Roll dice: !roll 2d6"""
        # Implementation
        await ctx.send(f"๐ŸŽฒ You rolled: {result}")

# Load in main bot
bot.add_cog(Fun(bot))

Event Handling

class MyBot(commands.Bot):
    async def on_ready(self):
        print(f"Logged in as {self.user}")

    async def on_member_join(self, member):
        channel = member.guild.system_channel
        await channel.send(f"Welcome {member.mention}!")

    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.send("You don't have permission!")

Background Tasks

from discord.ext import tasks

class Reminders(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.check_reminders.start()

    @tasks.loop(seconds=30)
    async def check_reminders(self):
        """Check for due reminders."""
        due = self.db.get_due_reminders()
        for reminder in due:
            user = self.bot.get_user(reminder.user_id)
            await user.send(f"โฐ Reminder: {reminder.message}")

๐Ÿงช Running Tests

pytest tests/ -v

๐Ÿ“š Related Learning

โœ… Project Checklist

  • โ€ข Set up Discord application and bot
  • โ€ข Implement basic commands (ping, help)
  • โ€ข Add reminder system with database
  • โ€ข Create poll command with reactions
  • โ€ข Add moderation commands
  • โ€ข Implement user statistics
  • โ€ข Add error handling
  • โ€ข Deploy to cloud (Railway, Heroku)
Discord Bot - Python Tutorial | DeepML