【问题标题】:How to create an custom Exception/Error Handler class in discord.py which would handle command specific errors?如何在 discord.py 中创建一个自定义异常/错误处理程序类来处理特定于命令的错误?
【发布时间】:2021-04-23 21:22:36
【问题描述】:

我正在尝试在我的 discord 机器人中创建自定义错误处理程序。所以我有一个名为 MyBot 的 Cog,我正在尝试创建一个错误处理程序类来处理与此类相关的错误。

我有以下代码,但它不起作用。

我希望在遇到 BadArguement 错误(当我调用 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)

如何构建类以使这种层次结构起作用?

【问题讨论】:

    标签: python inheritance error-handling discord.py


    【解决方案1】:

    您可以使用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))
    

    参考:

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2021-03-12
      • 2010-12-26
      相关资源
      最近更新 更多