如何在Python中存储多用户数据以开发Discord bot经济系统
实现方案
存储方案选型
优先使用JSON格式的文本文件存储用户数据,比自定义格式的纯TXT更易解析、不易出错,Python原生支持读写操作。你可以用Discord用户的唯一ID作为索引键,存储对应用户的余额等经济数据,结构示例如下:
{ "123456789012345678": { "balance": 100, "register_time": "2024-01-01 12:00:00" }, "876543210987654321": { "balance": 250, "register_time": "2024-01-02 15:30:00" } }
前置依赖
你需要先安装discord.py库用于开发Discord bot:pip install discord.py
核心代码实现
import discord from discord import app_commands import json import os # 数据文件路径 DATA_FILE = "user_economy_data.json" # 加载用户数据 def load_data(): # 如果文件不存在就初始化空数据 if not os.path.exists(DATA_FILE): with open(DATA_FILE, "w", encoding="utf-8") as f: json.dump({}, f) with open(DATA_FILE, "r", encoding="utf-8") as f: return json.load(f) # 保存用户数据 def save_data(data): with open(DATA_FILE, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) # 初始化Bot intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # /balance 指令实现 @tree.command(name="balance", description="查询你的账户余额") async def get_balance(interaction: discord.Interaction): user_id = str(interaction.user.id) data = load_data() # 如果用户没有数据,初始化默认余额 if user_id not in data: data[user_id] = {"balance": 100} # 初始余额可以自行调整 save_data(data) balance = data[user_id]["balance"] await interaction.response.send_message(f"你的当前账户余额为:{balance} 金币", ephemeral=False) # ephemeral设为True可以让返回内容仅用户自己可见 @client.event async def on_ready(): await tree.sync() # 同步全局指令,首次同步可能需要最多1小时生效,测试可同步到指定服务器 print(f"Bot已登录:{client.user}") # 填入你自己的Bot Token启动 client.run("YOUR_BOT_TOKEN_HERE")
注意事项
- 测试阶段推荐将指令同步到指定测试服务器,生效速度更快,只需把
tree.sync()替换为await tree.sync(guild=discord.Object(id=你的服务器ID))即可 - 高频读写场景下可以把数据缓存到内存变量中,每隔固定时间写入一次文件,减少磁盘IO消耗
- 操作文件时可以增加异常捕获逻辑,避免文件损坏导致程序崩溃
- Discord用户ID是唯一不变的,不要用用户名作为索引,避免用户改名后数据丢失
内容的提问来源于stack exchange,提问作者Brandon Smith
相关产品推荐
相关产品推荐

