首页 > 解决方案 > 如果支付所有命令经济机器人的所有参数值错误

问题描述

我的代码有效,但是当我包含 pay 'all' 命令时,它似乎给了我一个错误。 我希望机器人基本上在我告诉它“.pay @example#0001 all”时选择所有“bal”

我的代码:

@client.command(aliases=['send'])
async def pay(ctx, member : discord.Member, amount = None):
    await open_account(ctx.author)
    await open_account(member)
    
    if amount == None:
        await ctx.send('Please enter the amount')
        return

    bal = await update_bank(ctx.author)
   


    amount = int(amount)
    if amount == 'all':     #This
        amount = bal[0]     #Wont work

    if amount>bal[1]:
        await ctx.send('You do not have that much money!')
        return
    if amount<0:
        await ctx.send('Amount must be positive!')
        return

    await update_bank(ctx.author,amount, 'wallet')
    await update_bank(member,-1*amount,'bank') 

    await ctx.send(f'{ctx.author.mention} Payed {amount} coins! How generous!')

错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: 'all'

标签: pythonpython-3.xdiscorddiscord.pydiscord.py-rewrite

解决方案


改变这个:

    amount = int(amount)
    if amount == 'all':     #This
        amount = bal[0]     #Wont work

对此:

    if amount == 'all':     #This
        amount = bal[0]     #Wont work
    else:
        try:
            amount = int(amount)
        except ValueError:
            await ctx.send(f'Invalid amount({amount}) Must be "all" or an integer')
            return
            

这里的想法是您要检查是否发送了“全部”,如果没有,请尝试将其转换为整数。如果您无法转换为 int() ,您将得到一个 ValueError ,如您所述。捕获 ValueError,然后向用户回复一条消息。


推荐阅读