Defining a Cog
A cog is a class that extendsalterself.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 withbot.add_cog(). Remove it with bot.remove_cog(), passing the cog’s class name as a string.
Accessing Cogs
Thebot.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.
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.