Discord用户名写入JSON重复问题求助(附Python代码)
问题:含特殊字符的Discord用户名重复写入JSON文件
问题根源
你的代码存在两个核心问题导致特殊字符用户名被重复写入:
- 错误的存在性检查逻辑:你将存储用户历史名称的列表
users[str(usersid)]转成字符串来判断用户名是否存在。当用户名包含特殊字符(如双引号、反斜杠)时,JSON序列化后的字符串会对这些字符进行转义(比如"变成\"),导致原用户名和转义后的字符串无法匹配,明明已存在的用户名被判定为不存在,从而重复添加。 - 低效的文件IO操作:每次添加一个用户就写入一次JSON文件,不仅影响性能,还可能引发文件写入冲突。
修复方案
- 直接遍历用户历史名称列表中的字典,提取每个历史名称进行匹配,彻底避免字符串转义的干扰
- 统一在遍历完所有成员后再写入JSON文件,减少IO操作次数
- 优化
cleared的检查逻辑,假设cleared是用户名列表,直接用names not in cleared代替转字符串检查
修正后的代码
import discord from discord.ext import commands from discord.ext import tasks import json from datetime import date @tasks.loop(minutes=30) async def autoUpdateDB(): count = 0 # 统计新增到JSON的用户记录数 debugchannel = bot.get_channel(1134732572816068628) # 调试消息发送频道 # 加载现有数据文件 with open("prevname.json", "r", encoding="utf-8") as f: users = json.load(f) with open("cleared.json", "r", encoding="utf-8") as f: cleared = json.load(f) currentDate = str(date.today()) # 提前转换为字符串,避免重复创建对象 for guild in bot.guilds: for member in guild.members: user_id = str(member.id) current_name = member.name # 跳过已在cleared列表中的用户名 if current_name in cleared: continue # 检查用户是否已有历史记录 if user_id in users: # 遍历用户的历史名称字典,提取所有历史名称做匹配 name_existed = any( current_name in history.values() for history in users[user_id] ) if not name_existed: users[user_id].append({currentDate: current_name}) count += 1 else: # 新用户直接添加历史记录 users[user_id] = [{currentDate: current_name}] count += 1 # 所有成员处理完成后统一写入文件 if count > 0: with open("prevname.json", "w", encoding="utf-8") as f: json.dump(users, f, ensure_ascii=False, indent=4) # 可选:发送调试统计消息 if debugchannel: await debugchannel.send(f"本次更新共新增 {count} 条用户名记录")
关键修改说明
- 替换了
str(users[str(usersid)])的字符串匹配逻辑,改为直接遍历字典提取用户名进行原字符串匹配,彻底解决特殊字符转义导致的匹配失效问题 - 将日期转换操作提前,减少重复计算开销
- 统一在遍历完成后写入文件,提升程序性能并避免潜在的文件写入冲突
- 优化了代码结构,让逻辑更清晰易读
内容的提问来源于stack exchange,提问作者schizophrenic
相关产品推荐
相关产品推荐

