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

Discord Bot开发:实现命令调用时指定用户数值独立递增

问题解决:Discord机器人用户计数独立递增

问题原因分析

你的代码存在两个核心问题导致所有用户计数同步增长:

  1. 条件判断逻辑错误:if ctx.message.content == "Tali" or "tali" 这种写法等价于if (ctx.message.content == "Tali") or True,因为字符串"tali"本身是布尔真值,所以第一个if分支永远会被触发,不管你输入的用户名是什么。每次调用命令都会执行tali_cap的递增操作,而后面的elif分支完全不会执行,导致输出时虽然显示的是指定用户名,但数值用的是tali_cap的累计值。
  2. 不必要的列表存储:你用单个元素的列表来存计数(比如tali_cap = [0])完全没必要,直接用整数变量即可,列表在这里只会增加代码复杂度。

修复方案

方案1:修复原代码的逻辑错误

把条件判断改为针对arg(即命令传入的用户名参数)进行判断,同时把列表替换为普通整数变量:

tali_cap = 0
robert_cap = 0
alex_cap = 0
justin_cap = 0

@bot.command()
async def cap(ctx, arg):
    # 统一转为小写,避免大小写敏感问题
    username = arg.lower()
    if username == "tali":
        tali_cap += 1
        await ctx.send(f'{arg} has capped {tali_cap} time(s).')
    elif username == "robert":
        robert_cap += 1
        await ctx.send(f'{arg} has capped {robert_cap} time(s).')
    elif username == "alex":
        alex_cap += 1
        await ctx.send(f'{arg} has capped {alex_cap} time(s).')
    elif username == "justin":
        justin_cap += 1
        await ctx.send(f'{arg} has capped {justin_cap} time(s).')
    else:
        await ctx.send("I don't know that person.")

方案2:用字典优化代码(更简洁易维护)

如果后续要添加更多用户,用字典管理计数会更高效,不需要重复写多个elif:

# 初始化用户计数字典,键是用户名(小写),值是计数
user_caps = {
    "tali": 0,
    "robert": 0,
    "alex": 0,
    "justin": 0
}

@bot.command()
async def cap(ctx, arg):
    username = arg.lower()
    if username in user_caps:
        user_caps[username] += 1
        await ctx.send(f'{arg} has capped {user_caps[username]} time(s).')
    else:
        await ctx.send("I don't know that person.")

这样修改后,每个用户的计数会独立递增,输入!cap tali会增加tali的计数,输入!cap robert只会增加robert的计数,不会互相影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:55:30