discord.py-rewrite-通过COG处理异常
因此,在我的主文件discord.py-rewrite-通过COG处理异常,discord,discord.py,discord.py-rewrite,Discord,Discord.py,Discord.py Rewrite,因此,在我的主文件bot.py中,我有: class Bot(commands.Bot): # BOT ATTRIBUTES class MyException(Exception): def __init__(self, argument): self.argument = argument bot = Bot(...) @bot.event async def on_command_error(ctx, error):
bot.py
中,我有:
class Bot(commands.Bot):
# BOT ATTRIBUTES
class MyException(Exception):
def __init__(self, argument):
self.argument = argument
bot = Bot(...)
@bot.event
async def on_command_error(ctx, error):
if isistance(error, bot.MyException):
await ctx.send("{} went wrong!".format(error.argument))
else:
print(error)
现在我还有一个cog文件,有时我想在其中抛出Bot()。MyException
异常:
class Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def a_command(self, ctx):
if a_condition:
raise self.bot.MyException("arg")
当我运行代码时,如果a\u条件
已被验证,程序将引发MyException
异常,但BOT不会在on\u命令中发送所需消息\u error()
函数中的BOT.py
。相反,异常会在控制台中打印出来,我会收到以下错误消息:
Command raised an exception: MyException: arg
有谁能告诉我如何让机器人在
on_command_error()
inBOT.py
中说出所需的消息吗?命令只会引发源自CommandError
的异常。当您的命令引发非CommandError异常时,它将被包装为:
@Patrick Haugh非常感谢您提供的这些信息,我通过从
命令继承MyException
类来解决这个问题。CommandError
而不是Exception
基本上通过写作:
class MyException(commands.CommandError):
def __init__(self, argument):
self.argument = argument
而不是:
class MyException(Exception):
def __init__(self, argument):
self.argument = argument
然后离开:
@bot.event
async def on_command_error(ctx, error):
if isistance(error, bot.MyException):
await ctx.send("{} went wrong!".format(error.argument))
else:
print(error)
@bot.event
async def on_command_error(ctx, error):
if isistance(error, bot.MyException):
await ctx.send("{} went wrong!".format(error.argument))
else:
print(error)