discord.py跨多个Cog调用异步命令的报错问题求助
问题解决:Discord.py跨Cog调用clear命令
错误原因分析
'OBJECT' object has no attribute 'clear':当前Cog实例(self)没有clear方法,该方法属于另一个独立Cog的类成员,无法直接通过当前Cog的self调用。- 导入方式错误:直接
from TARGETCOGNAME import clear无效,因为clear是目标Cog类的成员方法,并非模块级别的独立函数。 on_message参数定义错误:监听器的正确参数应为(self, message),你之前写的(ctx, message)会导致参数不匹配。
两种可行解决方案
前提准备
假设你的消息清理Cog代码如下(类名为ClearCog):
# cogs/clear_cog.py from discord.ext import commands class ClearCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['kl']) @commands.has_permissions(manage_messages=True) async def clear(self, ctx, amount=5): await ctx.message.delete() await ctx.channel.purge(limit=amount) await ctx.send(f'{amount} messages have been deleted.', delete_after=5)
确保该Cog已通过bot.load_extension("cogs.clear_cog")加载到机器人中。
方案一:获取目标Cog实例直接调用方法
适合需要跳过命令权限检查的场景(比如自动清理无需管理员权限):
# cogs/auto_mod_cog.py from discord.ext import commands class AutoModCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): # 跳过机器人自身消息,避免循环触发 if message.author.bot: return # 示例触发条件:消息包含违规关键词 if "违规内容" in message.content: # 获取ClearCog的实例 clear_cog = self.bot.get_cog("ClearCog") if not clear_cog: print("错误:ClearCog未加载") return # 从message生成上下文对象 ctx = await self.bot.get_context(message) # 调用clear方法,指定要删除的消息数量 await clear_cog.clear(ctx, amount=1)
方案二:通过命令对象的invoke方法调用
适合需要保留命令原有权限检查逻辑的场景:
# cogs/auto_mod_cog.py from discord.ext import commands class AutoModCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message): if message.author.bot: return if "违规内容" in message.content: # 获取clear命令对象 clear_command = self.bot.get_command("clear") if not clear_command: print("错误:clear命令未找到") return # 生成上下文对象 ctx = await self.bot.get_context(message) # 调用命令(会自动触发权限检查) await clear_command.invoke(ctx, amount=1)
关键注意事项
- 如果自动清理场景不需要权限检查,优先使用方案一,直接调用Cog实例的
clear方法,避免权限拦截。 - 必须确保目标Cog已正确加载,否则
get_cog或get_command会返回None。
内容的提问来源于stack exchange,提问作者Daddy Myers
相关产品推荐
相关产品推荐

