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

如何在discord.py中统计并展示用户的命令使用次数?

实现命令使用次数跟踪的方案

嘿,我来帮你搞定命令使用次数跟踪的需求!下面是针对你的场景给出的具体实现方案,结合你提到的「Ignore Selection Statements」命令来举例:

1. 先准备计数存储

首先你需要一个地方来存每个命令的使用次数,如果只是短期运行(比如单次会话),用全局字典就足够;要是需要重启后保留数据,后面再补充持久化的方法。初始化代码如下:

# 全局字典,键是命令名称,值是使用次数
command_counts = {}

2. 在命令逻辑里加入计数递增

每次用户触发「Ignore Selection Statements」命令时,先更新计数,再执行原有逻辑。修改后的代码示例:

def ignore_selection_statements():
    # 定义命令的标识名称
    cmd_name = "Ignore Selection Statements"
    
    # 更新计数:如果命令不在字典里就初始化为0,然后加1
    command_counts[cmd_name] = command_counts.get(cmd_name, 0) + 1
    
    # 这里放你原来的命令逻辑,比如处理选择语句的代码...
    
    # 执行完成后展示当前次数
    print(f"✅ 已执行「{cmd_name}」命令,累计使用次数:{command_counts[cmd_name]}")

3. 可选:添加统计查询命令

如果你想让用户随时查看所有命令的使用情况,可以加一个专门的查询命令:

def show_command_usage_stats():
    print("\n📊 命令使用次数统计:")
    if not command_counts:
        print("   暂无命令使用记录")
        return
    # 按次数排序展示
    for cmd, count in sorted(command_counts.items(), key=lambda x: x[1], reverse=True):
        print(f"- {cmd}: {count} 次")

4. 可选:持久化计数(重启不丢失)

要是希望程序重启后还能保留之前的计数,可以把字典存到JSON文件里:

import json

# 启动时加载已保存的计数
def load_saved_counts():
    global command_counts
    try:
        with open("command_usage.json", "r", encoding="utf-8") as f:
            command_counts = json.load(f)
    except FileNotFoundError:
        # 文件不存在就初始化空字典
        command_counts = {}

# 退出时保存计数(或者每次更新后保存)
def save_current_counts():
    with open("command_usage.json", "w", encoding="utf-8") as f:
        json.dump(command_counts, f, indent=2, ensure_ascii=False)
  • 记得在程序启动时调用load_saved_counts(),在程序退出前或者每次命令执行后调用save_current_counts()来保存数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:48:51