如何在Discord.py中修改JSON文件值而不覆盖其他数据?
问题解决:Discord机器人切换Leveling模块时保留其他服务器配置
问题根源
你代码里的data[str(interaction.guild.id)] = {}语句会直接清空当前服务器的所有配置条目,替换成空字典后仅设置level_module的值,导致其他配置(比如moderation_module、test)被删除。
修改后的代码
levelmds = app_commands.Group(name="leveling", description="Toggle leveling cmds") @levelmds.command(name="toggle", description="Toggle the leveling module.") @commands.has_permissions(administrator=True) async def count_steam(interaction: discord.Interaction): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message(":x: Only administrators can execute this command.") else: guild_id_str = str(interaction.guild.id) # 仅读取一次JSON文件,减少IO操作 with open("database\\wae.json", encoding="utf-8") as f: data = json.load(f) if guild_id_str in data: # 获取当前level_module的状态并切换 lvlmod = data[guild_id_str]['level_module'] new_value = 1 if lvlmod == 0 else 0 # 直接修改目标键,不清空整个服务器配置 data[guild_id_str]['level_module'] = new_value # 写入修改后的配置,indent参数让JSON格式更易读 with open("database\\wae.json", "w+", encoding="utf-8") as fa: json.dump(data, fa, indent=4) # 发送状态反馈 msg = "✅ Successfully disabled the Leveling module." if new_value == 1 else "✅ Successfully enabled the Leveling module." await interaction.response.send_message(msg) else: # 可选:处理服务器未初始化配置的情况 await interaction.response.send_message(":x: This server has no configuration entry yet.") bot.tree.add_command(levelmds)
关键优化点
- 删除了清空服务器配置的
data[guild_id_str] = {}语句,直接修改目标键值 - 优化了文件读取逻辑,仅读取一次JSON文件,避免重复IO操作
- 新增
indent=4参数,让输出的JSON格式更清晰(可选但推荐)
测试效果
初始JSON内容:
{"1172011084274733076": {"level_module": 0, "moderation_module": 0, "test": 1}}
执行/leveling toggle命令后,JSON内容变为:
{ "1172011084274733076": { "level_module": 1, "moderation_module": 0, "test": 1 } }
可见moderation_module和test的配置被完整保留,仅level_module的值完成了切换。
内容的提问来源于stack exchange,提问作者As2Bax
相关产品推荐
相关产品推荐

