You need to enable JavaScript to run this app. discord.py开发时同一用户ID重复两次写入JSON字典如何解决
优惠活动
大模型
产品
解决方案
定价
更多

discord.py开发时同一用户ID重复两次写入JSON字典如何解决

问题原因

  • 类型不匹配:Discord.py中user.id为整数类型,JSON序列化时会自动将数字键转换为字符串类型,你从文件读取的users字典键全为字符串,用整数user.id判断是否存在永远返回False,每次事件触发都会重新插入同个ID的键值对。
  • 文件名大小写不一致:代码中读取用Users.json(大写U),写入用users.json(小写u),大小写敏感的操作系统下会读写两个不同文件,每次读取的都是旧空数据,导致重复插入。
  • 异步时序问题:未限制写入频率时,短时间内多次触发事件可能导致IO操作叠加,出现JSON文件写入重复键的格式异常(JSON标准本身不允许重复键,该异常是多次写入冲突导致)。

修复方案

1. 统一文件命名

所有读写操作使用相同大小写的文件名,推荐统一用小写users.json。

2. 匹配ID类型

修改update_data逻辑,将user.id转为字符串后再做存在性判断,和JSON序列化后的键类型保持一致。

3. 优化事件逻辑

新增过滤规则,忽略机器人自身发送的消息,减少不必要的IO操作。

修复后的完整代码

import json
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@client.event
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)
    await update_data(users, member)
    with open('users.json', 'w') as f:
        # 加indent参数格式化JSON,方便查看,可自行删除
        json.dump(users, f, indent=2)

@client.event
async def on_message(message):
    # 过滤机器人自身的消息,避免不必要的写入
    if message.author.bot:
        return
    with open('users.json', 'r') as f:
        users = json.load(f)
    await update_data(users, message.author)
    with open('users.json', 'w') as f:
        json.dump(users, f, indent=2)
    # 后续如果需要添加指令功能,必须保留这行
    await client.process_commands(message)

async def update_data(users, user):
    # 转为字符串和JSON键类型匹配
    user_id = str(user.id)
    if user_id not in users:
        users[user_id] = {}

额外优化建议

如果你的机器人用户量较大,频繁读写文件会影响性能,可以将users数据缓存到内存中,定时批量写入到JSON文件,降低IO频率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 07:33:01