READMEPython

README

real world projects / discord bot

Project
Advanced
4 min

Learning Objective

Understand real world projects well enough to explain it, recognize it in Python, and apply it in a small task.

Why It Matters

This concept is part of the foundation that later lessons and projects assume you already understand.

RealWorldProjectsLearning ObjectivesFeatures
Private notes
0/8000

Notes stay private to your browser until account sync is configured.

README
2 min read18 headings

๐Ÿค– 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

โœ… 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)

Skill Check

Test this lesson

Answer 4 quick questions to lock in the lesson and feed your adaptive practice queue.

--
Score
0/4
Answered
Not attempted
Status
1

Which module does this lesson belong to?

2

Which section is covered in this lesson content?

3

Which term is most central to this lesson?

4

What is the best way to use this lesson for real learning?

Your answers save locally first, then sync when account storage is available.
Practice queue