Difficulty importing a Cog function into main.py for my Discord bot

I’m trying to set up a Discord bot and facing issues with loading Cog commands properly

I started a project for a Discord bot and organized my commands using Cogs. I’ve created a separate file specifically for a ban command, but when I attempt to load it in my main.py file, I keep running into errors.

Here’s the code for my main.py file:

import discord
import os
import asyncio
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith(".py"):
            cog_name = filename[:-3]  # Remove the '.py'
            cog_path = f'cogs.{cog_name}'  # Full cog path
            try:
                await bot.load_extension(cog_path)
                print(f"Loaded extension: {cog_name}")
            except commands.ExtensionAlreadyLoaded:
                print(f"Extension {cog_name} is already loaded.")
            except commands.ExtensionNotFound:
                print(f"Extension {cog_name} not found.")

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.dnd, activity=discord.Game('Playing a game'))
    print("Bot is ready")

@bot.command()
async def hello(ctx):
    await ctx.send(f"Hello {ctx.author.mention}!")

with open("token.txt") as file:
    token = file.read()
    
bot.run(token)

And here’s the code for my ban command cog:

import discord
from discord.ext import commands

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

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        await member.ban(reason=reason)
        await ctx.send(f"{member} has been banned!")

async def setup(bot):
    await bot.add_cog(Ban(bot))

However, I encounter parameter mismatches and other errors when I run the bot, preventing the command from working. I’ve attempted several solutions, but either receive warnings about coroutines not being awaited or the commands fail to register. What might I be doing incorrectly with the loading of Cogs?

Everyone covered the main issue, but here’s another thing - your cogs folder needs an __init__.py file, even if it’s empty. Python won’t recognize it as a package without one, and you’ll get import errors. Also double-check for syntax errors in your cog files - one broken cog will break the entire loading process.

You’re not calling the load() function after defining it. Without await load() before bot.run(token), your bot won’t load any cogs and the commands won’t work. Put the function call right after you define it, or stick it inside an async main function to keep things organized. Also make sure you’ve got an __init__.py file in your cogs directory - Python needs that to recognize it as a package. I ran into the same issue when I started using cogs, so this should fix your problem.

Your cog structure looks fine, but you’re not actually calling the load() function you wrote. It’s just sitting there while your bot runs without loading any extensions. You need to call await load() before bot.run(token). Since bot.run() blocks everything, restructure it like this:

async def main():
    await load()
    await bot.start(token)

if __name__ == "__main__":
    asyncio.run(main())

Ditch the bot.run(token) line and use this pattern instead. I ran into the same thing when I started with cogs - the async loading timing screws with everyone at first.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.