discord.py尝试保存单个数据,但得到json解码错误

问题描述

我正在discord.py中制作一个机器人,我试图为每个用户保存个人信息。 我是python的新手,还是discord.py的新手,如果这样做是一种不好的方法,请您谅解。 我也没有太多地将json库用于python,所以我对它不是很熟悉。 是的,我在botfolder目录中有一个名为users.json的文件

这是我的代码

import discord
import json
from discord.ext import commands

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------------------')

@client.event
async def on_message(message):
    if message.author.bot == False:
        with open('/home/ian/python/botfolder/users.json','r') as f:
            users = json.load(f)

        await update_data(users,message.author)
        await add_cash(users,message.author)
 
    with open('/home/ian/python/botfolder/users.json','w') as f:
         json.dump(users,f,indent=3)
    
    await client.process_commands(message)

async def update_data(users,user):
    if f'{user.id}' in users:
        return
    else:
        users[str(user.id)] = {}
        users[str(user.id)]['money'] = 0

client.run('token')

这是错误(顺便说一句,我在unbuntu上)

Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/ian/.local/lib/python3.8/site-packages/discord/client.py",line 312,in _run_event
    await coro(*args,**kwargs)
  File "/home/ian/python/botfolder/counrtybot2.py",line 18,in on_message
    users = json.load(f)
  File "/usr/lib/python3.8/json/__init__.py",line 293,in load
    return loads(fp.read(),File "/usr/lib/python3.8/json/__init__.py",line 357,in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py",line 337,in decode
    obj,end = self.raw_decode(s,idx=_w(s,0).end())
  File "/usr/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)

我从未见过JSONDecodeError,但可能安装了错误的东西。 每当有人发送消息时,都会显示错误

解决方法

文件中没有任何内容。您应该捕获错误并在错误为空时进行处理,或者永远不要让文件为空。使其成为仅使用json创建文件,或者不创建文件。