I'll provide a comprehensive example of creating a Discord bot using Python with cogs. I'll break this down into multiple files to demonstrate best practices:
- First, install required libraries:
pip install discord.py
- Project Structure:
discord_bot/
│
├── main.py
├── cogs/
│ ├── __init__.py
│ ├── basic_commands.py
│ └── fun_commands.py
└── config.py
config.py:
# Store your bot token securely
BOT_TOKEN = 'your_discord_bot_token_here'
main.py:
import discord
from discord.ext import commands
import config
import os
# Set up intents
intents = discord.Intents.default()
intents.message_content = True
# Create bot instance with command prefix
class MyBot(commands.Bot):
async def setup_hook(self):
# Load all cogs in the cogs directory
for filename in os.listdir('./cogs'):
if filename.endswith('.py') and filename != '__init__.py':
await self.load_extension(f'cogs.{filename[:-3]}')
# Sync slash commands
await self.tree.sync()
# Initialize bot
bot = MyBot(command_prefix='!', intents=intents)
# Basic error handling
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Command not found. Try !help for a list of commands.")
# Ready event
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
print(f'Bot ID: {bot.user.id}')
print('------')
# Run the bot
bot.run(config.BOT_TOKEN)
cogs/basic_commands.py:
import discord
from discord.ext import commands
class BasicCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='ping')
async def ping(self, ctx):
"""Check bot latency"""
await ctx.send(f'Pong! Latency is {round(self.bot.latency * 1000)}ms')
@commands.command(name='hello')
async def hello(self, ctx):
"""Greet the user"""
await ctx.send(f'Hello, {ctx.author.mention}!')
async def setup(bot):
await bot.add_cog(BasicCommands(bot))
cogs/fun_commands.py:
import discord
from discord.ext import commands
import random
class FunCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='roll')
async def roll_dice(self, ctx, sides: int = 6):
"""Roll a dice with specified number of sides"""
result = random.randint(1, sides)
await ctx.send(f'🎲 You rolled a {result}!')
@commands.command(name='choose')
async def choose(self, ctx, *options):
"""Randomly choose between given options"""
if not options:
await ctx.send("Please provide some options to choose from!")
return
choice = random.choice(options)
await ctx.send(f"I choose: {choice}")
async def setup(bot):
await bot.add_cog(FunCommands(bot))
Key Points:
- Uses
discord.py library
- Implements a modular bot structure with cogs
- Separates commands into different cogs
- Uses
setup_hook() to automatically load cogs
- Includes basic error handling
- Provides a few example commands
How to Use:
- Replace
BOT_TOKEN in config.py with your actual Discord bot token
- Run
main.py
- In Discord, you can now use commands like:
!ping
!hello
!roll
!roll 20 (for a 20-sided die)
!choose pizza burger salad
Additional Tips:
- Always keep your bot token private
- Use environment variables or a secure method to store tokens
- Add more cogs as your bot grows
- Implement proper error handling
- Consider adding logging
This example provides a solid foundation for building a Discord bot with a scalable, organized structure using cogs.