Learnmonkey Learnmonkey Logo
× Warning:

The tutorial you are reading is currently a work in-progress.

Discord.py Cogs

What are Cogs?

Cogs are a way to organize your bot's commands into different sections, so to speak. Cogs are classes and then we can individually add them to our bot object.

Making a Cog

Below is an example of a cog:


from discord.ext import commands

class SomeCommands(commands.Cog):
    """Some useful commands"""
    
    @commands.command()
    async def hello(self, ctx):
        await ctx.send("Hello!")
    
    @commands.command()
    async def greet(self, ctx, name):
        await ctx.send("Hello " + name + "!")
    

Let's break down the code step-by-step. First of all, notice that we have a class that inherits off of the commands.Cog base class, which includes all of the behind-the-scenes stuff for cogs.

Then, inside of the class, we have a multiline comment called a docstring. Docstrings are what Discord.py uses for the built-in help command.

Then, we have the commands inside of the cog. Notice that the function has self as the first argument instead of ctx. This is because we are inside a class and functions inside classes always have self as their first arguments. Also notice that instead of using the @bot.command() decorator, we now use @commands.command(). This is because we don't have access to the bot object inside of the cog class.

Adding the Cog to the Bot

Finally, we need to add the cog to our bot object. This can be simply achieved by putting the following line of code into our Python code:


bot.add_cog(SomeCommands)
    

Now, when you use your bot, you should be able to use the hello and name commands.