Discord.py 当我尝试将自定义前缀发送到 JSON 文件时出现此错误:预期值:第 1 行第 1 列(字符 0)

Discord.py I'm getting this error when I try to send a custom prefix to a JSON file: Expecting value: line 1 column 1 (char 0)

我正在编写一个 discord.py 机器人,我正在尝试创建一个允许服务器设置自己的前缀的命令。这是代码:

@bot.command(
    help = "Set the server prefix!"
)
async def setprefix(ctx, arg1):
    with open('prefixes.json', 'a+') as f:
        prefixes = json.load(f)
        prefixes[ctx.guild.id] = arg1
    await ctx.channel.send(f"The server prefix has been set to **{arg1}**")

这是 json 文件的样子:

{
    "guild_id": "!",
}

此处,“guild_id”:“!”只是一个有意义的占位符。

当我在我的测试服务器上 运行 命令时,这是我得到完整记录的错误:

Ignoring exception in command setprefix:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/Users/secret/OneDrive/PyBot/Millenium_Build.py", line 174, in setprefix
    prefixes = json.load(f)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

有人知道如何解决吗?

with open('prefixes.json', 'a+') as f:

Opening with a+ mode opening the file for appending,这意味着指针从文件末尾开始。因此,当您调用 json.load(f).

时,没有什么可读的
        prefixes[ctx.guild.id] = arg1

这里这一行也完全没有作用。它不会向文件写入任何内容,如果这是您期望的。

相反,您想做这样的事情:

    with open('prefixes.json') as f:
        prefixes = json.load(f)
    prefixes[ctx.guild.id] = arg1
    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f)
    ...

理想情况下,您希望将其设为原子操作,但这将用于演示如何解决您遇到的问题。

另外,json 文件中的尾随逗号也会导致解码错误(尽管这不是您在此处看到的错误)。