如何使discord.py向聊天室发送错误消息

时间:2020-11-09 09:49:16

标签: python-3.x discord discord.py discord.py-rewrite

好的,这是我的代码:

@bot.command(name="randint")
async def random_num(ctx, min_num:int, max_num:int):
    result = random.randint(min_num, max_num)
    embed=discord.Embed(color=0x1e9f9c)
    embed.add_field(name="Random number", value="min:%d, max:%d" % (min_num, max_num), inline=False)
    embed.add_field(name="Result", value=result, inline=False)
    await ctx.send(embed=embed) 

现在我要添加到代码中的是,当输入字符串而不是数字时,它会向使用命令的通道发送错误,如果根本没有输入任何内容,也将执行相同的操作。 我到处搜索,并且也尝试了此操作:

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.BadArgument):
        ctx.send("bruh input numbers")
    if isinstance(error, commands.MissingRequiredArgument):
        ctx.send("bruh you do know you have to input 2 numbers lol")

但是当我尝试这样做时,它根本不会为错误做任何事情,甚至不会在终端中放置错误。

2 个答案:

答案 0 :(得分:1)

它不起作用,因为您切换了参数的顺序。查看on_command_error的{​​{3}},首先需要ctx然后 error。因此,您的isinstance都不起作用(因为ctx永远不是错误的实例)。

您不会再在终端中遇到任何其他错误,因为您将覆盖默认的错误处理程序,默认情况下,该错误处理程序会打印这些错误处理程序,从而不再发生。

您也不会await ctx.send,这会导致您看不到错误,因为您忽略了这种类型的错误。建议raise重新发现所有未发现的错误,以便您仍然可以看到它们。

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("bruh input numbers")
    else if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("bruh you do know you have to input 2 numbers lol")
    else:
        raise error

答案 1 :(得分:0)

您必须等待ctx.send命令。 另外,我不建议对特定命令进行错误处理,因为在randint命令以外的其他命令中触发错误时,错误消息将毫无意义。

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.BadArgument):
        await ctx.send("bruh input numbers")
        raise error
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("bruh you do know you have to input 2 numbers lol")
        raise error