迁移可用脚本至新Cog后,discord.py出现JSONDecodeError报错
解决Discord.py Cog迁移后的JSONDecodeError问题
看起来你遇到的JSONDecodeError主要是因为文件数据读取/写入逻辑错误,加上Cog结构下的方法定义问题导致的。咱们一步步拆解问题并修复:
报错根源分析
- 全局变量
d的误用:你定义的全局d = {"warning1": []}不会同步JSON文件的内容——比如当你已经有用户被警告记录在test.json里时,你的代码在执行警告操作时,依然会修改这个全局空数组,然后覆盖掉文件里的有效数据,甚至可能导致文件内容损坏。 - Cog事件监听不规范:原代码里的
on_ready没有使用Cog专属的监听装饰器,这可能导致事件无法正常触发,间接引发后续文件操作异常。 - 缺少文件异常处理:如果
test.json路径错误、文件为空或损坏,直接读取会触发JSON解析错误,而你的代码没有做任何容错处理。
修正后的完整代码
from discord.ext import commands import discord import json import os class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot # 定义警告文件路径,确保和bot运行目录一致 self.warn_file = "test.json" # 初始化文件:不存在则创建带初始结构的JSON if not os.path.exists(self.warn_file): with open(self.warn_file, "w") as fp: json.dump({"warning1": []}, fp) @commands.Cog.listener() async def on_ready(self): """Prints to the console that the test cog is working""" print("Ready in Moderation Cog.") @commands.command() async def warn(self, ctx, user: discord.Member=None): """Warns the user, writes the information to a json file and if they get warned a second time it kicks them from the server""" # 处理未指定用户的情况 if not user: await ctx.send("请指定要警告的用户!") return # 读取并解析警告文件,处理可能的错误 try: with open(self.warn_file, "r") as fp: warn_data = json.load(fp) except json.JSONDecodeError: # 文件损坏时重置为初始结构 warn_data = {"warning1": []} with open(self.warn_file, "w") as fp: json.dump(warn_data, fp) user_id_str = str(user.id) # 判断用户是否已有警告记录 if user_id_str in warn_data.get("warning1", []): await ctx.send("User has already been warned once, kicking user!") await user.kick(reason="第二次警告触发踢出") else: # 更新警告列表并写入文件 warn_data["warning1"].append(user_id_str) with open(self.warn_file, "w") as fp: json.dump(warn_data, fp, indent=4) # indent让JSON格式更易读 await ctx.send(f"User {user.mention} has been warned successfully") def setup(bot): bot.add_cog(Moderation(bot))
关键修复点说明
- 移除全局变量
d:每次操作都直接从JSON文件读取最新数据,修改后再写回,彻底解决内存数据与文件数据不一致的问题。 - 规范Cog事件监听:给
on_ready添加@commands.Cog.listener()装饰器,这是Cog中监听事件的标准写法。 - 增加文件容错机制:初始化时检查文件是否存在,读取时捕获JSON解析错误并重置文件,避免报错导致bot崩溃。
- 补充参数校验:处理用户未指定的情况,防止后续
user.id调用报错。 - 优化写入格式:添加
indent=4让JSON文件内容更易读,方便后续排查问题。
现在你的脚本应该能正常运行,不会再出现JSON解析错误了。
内容的提问来源于stack exchange,提问作者Englad
相关产品推荐
相关产品推荐

