我正在用Python制作一个Discord机器人。我使用JSON文件来存储我的机器人所在的服务器的设置。(例如:模块)。当有人运行/level toggle命令时,它会将“level_module”值从0修改为1。(0打开,1关闭。)。它确实有效,但有一个问题:
它清除其他所有值。
我希望这些值保持不变,如果用户禁用了审核模块(1),并且有人切换了某个模块,则该值不应返回到0。它应该
只有
编辑该值。我在互联网上搜索了很长时间,想知道如何在不删除或更改所有其他值的情况下编辑此值,但没有找到答案。知道吗?求你了,谢谢你。
记住:它应该
仅
编辑该值,而不是其他所有值。不应该发生的是,如果用户有混合切换,则在切换模块时不应该转到默认值。
代码:
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}}