Skip to content

Instantly share code, notes, and snippets.

@15696
Last active June 18, 2024 07:23
Show Gist options
  • Save 15696/a1b10f044fbd658ce76ab1f862a1bda2 to your computer and use it in GitHub Desktop.
Save 15696/a1b10f044fbd658ce76ab1f862a1bda2 to your computer and use it in GitHub Desktop.
simple cogs example in discord.py
# main.py
from discord.ext import commands
import os
client = commands.Bot(command_prefix = "!")
for f in os.listdir("./cogs"):
if f.endswith(".py"):
client.load_extension("cogs." + f[:-3])
client.run("token")
# cogs / test.py
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client # sets the client variable so we can use it in cogs
@commands.Cog.listener()
async def on_ready(self):
# an example event with cogs
@commands.command()
async def command(self, ctx):
# an example command with cogs
def setup(client):
client.add_cog(Test(client))
@mudkipdev
Copy link

mudkipdev commented Mar 23, 2023

@Tango0o0o Here is a far better version of the code:

# main.py
from discord.ext import commands
import discord

EXTENSIONS = ("extensions.example",)
INTENTS = discord.Intents.default()
INTENTS.message_content = True

bot = commands.Bot(
    intents=INTENTS,
    command_prefix="!"
)

@bot.event
async def setup_hook() -> None:
    for extension in EXTENSIONS:
        await bot.load_extension(extension)

bot.run("token")

# extensions/example.py
from discord.ext import commands

class ExampleCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot
	
    @commands.Cog.listener()
    async def on_ready(self) -> None:
        pass
	
    @commands.command()
    async def command(self, ctx: commands.Context) -> None:
        pass

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(ExampleCog(bot))

I deliberately avoided automatically loading extensions, because it could lead to errors and listing the extensions manually was far simpler. Also, note that extensions and cogs are different and should be treated as such, as you can load an extension without any cogs in it at all.

@Honkou
Copy link

Honkou commented May 13, 2023

@bot.event
async def setup_hook() -> None:
for extension in extensions:
await bot.load_extension(extension)

That's what I was missing in all the official and fancy guidelines.
Thank you, sir, you are a true savior!

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