Python Discord.py I';我在尝试向JSON文件发送自定义前缀时遇到此错误:期望值:第1行第1列(字符0)
我正在编写一个discord.py bot,我正在尝试生成一个命令,允许服务器设置自己的前缀。代码如下:Python Discord.py I';我在尝试向JSON文件发送自定义前缀时遇到此错误:期望值:第1行第1列(字符0),python,discord.py,python-3.8,Python,Discord.py,Python 3.8,我正在编写一个discord.py bot,我正在尝试生成一个命令,允许服务器设置自己的前缀。代码如下: @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.i
@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": "!",
}
这里,“帮会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)
有人知道如何修复它吗?将open('prefixes.json','a+')作为f:
使用a+
模式打开文件进行追加,这意味着指针从文件末尾开始。因此,当您调用json.load(f)
时,没有什么可读的
这一行在这里也没有任何效果。它不会向文件写入任何内容,如果您希望这样做的话
相反,您希望执行以下操作:
以open('prefixes.json')作为f的:
前缀=json.load(f)
前缀[ctx.guild.id]=arg1
将open('prefixes.json','w')作为f:
dump(前缀,f)
...
理想情况下,您可能希望将其作为一个原子操作,但这将用于演示如何解决您遇到的问题
另外,json文件中的尾随逗号也会导致解码错误(尽管这不是您在这里看到的错误)
prefixes[ctx.guild.id] = arg1