首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >discord.py-rewrite -通过cogs处理异常

discord.py-rewrite -通过cogs处理异常
EN

Stack Overflow用户
提问于 2019-05-03 06:13:56
回答 2查看 721关注 0票数 0

因此,在我的主文件bot.py上,我有:

代码语言:javascript
复制
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异常:

代码语言:javascript
复制
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.pyon_command_error()函数中发送所需的消息。取而代之的是,异常在控制台中打印出来,我得到了这个错误消息:

代码语言:javascript
复制
Command raised an exception: MyException: arg

谁能告诉我如何让机器人在bot.py中用on_command_error()说出想要的消息

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-03 07:58:48

命令只会引发从CommandError派生的异常。当您的命令引发非CommandError异常时,它将被包装在CommandInvokeError

代码语言:javascript
复制
@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)
票数 2
EN

Stack Overflow用户

发布于 2019-05-03 08:16:46

@Patrick Haugh非常感谢你的信息,我从commands.CommandError而不是Exception继承了MyException类,从而解决了这个问题。

基本上是这样写的:

代码语言:javascript
复制
class MyException(commands.CommandError):
        def __init__(self, argument):
            self.argument = argument

而不是:

代码语言:javascript
复制
class MyException(Exception):
        def __init__(self, argument):
            self.argument = argument

然后离开:

代码语言:javascript
复制
@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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55960925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档