【问题标题】:executing a function when a cog is loaded加载 cog 时执行函数
【发布时间】:2021-10-26 22:39:38
【问题描述】:

我一直在寻找一种方法来使 cog 在加载/重新加载时与 cog 一起执行一个函数,但我发现没有这样的函数或有人在谈论它,
所以我想出了 INGENIOUS 尝试使用字符串来调用 cog 中的函数的想法。

我尝试了几件事,主要是 evalgetattr 的组合,但我没有成功获得工作代码,因为......大脑太smol了。

希望这会清楚我想要做什么:

齿轮test.py

class test(commands.Cog):

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

这是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

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    由于 Discord Cog 是一个类,因此可以调用 __init__ 方法,该方法将在初始化时执行。我有一个类似的设置,每当加载/重新加载 Cog 时,都会执行一组指令。

    示例代码(基于您的示例):

    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')
    
    

    添加到代码 cmets,您可以使用 staticmethod 装饰器使 post_init 函数成为静态方法。如果您的函数不需要访问实例/类变量,建议使用静态方法。

    我强烈建议您查看 discord.py 文档,它将为您提供有关扩展和 Cogs 的宝贵信息。

    来源:

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 2019-10-27
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多