Encountering difficulties with loading cogs in a Discord bot using Python

I’m new to creating Discord bots and I’m struggling with the implementation of cogs. I’m seeking assistance on how to effectively load these cogs.

Here’s an example of my main bot file:

import discord
import os
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
token = os.getenv('TOKEN')

intents = discord.Intents.default()
intents.messages = True
intents.message_content = True

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

@bot.event
async def on_start():
    print("Bot is operational!")

@bot.command()
async def load_cog(ctx, cog_name):
    try:
        bot.load_extension(f'cogs.{cog_name}')
        await ctx.send(f'Loaded cog: {cog_name}.')
    except Exception as error:
        await ctx.send(f'Error: {error}')

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

    bot.run(token)

And here is one of my cogs:

from discord.ext import commands
import requests
from random import choice

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

    @commands.command()
    async def start_game(self, ctx):
        # Implement game logic here

def setup_cog(bot):
    bot.add_cog(GameCog(bot))

I’m encountering runtime warnings that I cannot resolve:

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2023-10-18 01:54:39 INFO     discord.client logging in using static token
2023-10-18 01:54:40 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: hidden).
Bot is operational!

The bot works fine in bot.py, but problems arise when I integrate cogs as shown above.

Try looking into the setup_cog function in your cog file. You shoudl rename it to setup, otherwise discord.py might not recognize it when loading the cog. Also, check that there’s no misspelling in the class GameCog naming. Keep experimenting with small changes! :slight_smile: