Skip to main content
As your bot grows, placing every command and event listener in a single file quickly becomes hard to navigate and maintain. Cogs solve this by letting you group related commands, listeners, and shared state into a self-contained class. You can load a cog to activate all of its features, unload it to disable them, and swap it at runtime without restarting your bot. This makes cogs the natural building block for organising bots of any size.

Defining a Cog

A cog is a class that extends alterself.Cog. You decorate each command method with @alterself.cmd() and each listener method with @alterself.listen() just as you would on the top-level client. alterself discovers them automatically when the cog is registered.
Command and listener methods inside a cog always receive self as the first argument, followed by the usual ctx (for commands) or event arguments (for listeners).

Lifecycle Hooks

Cogs support two optional lifecycle hooks that alterself calls automatically: Use these hooks to open database connections, start background tasks, or clean up resources:

Registering Cogs

Add a cog instance to your client with bot.add_cog(). Remove it with bot.remove_cog(), passing the cog’s class name as a string.
You can call bot.add_cog() at any time, before or after bot.run(). Adding a cog while the bot is running immediately makes its commands and listeners available.
Calling bot.add_cog() with a cog whose class name is already registered raises CogAlreadyLoaded. Remove the existing instance first if you want to hot-reload a cog.

Accessing Cogs

The bot.cogs property returns a dictionary of all currently loaded cogs, keyed by class name. Use it to inspect loaded cogs or to call methods on a cog from outside the cog itself:

Worked Example: AdminCog

The following cog implements two owner-only admin utilities: purge to bulk-delete your own messages, and sinfo to display server information.
Let’s walk through what each command does:
1

purge: delete your own messages

purge accepts an optional count n (default 10, capped at 100). It fetches the most recent messages in the current channel, filters for messages authored by you, deletes each one with a short sleep to avoid hitting the rate limit, and then sends a confirmation notice that auto-deletes after three seconds.The @alterself.check(owner_only) decorator ensures only you (or user IDs listed in owner_ids) can invoke this command.
2

sinfo: display server information

sinfo reads ctx.guild from the cache. If called in a DM where no guild is present, it replies with a helpful error. Otherwise it formats the guild name, ID, member count, and Nitro boost tier into a reply.
The purge command deletes messages one at a time with a 0.4 s delay between each deletion. Discord’s self-bot rate limits are stricter than bot rate limits, so be conservative with deletion speed to avoid triggering automated flagging.