Python Discord机器人:能否导入含装饰器的函数代码?
如何在Discord机器人Cog中复用通用装饰器代码
当然可以实现!你只需要把这些通用的监听器和命令封装成一个基类,然后让你的各个子模块Cog继承这个基类就行,这样所有子模块都会自动拥有这些通用功能,不用重复写代码。
步骤1:创建通用基类文件
先新建一个比如base_cog.py的文件,把你的通用代码放到这个基类里,记得导入需要的依赖:
from discord.ext import commands import sys import os class BaseCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.CommandNotFound): return raise error @commands.group(name='stop', hidden=True) @commands.is_owner() async def stop(self, ctx): await ctx.message.add_reaction('\N{THUMBS UP SIGN}') await self.bot.logout() sys.exit() @commands.group(name='reload', hidden=True) @commands.is_owner() async def reload(self, ctx): await ctx.message.add_reaction('\N{THUMBS UP SIGN}') await self.bot.logout() sys.stdout.flush() os.execv(sys.executable, [sys.executable, __file__])
步骤2:让子模块继承基类
接下来修改你的各个子模块(比如updates.py),让它们继承BaseCog而不是直接继承commands.Cog,记得调用父类的初始化方法:
from discord.ext import commands from base_cog import BaseCog # 导入刚才的基类 class Updates(BaseCog): # 继承BaseCog def __init__(self, bot): super().__init__(bot) # 必须调用父类的__init__方法,确保bot实例被正确传递 # 这里可以添加Updates类专属的初始化逻辑或属性 if __name__ == "__main__": token = 'XXXXXXXXXXXXXXXXXXX' prefix = '!' bot = commands.Bot(command_prefix=commands.when_mentioned_or(prefix), description='Useless - Updates') bot.add_cog(Updates(bot)) bot.run(token)
额外小提示
- 如果某个子模块需要自定义
on_command_error逻辑,直接在子类里重新定义这个方法就行,Python会自动使用子类的实现覆盖父类的。 - 确保
base_cog.py和你的子模块文件在同一个目录下,或者把它所在的目录添加到Python的搜索路径里,避免导入错误。
内容的提问来源于stack exchange,提问作者sehn




