discord.py运行命令写入JSON服务器配置报JSONDecodeError问题求助
报错根因
你遇到的json.decoder.JSONDecodeError是读取JSON文件时的典型报错,触发原因包括:
serverconfigs.json文件为空,没有任何内容- 文件内的JSON格式不合法
- 程序首次运行时该文件不存在
现有代码的问题
除了JSON文件本身的问题,你的代码还存在多个逻辑错误:
- 变量名错误:加载JSON得到的变量是
data,但后续你调用了未定义的configData["Servers"] - 类型使用错误:
serverdata是字典类型,没有append方法,append是列表的专属方法 - 读写逻辑错误:使用
r+模式打开文件时,加载JSON后直接dump会导致内容追加、格式混乱,且你没有对加载的data做任何修改就执行了dump - 数据为空:配置项里的
guildid、guildname没有赋值,存储的是空值 - 没有去重逻辑:多次执行命令会重复添加同一个服务器的配置
修复实现(命令触发版本)
首先会自动处理配置文件初始化逻辑,文件不存在/为空/格式错误时自动生成合法初始结构:
import json import discord from discord.ext import commands # 按需修改你的机器人命令前缀和intents权限 client = commands.Bot(command_prefix='!', intents=discord.Intents.all()) CONFIG_PATH = "./serverconfigs.json" # 初始化全局配置 try: with open(CONFIG_PATH, "r", encoding="utf-8") as f: config = json.load(f) if "Servers" not in config: config["Servers"] = [] except (FileNotFoundError, json.JSONDecodeError): config = {"Servers": []} with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False) @client.event async def on_ready(): print(client.user.name) print(client.user.id) print('Client ready!') @client.command() async def test1(ctx): # 排除私聊场景 if not ctx.guild: await ctx.send("该命令只能在服务器中使用") return # 配置去重校验 for server in config["Servers"]: if server["guildid"] == str(ctx.guild.id): await ctx.send("当前服务器配置已存在") return # 构造新配置 new_server_config = { "guildid": str(ctx.guild.id), "guildname": ctx.guild.name, "bannedwords": [], "blacklistedchannels": [], "modrole": [] } # 更新配置并持久化写入 config["Servers"].append(new_server_config) with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False) await ctx.send('服务器配置已新增成功') # 替换为你自己的机器人token client.run("你的机器人token")
切换为加入服务器自动触发的实现
只需要新增on_guild_join事件即可,逻辑和命令触发基本一致,参数替换为事件传入的guild对象:
@client.event async def on_guild_join(guild): # 去重校验 for server in config["Servers"]: if server["guildid"] == str(guild.id): return # 构造新配置 new_server_config = { "guildid": str(guild.id), "guildname": guild.name, "bannedwords": [], "blacklistedchannels": [], "modrole": [] } # 写入配置 config["Servers"].append(new_server_config) with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False)
其他功能模块可以直接读取全局config变量里的Servers列表获取对应服务器的配置。
内容的提问来源于stack exchange,提问作者pythonguy
相关产品推荐
相关产品推荐

