python - 如果支付所有命令经济机器人的所有参数值错误
问题描述
我的代码有效,但是当我包含 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'
解决方案
改变这个:
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,然后向用户回复一条消息。
推荐阅读
- java - 如何在 Spring 的 WebClient 上验证 bean?
- python - 将具有可为空整数数据类型的 pandas DataFrame 保存到 HDF 文件(格式='table')
- elasticsearch - 如何提升与最佳结果相似的替代方案
- mysql - 如何在 MySQL 中为 SET 类型设置超过 1 个默认值?
- blazor - Mat Blazor mat-expansion-panel 移除高程/边框
- ruby - 对使用 reduce 及其实际尝试做的事情感到困惑
- java - 再次点击按钮以确认操作
- c# - 如何向 API 提交包含 536000 个字符的字符串
- python - 使用 tkinter 包几何管理器的帧之间的空间
- c# - 抓取时如何获取Leap Motion的计算变换数据