executing a function when a cog is loaded

Viewed 151

i was looking for a way to make the cog executes a function withing the cog when it's loaded/reloaded but i found no such function or anyone talking about it,
so i came up with the INGENIOUS idea of trying to use a string to call a function within the cog.

i tried couple of things, mainly a combination of eval and getattr but i was unsuccessful to get a working code coz... brain too smol.

hope this will clear the idea of what i want to do:

cog test.py

class test(commands.Cog):

    @commands.command()
    async def testReload(self, ctx):
        # do stuff

and this is the reload function in main.py

import cogs

@bot.command()
async def reload(ctx, extension):
    bot.reload_extension(f'cogs.{extension}')
    await ctx.send(f'reloaded {extension}')
    # cogs.(extension).(extension)Reload # something like this
1 Answers

Since Discord Cog is a class, an __init__ method can be called upon, which will be executed upon initialisation. I have a similar setup whereby, whenever a Cog is loaded/reloaded, a set of instructions are performed.

Sample code (Based on your example):

from discord.ext import commands

class test(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

        # Run required instructions, you could even call a function.
        print('Init test Cog')

    # If you have a long list of instructions,
    # you can call this function from __init__.
    def post_init(self):
        # do stuff

    # Sample command
    @commands.command()
    async def greeting(self, ctx):
        await ctx.send(f'Hello, I am a test bot')

# The setup & teardown methods are part of extensions.
# Since you are running the Cog in a different .py file,
# it can be used to add and remove the cog from your main.py.

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


def teardown(bot):
    bot.remove_cog('test')

Adding on to the code comments, you could make the post_init function a staticmethod by using a staticmethod decorator. Using a staticmethod is recommended if your function does not require access to instance / class variables.

I highly recommend you view the discord.py documentation, it will provide you valuable information about extensions and Cogs.

Sources:

Related