Mysterious K
Mysterious K

Reputation: 79

How to load multiple cogs in Python 3

I was making a Discord bot and had to load 2 cogs cogs/foo.py and cogs/fooo.py. I wanted to load both of them so I did this in my code:

@bot.event
async def on_ready():
    print('UwU')
    bot.load_extension("cogs.foo")
    bot.load_extension("cogs.fooo")

This is my cog:

import discord
from discord.ext import commands

class Cog(commands.Cog):
    def __init__(self,bot):
        self.bot = bot
    @commands.command()
    def Foo(self,ctx):
        await ctx.send("Foo")

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

And, this is the error I get after running my code:

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fooo' raised an error: CommandRegistrationError: The alias n is already an existing command or alias.

So, it successfully loads the first cog but raises the error on the second one.

Upvotes: 1

Views: 2613

Answers (3)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15728

Simply loop through os.listdir

import os

for f in os.listdir('./cogs'):
    if f.endswith('.py'):
        bot.load_extension(f'cogs.{f[:-3]}')

Also the error means that there is already a command named n, so go through your code and check if every command has a unique name

Upvotes: 0

mjk 134
mjk 134

Reputation: 33

Maybe this can help? Its an example on how to load cogs and how they work. To load multiple cogs do this:

    for cog in initial_extensions:
        client.load_extension(cog)

If you clicked on the link and read through the code you'll know what initial_extensions is.

Upvotes: 2

Willy Pro
Willy Pro

Reputation: 11

You can use

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")
        print("Cog Loaded!")

To import more than 1 cogs. Happy coding!

Upvotes: 1

Related Questions