【发布时间】: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