如何在Python中使用此错误处理?

时间:2019-06-04 15:49:26

标签: python discord discord.py

我正在尝试添加一个新的错误处理程序,但是不知何故它不起作用。如果用户忘记了这三个参数之一,我想发送一条消息。

代码:

async def redeem(ctx, arg1, arg2, arg3):
    allowed_countries = ['US', 'GB', 'DE']
    accounts = []
    keys = []
    country = arg1.upper()
    keyGrab(keys)
    if country in allowed_countries:
        f = open('Accounts/' + str(country) + '.txt', 'r')
        for line in f:
            clean = line.split('\n')
            accounts.append(clean[0])

        f.close()
    if arg1 is None or arg2 is None or arg3 is None
        return await (ctx.send('Please enter in this format ...'))
    if country not in allowed_countries:
        return await (ctx.send('Sorry But the Country you Specified is Not Currently Offered'))
    if arg3 not in keys:
        return await (ctx.send('Sorry but you entered an invalid product key.'))

以下内容无效:

if arg1 is None or arg2 is None or arg3 is None
    return await (ctx.send('Please enter in this format ...'))

其他一切都很好。

2 个答案:

答案 0 :(得分:0)

错误处理通常使用try/except完成,看起来您只是在进行边界检查或输入检查。无论哪种方式,您都在:的末尾缺少if。此外,由于可以将if的值视为None,因此可以缩短Falsey语句。

if arg1 or arg2 or arg3:
    return await (ctx.send('Please enter in this format ...'))

答案 1 :(得分:0)

Discord.py提供了另一种方法来处理错误,而不必通过自动调用on_command_error,传递上下文和引发的错误来手动检查每个参数。可以传递bunch of different errors,但我们真正关心的唯一一个是MissingRequiredArgument,因此我们将使用if语句进行检查。

from discord.ext import commands

bot = commands.Bot(...)

...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.MissingRequiredArgument):
        await ctx.send(f'Required arguments are missing for "{ctx.command}". \n'
                       f'```Usage: {ctx.prefix}{ctx.command} {ctx.command.signature}```')

        # you might also like
        # await ctx.send(f'Required arguments are missing for "{ctx.command}". '
        #                f'For help using this command, enter\n```{ctx.prefix}help {ctx.command.qualified_name}```')

如果您不熟悉上面使用的某些语句(例如ctx.prefixctx.command.qualified_name),则可能有助于检查ContextCommand的文档。

在这里,第一个ctx.send打印一条类似于

的消息
  

“兑换”缺少必需的参数。

     
Usage: !redeem <arg1> <arg2> <arg3>

第二个ctx.send打印类似

  

“兑换”缺少必需的参数。要获得使用此命令的帮助,请输入

     
!help redeem

整洁的事情是所有命令都默认使用它。这样一来,您不必检查每个参数就很麻烦。

如果您要检查错误是否是由特定命令引起的,只需嵌套一个if语句。

    if isinstance(error, commands.errors.MissingRequiredArgument):
        if ctx.command.name == 'redeem':
            # do something special
            ...