-
Notifications
You must be signed in to change notification settings - Fork 9
Adding a New Cog to the Bot
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".
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
:
In order to create a cog we need to import the commands
module from the discord.ext
module.
from discord.ext import commands
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
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')
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))
Finally add your cog to the list in ALBot.py.
...
startup_cogs = [
"cogs.messages",
...
"cogs.help",
"cogs.wiki"
]