我正在用Python制作一个discord的机器人.我使用一个JSON文件来存储我的机器人所在的服务器的设置.(例如:模块).当有人运行/Level切换命令时,它会将‘LEVEL_MODULE’值从0修改为1.(0表示打开,1表示关闭.)它确实可以工作,但有一个问题:It clears every other value.我希望这些值保持不变,如果用户禁用了审核模块(1),而有人切换了一个模块,则该值不应该返回到0.它应该only编辑该值.我在互联网上搜索了很长时间,想知道如何在不删除或更改所有其他值的情况下编辑此值,但我没有找到答案.有什么主意吗?拜托了,谢谢你.
记住:它应该ONLY编辑这个值,而不是其他所有东西.不应该发生的是,如果用户具有混合切换,则在切换模块时不应该使用其缺省值.
代码:
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:
with open("database\\wae.json", encoding="utf-8") as f:
data = json.load(f)
if str(interaction.guild.id) in data:
lvlmod = data[str(interaction.guild.id)]['level_module']
if lvlmod == 0:
with open("database\\wae.json", encoding="utf-8") as f:
data = json.load(f)
data[str(interaction.guild.id)] = {}
data[str(interaction.guild.id)]['level_module'] = 1
with open("database\\wae.json", "w+") as fa:
json.dump(data, fa)
await interaction.response.send_message("✅ Successfully disabled the Leveling module.")
else:
with open("database\\wae.json", encoding="utf-8") as f:
data = json.load(f)
data[str(interaction.guild.id)] = {}
data[str(interaction.guild.id)]['level_module'] = 0
with open("database\\wae.json", "w+") as fa:
json.dump(data, fa)
await interaction.response.send_message("✅ Successfully enabled the Leveling module.")
bot.tree.add_command(levelmds)
我的JSON文件:
{"1172011084274733076": {"level_module": 0, "moderation_module": 0, "test": 1}}
执行该命令后的结果:
文本格式:
{"1172011084274733076": {"level_module": 1}}