You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Discord机器人存款命令支持all和half代替指定金额

如何让Discord机器人存款命令支持"all"和"half"参数?

原始代码

@client.command(aliases=['dep'])
async def deposit(ctx, amount = None):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()

    if amount == None:
        await ctx.send("Enter the amount you want to deposit")
        return

    bal = await update_bank(ctx.author)

    amount = int(amount)
    if amount>bal[0]:
        await ctx.send("You don't have that much money!")
        return
    if amount<100:
        await ctx.send("You cannot deposit less than 100!")
        return
  
    await update_bank(ctx.author, -1*amount)
    await update_bank(ctx.author, amount, "bank")

    await ctx.send(f"You have deposited {amount} to bank!")

修改方案

要让命令支持"all"和"half"关键词,需要在转换金额为整数前先判断输入内容,对应计算存款金额,同时处理无效输入的情况。具体修改如下:

  1. 在获取用户现金余额后,优先判断输入是否为指定关键词,计算对应存款金额
  2. 新增输入合法性校验,处理既不是关键词也不是有效数字的情况
  3. 保留原有的金额限制逻辑(不能超过现金余额、不能低于100)

修改后的完整代码

@client.command(aliases=['dep'])
async def deposit(ctx, amount = None):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()

    if amount == None:
        await ctx.send("Enter the amount you want to deposit (or use 'all'/'half')")
        return

    bal = await update_bank(ctx.author)
    deposit_amount = 0

    # 处理关键词逻辑,大小写不敏感
    if amount.lower() == "all":
        deposit_amount = bal[0]
    elif amount.lower() == "half":
        deposit_amount = bal[0] // 2  # 整数除法避免小数金额
    else:
        # 尝试转换为整数,捕获无效输入
        try:
            deposit_amount = int(amount)
        except ValueError:
            await ctx.send("Invalid input! Use a number, 'all', or 'half'")
            return

    # 原有金额校验逻辑
    if deposit_amount > bal[0]:
        await ctx.send("You don't have that much money!")
        return
    if deposit_amount < 100:
        await ctx.send("You cannot deposit less than 100!")
        return
  
    await update_bank(ctx.author, -1 * deposit_amount)
    await update_bank(ctx.author, deposit_amount, "bank")

    await ctx.send(f"You have deposited {deposit_amount} to bank!")

关键修改说明

  • 用lower()处理关键词,确保输入"ALL"或"Half"这类大小写混合的内容也能生效
  • 新增try-except捕获非数字非关键词的无效输入,给用户明确提示
  • 将原amount变量拆分为deposit_amount,避免关键词与数字变量混淆
  • 更新初始提示文案,告知用户可使用的关键词选项
  • 用整数除法//处理"half"逻辑,保证金额为整数,符合常规货币场景

内容的提问来源于stack exchange,提问作者user20907688

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:50:32