Search code examples
pythonpython-class

How can I use cogs (discord.py)


I'm quite new to Python, but I understand how cogs work. But what do I have to write in the main-File (to load all the cogs in a subfolder of my main.py) and what do I have to write in the cog?

And what can I do in cogs besides commands?

Lets say, I have a function, that sends every message written in the Bots DMs to a channel in my server and I wanna outsource it into a cog. How do I do that for example?

And what are the options for outsourcing things into cogs?

I watched several YT-tutorials, but I didn't understand it well.

The only thing I've done, is I wrote the following stuff into my main.py

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

Solution

  • Im using this, to handle Cogs:

    main.py:

    ...
    from CogFileFame import CogName
    
    client = commands.Bot(command_prefix=".", intents=discord.Intents.all(), case_insensitive=True)
    
    @client.event
    async def on_ready():
        await setup(client)
    
    async def setup(client: commands.Bot):
        await client.add_cog(Cogname(client))
    

    CogFileName.py:

    class CogName(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
    
        // commands in cogs start like this:
        @commands.command()
        async def ping(self, message)
    
     
        // events in cogs start like this:
        @commands.Cog.listener()
        async def on_message(self, message):