Sure! Here's a simple example of a discord.py bot that is structured using Cogs in a cog directory.
This bot will have the following structure:
my_bot/
│
├── bot.py
└── cogs/
└── general.py
We'll include:
bot.py: The main file to start the bot.
cogs/general.py: A Cog with a simple command (!ping).
✅ Step-by-step Setup
1. bot.py — Main Bot File
# bot.py
import discord
from discord.ext import commands
import os
intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Bot is ready. Logged in as {bot.user}')
# Automatically load cogs from the /cogs folder
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
# Run the bot with your token
bot.run('YOUR_BOT_TOKEN')
2. cogs/general.py — A Simple Cog
# cogs/general.py
import discord
from discord.ext import commands
class General(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
"""Replies with Pong!"""
await ctx.send("Pong!")
# Required setup function to load the cog
def setup(bot):
bot.add_cog(General(bot))
✅ Running the Bot
- Replace
'YOUR_BOT_TOKEN' in bot.py with your actual Discord bot token.
- In the terminal, make sure you’re in the correct directory (where
bot.py is).
- Run this command:
python bot.py
Now, once the bot is online, you can type !ping in a Discord server where your bot is present and has permissions.
🔓 Requirements
Install discord.py using pip if not already installed:
pip install -U discord.py
⚠️ Warning: Ensure you're using a compatible Python version (usually Python 3.8+).
Would you like examples of how to create more Cogs (e.g., moderation, fun, welcome message)?