【问题标题】:How to error handle TypeError with discord.py如何使用 discord.py 错误处理 TypeError
【发布时间】:2021-06-24 02:11:37
【问题描述】:

我正在学习如何使用 discord.py 创建一个不和谐机器人,但每当我弄乱我的代码时,有时我会收到“TypeError”错误。

例如

@bot.command()
async def compress(ctx):
    directory = '/pictures/'
    picture = '83680009_p0.png'
    path = directory+picture
    img = Image.open(path)
    img.save(path, optimize=True, quality = 85)
    img.save()

该代码中有一个错误,错误在directory = '/pictures/' 行中。 'pictures/' 之前不应该有反斜杠。所以,当我尝试运行 compress 命令时,我得到了错误

TypeError: on_command_error() missing 1 required positional argument: 'error'

有没有办法处理错误并在发生此错误时向机器人发送消息?谢谢。顺便说一句,这是我第一次提出问题,所以如果我遗漏了什么,请告诉我。

【问题讨论】:

    标签: error-handling discord.py typeerror


    【解决方案1】:

    正如错误所说,您的 on_command_error 缺少一个参数。您还没有真正提供它的代码,但正确的方法应该是:

    @bot.event
    async def on_command_error(ctx, error):
        ...
    

    此外,错误处理程序仅处理 discord.py 错误,而不是 NameErrorAttributeError... 要处理它们,您应该使用简单的 try/except 块。

    在错误处理程序中处理“正常”错误

    @bot.event
    async def on_command_error(ctx, error):
        # If an error happens inside the command,
        # discord.py wraps it around with `commands.CommandInvokeError` 
        # which has the `original` attribute which is the "original" error
        error = getattr(error, "original", error)
        if isinstance(error, TypeError):
            ...
        elif isinstance(error, commands.MissingPermissions):
            ...
        # And so on...
    

    我不建议这样做,命令的编码方式应该永远不会引发此类错误。

    【讨论】:

    • 感谢您的回答,当self 不在齿轮中时,我不小心将其用作参数。有没有办法处理TypeErrorNameError 等,比如 discord.py 错误和处理方式?我不想为我的每个命令编写一个 try /except 块,因为它很可能我在那里放了一个错误。
    【解决方案2】:

    它说函数缺少一个参数“错误”。要解决这个问题:

    @bot.event
    async def  on_command_error(ctx, error):
    

    如果你在一个齿轮里,

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
    

    【讨论】:

    • 感谢您的回答,我使用self 作为on_command_error 函数的参数,但我不在齿轮中。
    • 如果它不在类或 cog 中,请不要添加 self。
    猜你喜欢
    • 2023-02-11
    • 2020-09-03
    • 2021-02-24
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多