๐ค 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
- โขGo to Discord Developer Portal
- โขClick "New Application" and give it a name
- โขGo to "Bot" section and click "Add Bot"
- โขCopy the bot token
- โขEnable "Message Content Intent" under Privileged Gateway Intents
2. Install Dependencies
cd 04_discord_bot
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
3. Configure
cp .env.example .env
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
| Command | Description |
|---|
!help | Show help message |
!ping | Check bot latency |
!info | Server information |
!userinfo @user | User information |
Reminders
| Command | Description |
|---|
!remind 1h Do homework | Set a reminder |
!remind list | List your reminders |
!remind cancel <id> | Cancel a reminder |
Polls
| Command | Description |
|---|
!poll "Question?" "Opt1" "Opt2" | Create a poll |
!quickpoll Is this cool? | Yes/No poll |
Fun
| Command | Description |
|---|
!8ball <question> | Magic 8-ball |
!roll 2d6 | Roll dice |
!quote | Random quote |
!choose opt1 opt2 opt3 | Random choice |
Moderation (Admin only)
| Command | Description |
|---|
!kick @user [reason] | Kick a user |
!ban @user [reason] | Ban a user |
!mute @user [duration] | Mute a user |
!clear 10 | Delete 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"""
await ctx.send(f"๐ฒ You rolled: {result}")
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