【问题标题】:if all argument value error for pay all command economy bot如果支付所有命令经济机器人的所有参数值错误
【发布时间】:2021-03-13 02:24:59
【问题描述】:

我的代码有效,但是当我包含 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'

【问题讨论】:

  • 在尝试转换为 int 后,您无法检查字符串,因为如果它不是有效数字,那么已经太迟了。在任何情况下,您都需要防范异常,以防用户键入其他类型的垃圾。

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


【解决方案1】:

改变这个:

    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
            

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

【讨论】:

    【解决方案2】:

    改变这个:

    
    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
    

    收件人:

    bal = await update_bank(ctx.author)
    if amount == 'all':
        amount = bal[0]
    else:
        try:
            amount = int(amount)
        except ValueError:
            await ctx.send(f'Invalid amount({amount}) Must be "all" or an integer')
            return
    
    amount = int(amount) #This has to be after we define "amount == 'all'"
     #THE REST OF THE CODE
    
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2018-11-03
      • 2020-10-26
      • 2021-02-02
      • 2021-08-11
      • 1970-01-01
      • 2021-04-05
      • 2021-04-21
      • 2021-01-12
      相关资源
      最近更新 更多