如何在Discord Bot中实现用户答对赌博问题时计数自动累加功能
Discord Bot 猜数字计数功能修复方案
现有代码核心问题
- 同时初始化了
commands.Bot和discord.Client两个客户端实例,属于冗余错误写法,且最终启动时变量名拼写错误,会直接导致程序无法运行 - 计数存储使用
set集合结构,集合自带去重特性,重复添加1只会保留一个元素,完全无法实现累加效果 - 未按用户维度区分计数,所有用户共享同一个存储,无法统计单个用户的累计答对次数
- 变量命名为
json_file但未实现任何本地持久化逻辑,Bot重启后所有计数数据会全部丢失
修复后完整代码
import discord from discord.ext import commands import random import json # 统一只用commands.Bot实例即可 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # 计数存储路径 COUNT_FILE = "gamble_count.json" # 启动时读取本地已存储的计数数据 def load_count(): try: with open(COUNT_FILE, 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: # 首次运行没有文件时返回空字典 return {} # 计数更新时写入本地文件 def save_count(count_data): with open(COUNT_FILE, 'w', encoding='utf-8') as f: json.dump(count_data, f, ensure_ascii=False, indent=2) user_count = load_count() @bot.event async def on_ready(): print('ready') @bot.command() async def Gamble(ctx, num): # 校验输入是否为合法数字 if not num.isdigit(): await ctx.send("请输入1-3之间的有效数字") return guess_num = int(num) if guess_num <1 or guess_num >3: await ctx.send("请输入1-3之间的有效数字") return target = random.randint(1,3) user_id = str(ctx.author.id) if guess_num == target: # 用户不存在时默认计数为0,答对加1 user_count[user_id] = user_count.get(user_id, 0) + 1 save_count(user_count) await ctx.send(f"Congratulations! you won 1 Tes,当前累计答对次数:{user_count[user_id]}") print(f"用户{ctx.author.name}答对,累计次数:{user_count[user_id]}") else: await ctx.send('Better luck next time') print(f"用户{ctx.author.name}答错,当前累计次数:{user_count.get(user_id, 0)}") bot.run('你的TOKEN')
补充说明
- 代码已添加输入合法性校验,避免用户输入非数字、超出范围的内容导致程序报错
- 计数按用户ID独立存储,每个用户的答对次数互不影响
- 所有计数会实时写入本地
gamble_count.json文件,Bot重启后数据不会丢失 - 运行前需要在Discord开发者后台开启Bot的相关权限,否则命令无法触发
内容的提问来源于stack exchange,提问作者Python_Master
相关产品推荐
相关产品推荐

