Discord.py如何将统计的用户频道消息数从字典追加到JSON文件
代码调整与JSON写入实现
你当前的统计逻辑存在问题:全局共用messages列表统计所有匹配消息的总长度,无法正确计算单个用户在单个频道的独立消息数,且键用用户+频道的格式化字符串不利于后续解析,建议先调整统计逻辑,再按如下方式实现JSON写入:
首先在代码头部引入依赖模块:
import json import os # 用于判断本地统计文件是否存在
调整后的完整on_ready事件代码如下:
@client.event async def on_ready(): channels = [] users = [] # 统计用字典,键为(用户ID, 频道ID),值为对应消息数 count_map = {} # 加载待统计的频道列表 for i in dct_channels.values(): for j in i: channels.append(j) # 加载待统计的用户列表 for j in dct_memb.values(): for i in j: users.append(i) # 遍历所有频道统计消息 for channel_id in channels: channel = client.get_channel(channel_id) if not isinstance(channel, discord.TextChannel): continue async for message in channel.history(limit=None): if message.author.id not in users: continue # 生成统计维度键 key = (message.author.id, channel_id) # 计数累加 count_map[key] = count_map.get(key, 0) + 1 # 转换为你要求的存储格式 result_list = [] for (user_id, channel_id), count in count_map.items(): user = client.get_user(user_id) result_list.append({ "name": user.name if user else str(user_id), "channel": channel_id, "total_no_of_messages": count }) # 追加写入JSON文件逻辑 file_path = "message_count.json" # 如果文件已存在,先读取原有内容 if os.path.exists(file_path): with open(file_path, "r", encoding="utf-8") as f: try: old_data = json.load(f) # 合并新旧数据,如需按用户+频道维度去重更新,可在这里补充判断逻辑 old_data.extend(result_list) result_list = old_data except json.JSONDecodeError: # 文件内容损坏时直接用新数据覆盖 pass # 写入最终数据 with open(file_path, "w", encoding="utf-8") as f: json.dump(result_list, f, ensure_ascii=False, indent=2)
关键说明
- 统计逻辑改为按用户ID+频道ID为维度独立计数,避免不同用户、不同频道的统计结果互相干扰
- 写入JSON时默认支持追加:如果本地已有统计文件,会把新统计结果追加到原有列表末尾
- 用
ensure_ascii=False保证用户名里的中文等特殊字符正常显示,indent=2让JSON格式更易读
内容的提问来源于stack exchange,提问作者Hiresh Verma
相关产品推荐
相关产品推荐

