Cogs discord.py

Viewed 1151

I am trying to move my discord.py code into cogs. I keep on getting the same error Exception has occurred: ModuleNotFoundError No module named 'cogs'.

bot.py

from discord.ext import commands
bot = commands.Bot(command_prefix='!')

bot.load_extension('cogs.maincog')

bot.run('token')

maincog.py

from discord.ext import commands


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

    @commands.command()
    async def test(self, ctx):
        await ctx.send("test")


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

Folder:

enter image description here

Thanks!

2 Answers

Because maincog is in the same directory as bot, cogs. doesn't need to be included. This is because python will look for a subdirectory called cogs which is not needed in your case. New Bot.py code:

from discord.ext import commands
bot = commands.Bot(command_prefix='!')

bot.load_extension('maincog')

bot.run('token')

The bot.py don't need to be included on the folder, so put it out and this should work, but there are some improvements:

bot.py (Out of the folder)

import os
from discord.ext import commands

client = commands.Bot(command_prefix='!')
# If you don't want the default help command and want to make by yourself, you can use this:
client.remove_command('help')

# With this event, always when your bot is online, it will be printed on the terminal:
@client.event
async def on_ready():
    print('Bot Online!')

# This causes all files inside the folder with the ending .py to be loaded, without having to load one by one:
for filename in os.listdir('cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run('token')
  • OBS: I writed "client" but you can replace it for "bot" if you want to. It's just the way I prefer.
  • OBS2: If you keep this with "client", replace the "bot" on maincog.py by "client", just like this:

maincog.py (Inside the folder)

from discord.ext import commands


class MainCog(commands.Cog):
    def __init__(self, client):
        self.author = None
        self.client = client

    @commands.command()
    async def test(self, ctx):
        await ctx.send('test')


def setup(client):
    client.add_cog(MainCog(client))
Related