Skip to content

Instantly share code, notes, and snippets.

@izxxr
Last active October 21, 2021 14:00
Show Gist options
  • Save izxxr/16717ba774786ca22071320ba88efc99 to your computer and use it in GitHub Desktop.
Save izxxr/16717ba774786ca22071320ba88efc99 to your computer and use it in GitHub Desktop.

Basic Cogs Example (Discord.py rewrite)

This guide is on setting up cogs in discord.py.

What are cogs?

Cogs are used to split up your bot in different files.

Why cogs?

  • To organize your bot.
  • To avoid having tons of lines of codes in a single file.
  • To avoid messy code.

If you are making a large scale bots that has many commands and events, You will surely at some point run into problem of having tons of lines in a single file. This will make your code unmanageable. Extensions (or cogs) are a great way to avoid that and organize your bot.

Setting Up Cogs

Make a new folder in your bot directory named cogs. You can name it anything but it's the tradition to name it cogs. In this directory, we will be putting our extension files which will have our cogs.

In that directory, Make a new file and give it a name. For the sake of this example, Let's name it greeting.py. This file will contain your certain commands and listeners (events).

Start by importing discord.py and commands module.

import discord
from discord.ext import commands

Now make a new class that inherits from commands.Cog. This class will have your commands and events. Name this class anything let's name it Greeting.

class Greeting(commands.Cog):
  def __init__(self, bot):
    self.bot = bot

Here, self.bot will be your commands.Bot instance which is your main bot.

Now make a function outside the class named setup that takes one parameter bot.

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

You can make as many classes in a file and add them in setup function using add_cog() method however, It is good to have only one cog per file.

This function will be called when your extension is loaded. So, In this function you tell the bot to add the class (or cog) you just created.

Here note two things, A cog is the class we created inside our greeting.py, and extension is our greeting.py file. Cog and extension are two different things.

Adding stuff in your cog

Now let's add the commands and events in your cog. There are a few things to note.

Points to note

  1. In cogs, Commands are decorated with commands.command decorator (not with Bot.command decorator).
  2. In cogs, Events are marked with commands.Cog.listener decorator (not with Bot.event decorator).
  3. In cogs, When defining a function for either a command or an event, Make sure to pass in self parameter first and then other parameters.
  4. self.bot is your commands.Bot instance.

If you are confused with above points, Don't worry you'll get them once we make commands, Make sure to read the comments in the code.

Let's start by making a new command named hello. This command will simply send Hello World! I'm name#discriminator message.

Start by making a new function in the class you created.

@commands.command() # Read Point 1.
async def hello(self, ctx): # Read Point 3
  await ctx.send(f"Hello World! I'm {self.bot.user.name}#{self.bot.user.discriminator}") # Read point 4

This is our hello command.

Now let's make an on_message event.

@commands.Cog.listener() # Read point 2
async def on_message(self, message): # Read point 3
  if message.author == self.bot.user: # Read point 4
    return
  
  if message.content == 'hi':
    await message.channel.send("Hello "+message.author.name)

Loading the extension in your bot

Now that you have created the cog in our greeting.py extension, Go to your main bot file and in on_ready event, Use this:

async def on_ready():
  bot.load_extension("cogs.greeting")
  ...

Here, you are loading the greeting.py cog that you had created. In the string inside load_extension method, It is actually the path to your cog where cogs is the directory name you had created and then a . (period) and finally greetings is your cog name. Make sure not to include .py in the cog name. Also, Don't include path like this: cogs/greetings or cogs/greeting.py. This is wrong.

bot.load_extension("cogs.greeting.py")

bot.load_extension("cogs/greeting.py")

bot.load_extension("cogs/greeting")

☑️ bot.load_extension("cogs.greeting")

Your final code both in the main file and cog file should look somewhat like the code in the main.py file and greeting.py file.

import discord
from discord.ext import commands
class Greeting(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def hello(self, ctx):
await ctx.send(f"Hello World! I'm {self.bot.user.name}#{self.bot.user.discriminator}")
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
if message.content == 'hi':
await message.channel.send("Hello "+message.author.name)
def setup(bot):
bot.add_cog(Greeting(bot))
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
bot.load_extension('cogs.greeting')
bot.run('token')
@izxxr
Copy link
Author

izxxr commented Jun 22, 2021

Why not use bot.load_extension(cogs.greeting)

What do you mean?

@lykn
Copy link

lykn commented Oct 21, 2021

I finally got down cogs because of this man. Salude

@izxxr
Copy link
Author

izxxr commented Oct 21, 2021

I finally got down cogs because of this man. Salude

👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment