Skip to content

Adding a New Cog to the Bot

Hunter Jarrell edited this page Jun 8, 2019 · 1 revision

Adding a New Cog

Modules or 'Cogs' are an easy way to breakup the different parts of the bot into maintainable chunks. It is a good idea to create a new module for bot if you're adding a lot of features and functionality.

For our example we are going to build a simple wiki cog that has one command !wiki which prints the word "wiki".

Create File

The first step is to just create a new python file in the cogs/ directory. Please keep the name lowercase and end in .py.

Here is what we have so far wiki.py:

Import required package

In order to create a cog we need to import the commands module from the discord.ext module.

from discord.ext import commands

Create Class

Now we can create the class that will hold our command function. The class needs to inherit commands.Cog and we can give it a readable name. Then we define the __init__ function to take in the bot object. We can store the bot as a member so that we can use it if we need it.

from discord.ext import commands

class Wiki(commands.Cog, name='Wiki'):
    def __init__(self, bot):
        self.bot = bot

Add command

Now we can add the command to the class. All commands have the @commands.command() decorator.

from discord.ext import commands

class Wiki(commands.Cog, name='Wiki'):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def wiki(self, ctx):
        await ctx.send('wiki')

Add the setup function

We need to create a setup function for the bot to find when the startup script calls load_extension. Here is where we call add_cog for each cog class in our file.

from discord.ext import commands

class Wiki(commands.Cog, name='Wiki'):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def wiki(self, ctx):
        await ctx.send('wiki')

def setup(bot):
    bot.add_cog(Wiki(bot))

Add cog to ALBot.py

Finally add your cog to the list in ALBot.py.

...
startup_cogs = [
    "cogs.messages",
    ...
    "cogs.help",
    "cogs.wiki"
]

Other Resources

Official Docs on Cogs