You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py用json存储自定义前缀触发JSONDecodeError报错如何解决

报错原因

触发json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)的核心是prefixes.json文件为空、不存在,或者内部内容不符合JSON格式规范。现有代码没有做任何异常兼容,直接尝试读取文件解析为JSON结构,首次运行或文件损坏时就会触发解析失败。

修复方案
  • 新增JSON文件读写的异常处理逻辑,文件不存在、为空、格式非法时自动初始化为空字典
  • 补全前缀查询的兜底逻辑,当查询的服务器未存储自定义前缀时返回默认前缀,避免键不存在报错
  • 可选在机器人启动时批量补全已加入服务器的前缀记录,避免历史加入的服务器查询前缀失败
修复后的完整代码
import json
import discord
from discord.ext import commands
from discord_slash import SlashCommand

# 封装前缀读写逻辑统一处理异常
def load_prefixes():
    try:
        with open('prefixes.json', 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

def save_prefixes(prefixes):
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

def get_prefix(client, message):
    prefixes = load_prefixes()
    # 兜底返回默认前缀!
    return prefixes.get(str(message.guild.id), '!')

# 注意要配置Intents权限,否则无法接收服务器相关事件
client = commands.Bot(
    command_prefix = get_prefix,
    help_command = None,
    intents = discord.Intents.all()
)
slash = SlashCommand(client, sync_commands = True)

@client.event
async def on_ready():
    # 启动时补全已加入服务器的前缀记录
    prefixes = load_prefixes()
    for guild in client.guilds:
        guild_id = str(guild.id)
        if guild_id not in prefixes:
            prefixes[guild_id] = '!'
    save_prefixes(prefixes)
    activity = discord.Game(name="!help", type=3)
    await client.change_presence(activity=activity)
    print('online !')

@client.event
async def on_guild_join(guild):
    prefixes = load_prefixes()
    prefixes[str(guild.id)] = '!'
    save_prefixes(prefixes)

@client.event
async def on_guild_remove(guild):
    prefixes = load_prefixes()
    # 加None参数避免删除不存在的键时报错
    prefixes.pop(str(guild.id), None)
    save_prefixes(prefixes)
注意事项
  • 需要提前在Discord开发者后台的机器人设置页面开启Guilds Intent权限,否则机器人无法正常接收服务器加入、退出事件
  • 若使用discord.py v2及以上版本,框架已内置斜杠命令支持,无需额外安装discord_slash依赖,可直接使用官方app_commands实现斜杠命令功能

内容的提问来源于stack exchange,提问作者Akopa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:15:03