BluePigeon
BluePigeon

Reputation: 1812

discord.py-rewrite - How to use custom checks in cogs?

So, on my bot.py main file, I have:

class Bot(commands.Bot):

    # BOT ATTRIBUTES

    class default_cooldown:
        maxcommands = ...
        seconds = ...
        mode = ...

    class my_exception(commmands.CommandError): pass

    def my_check(self):
        def predicate(ctx):
            if ctx.author in a_list: return True
            raise self.my_exception

bot = Bot(...)

Now I also have a cog file where I want to use the Bot().my_check() check and my Bot().default_cooldown() class:

class Cog(commands.Cog):

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

    @commands.command()
    @self.bot.my_check()
    @commands.cooldown(self.bot.default_cooldown().maxcommands, self.bot.default_cooldown().seconds, self.bot.default_cooldown().mode)
    async def a_command(self, ctx):
        pass

But I get an error, saying that self is not defined on my check and cooldown. Can anyone please help me fix this problem?

Upvotes: 1

Views: 2504

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

Methods are created once when the class object is created, not individually for each instance. You have a couple of options:

  1. Factor out the code that need to appear in both places to a third module that contains just that code, then import that into both of your other files
  2. Move your Bot definition into a separate module from the execution of your bot, and make my_check a staticmethod. Then you can access it through Bot.my_check instead of through the specific instance.
  3. Define your cog inside setup so that the class is aware of the bot instance when it is created.

Upvotes: 1

Related Questions