What are Cogs?
A Cog is a Python class that groups related commands and event listeners together. They help you:- Organize code into logical modules
- Load and unload features dynamically
- Share code between multiple bots
- Maintain clean, manageable codebases
Cog class is implemented in discord/cog.py:319 and uses metaclasses to automatically register commands and listeners.
Creating a Cog
- Basic Cog
- Cog with Name
- Cog with Guild IDs
- Cog with Command Attributes
Create a simple cog by inheriting from
commands.Cog:Loading Cogs
- Load from Same File
- Load from Extension
- Load Multiple Extensions
Load a cog defined in the same file:
Cog Listeners
Add event listeners to cogs using the@commands.Cog.listener() decorator:
Cog Special Methods
Cogs have special methods for lifecycle management:cog_load
cog_load
Called when the cog is loaded. Use this for async initialization:
cog_unload
cog_unload
Called when the cog is unloaded. Clean up resources here:
cog_check
cog_check
Add a check that applies to all commands in the cog:
cog_command_error
cog_command_error
Handle errors for all commands in the cog:
cog_before_invoke / cog_after_invoke
cog_before_invoke / cog_after_invoke
Run code before/after every command in the cog:
Managing Cogs at Runtime
- Load Extension
- Unload Extension
- Reload Extension
- List Cogs
Cog Organization Patterns
By Feature
Organize cogs by functionality:By Category
Organize by Discord categories:Shared State
Share data between cogs:Complete Example
Here’s a complete bot with multiple cogs: main.py:Best Practices
- One cog per file - Keep cogs in separate files for better organization
- Use descriptive names - Name cogs after their functionality
- Group related commands - Put similar commands in the same cog
- Clean up resources - Use
cog_unloadto cancel tasks and close connections - Use cog checks - Apply permission checks to entire cogs when appropriate
- Document your cogs - Add docstrings to cogs and commands
- Handle errors - Use
cog_command_errorfor cog-specific error handling - Avoid circular imports - Don’t import cogs from each other
