How can I integrate a Cog function into the main file of my Discord bot?

I’m working on a Discord bot and I’m trying to use Cogs to organize my code. I’ve got a ban command in a separate file, but I’m having trouble adding it to my main script. Here’s what I’ve got so far:

import discord
from discord.ext import commands

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

@bot.event
async def on_ready():
    print('Bot is up and running!')

@bot.command()
async def greet(ctx):
    await ctx.send(f'Hey there, {ctx.author.name}!')

# Trying to load the ban cog
bot.load_extension('cogs.moderation')

bot.run('MY_TOKEN')

And here’s my cogs/moderation.py:

from discord.ext import commands

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

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def kick_user(self, ctx, member: commands.MemberConverter, *, reason=None):
        await member.kick(reason=reason)
        await ctx.send(f'{member.name} has been kicked.')


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

When I run the bot, it starts up fine, but the kick_user command doesn’t work. I’m not sure what I’m doing wrong. Any ideas on how to properly import and use this Cog in my main file?

hey mate, make sure ur cogs folder is in the same directory as ur main bot file. also, try using the async version of load_extension:

async def setup():
    await bot.load_extension('cogs.moderation')

bot.loop.run_until_complete(setup())

this should help load the cog properly. good luck!

I’ve dealt with similar Cog integration issues before. One thing that often trips people up is the setup function in the Cog file. Make sure it’s defined as an async function:

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

Also, in your main file, try loading the extension after the bot is ready:

@bot.event
async def on_ready():
    print('Bot is up and running!')
    await bot.load_extension('cogs.moderation')

bot.run('MY_TOKEN')

This ensures the bot is fully initialized before loading the Cog. If you’re still having issues, double-check your file structure and make sure the ‘cogs’ folder is in the same directory as your main script. Hope this helps!

I’ve run into similar issues when integrating Cogs. One thing to check is your file structure - make sure your ‘cogs’ folder is in the same directory as your main bot file. Also, in your main file, try using the async version of load_extension:

async def setup():
    await bot.load_extension('cogs.moderation')

bot.loop.run_until_complete(setup())

This ensures the Cog is loaded properly before the bot starts running. If you’re still having trouble, double-check that your Cog class and setup function in moderation.py are defined correctly. The command should work once these are set up properly.