因此,在我的主文件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_condition,程序就会引发MyException异常,但是机器人不会在bot.py的on_command_error()函数中发送所需的消息。取而代之的是,异常在控制台中打印出来,我得到了这个错误消息:
Command raised an exception: MyException: arg谁能告诉我如何让机器人在bot.py中用on_command_error()说出想要的消息
发布于 2019-05-03 07:58:48
命令只会引发从CommandError派生的异常。当您的命令引发非CommandError异常时,它将被包装在CommandInvokeError中
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
if isinstance(error.original, bot.MyException):
await ctx.send("{} went wrong!".format(error.argument))
return
print(error)发布于 2019-05-03 08:16:46
@Patrick Haugh非常感谢你的信息,我从commands.CommandError而不是Exception继承了MyException类,从而解决了这个问题。
基本上是这样写的:
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)https://stackoverflow.com/questions/55960925
复制相似问题