如何在discord.py中创建自定义异常/错误处理程序类,该类将处理命令特定的错误?

2024-10-03 13:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在discord bot中创建自定义错误处理程序。因此,我有一个名为MyBot的Cog,我正在尝试创建一个错误处理程序类,该类将处理与该类相关的错误

我有下面的代码,它不工作

我希望在遇到错误时(当我调用roll命令时)调用roll_error(),但它只是在控制台上引发了错误,并且没有返回任何结果

# BaseErrorHandler.py

from discord.ext import commands

class ErrorHandler(commands.errors.CommandError):

    # Create functions to handle errors globally
    
    pass
# BotErrorHandler.py 

import ErrorHandler
from discord.ext import commands

class BotErrorHandler(ErrorHandler):

    # Create functions to handle errors related to MyBot

    @commands.command()
    async def roll(self):
        pass

    @roll.error
    async def roll_error(self, ctx, error):
        if isinstance(error, errors.BadArgument):
            await ctx.send('Please enter a valid number')
# MyBotCog.py
import BotErrorHandler
from discord.ext import commands

class MyBot(commands.Cog, BotErrorHandler):

    def __init__(self, bot, *args, **kwargs):
        self.bot = bot

    @commands.command()
    async def roll(self, ctx, low: int, high: int):
        await ctx.send(random.randint(low, high)

如何构造类以使此层次结构正常工作


Tags: frompyimportselfdefbot错误error
1条回答
网友
1楼 · 发布于 2024-10-03 13:24:55

您可以使用Cog.cog_command_error函数来处理cog中的所有错误

class SomeCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def foo(self, ctx):
        raise commands.CommandInvokeError("Something went wrong")

    async def cog_command_error(self, ctx, error):
        # Handle the errors from the cog here
        if isinstance(error, commands.CommandInvokeError):
            await ctx.send("Whatever")


bot.add_cog(SomeCog(bot))

参考资料:

相关问题 更多 >