我想向我的 cog 添加一些错误处理,因为所有命令都需要用户的参数。然而,我发现做到这一点的唯一方法是要求每个命令都有自己的错误句柄,这非常耗时,因为我有 50 多个命令都采用这种格式。
如果可能的话,我希望能够创建一个错误处理程序,该处理程序仅适用于该齿轮中的命令。我该怎么办?
命令示例:
@commands.command()
async def poke(self, ctx, tag: Optional[discord.Member]=None, *args):
self.poke = False
await ctx.send(f"{tag.mention} Has been poked by {ctx.author.mention}")
@commands.command()
async def fight(self, ctx, tag: Optional[discord.Member]=None, *args):
self.fight = False
await ctx.send(f"{tag.mention} Has been fought by {ctx.author.mention}")
最佳答案
特定于 Cog 的错误处理可以通过覆盖 cog_command_error
来完成在齿轮类中:
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def poke(self, ctx, tag: Optional[discord.Member] = None, *args):
self.poke = False
await ctx.send(f"{tag.mention} Has been poked by {ctx.author.mention}")
@commands.command()
async def fight(self, ctx, tag: Optional[discord.Member]=None, *args):
self.fight = False
await ctx.send(f"{tag.mention} Has been fought by {ctx.author.mention}")
# Cog error handler
async def cog_command_error(self, ctx, error):
await ctx.send(f"An error occurred in the Test cog: {error}")
关于python - discord.py 对 cog 中每个命令的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71473890/