首页 > 解决方案 > 尝试将变量附加到 json 会在 python 中返回错误

问题描述

免责声明:其中大部分可能没有意义,因为基本上所有这些只是我试图做一些我以前从未做过的事情。

我正在尝试制作一个具有“排行榜”类型系统的不和谐机器人。但是我尝试了什么,给了我一个错误。

这是我的代码。

import discord
from discord.ext import commands
import json
from json import loads
import os
TOKEN = 'Token'
bot = commands.Bot(command_prefix='!')


@bot.event
async def on_ready():
    print(f'Logged in as: {bot.user.name}')
    print(f'With ID: {bot.user.id}')


@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.channel.id == 782989981752098886:
        if message.author == bot.user:
            return
        else:

            if ''.join(message.content.split()).lower() == "egg":
                os.chdir(r'Directory')
                with open('EggData.json', 'r') as file:
                    data = loads(file.read())
                try:
                    author = message.author.mention
                    usernameList = data
                    authorsAmount = usernameList[author]
                    print(authorsAmount)
                    usernameList[author] += 1
                    print(usernameList[author])
                    print(usernameList)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(usernameList, outfile)
                    return
                except:
                    addUsersID = {f"{author}" : 0}
                    appendUserID = usernameList.append(addUsersID)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(appendUserID, outfile)
                    author = message.author.mention
                    usernameList = data
                    authorsAmount = usernameList[author]
                    print(authorsAmount)
                    usernameList[author] += 1
                    print(usernameList[author])
                    print(usernameList)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(usernameList, outfile)
                    return
                return
            else:
                await message.channel.send(
                    "{} You fool. You absolute buffoon, it is illegal to say anything other than 'egg' in this server. I hope you feel the shame in side you. Us only saying 'egg' in this channel brings peace to our server, and you thinking your above everyone? above ME? You {}, have messed up. I want you to take a long time to reflect your self.".format(message.author.mention, message.author.mention))
    else:
        return

bot.run(TOKEN)

try:如果我手动添加用户 ID 并删除and ,它工作得很好except:。但是对于具有try:except:的部分,我尝试将其添加到列表中(如果他们尚未在列表中)。这是 json 的样子: {"<@494664629570764810>": 11, "variblePlaceholder": 4, "numbernumbernumberPlaceholder": 26} 我将尝试回答您可能遇到的任何问题,因为我确信这不是很清楚。

编辑:

忘记说错误了。我得到的错误是 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

回溯错误:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\name\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\name\Desktop\Python\ProofOfConcept\JsonEgg\bot.py", line 27, in on_message
    data = loads(file.read())
  File "C:\Users\name\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\name\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\name\AppData\Local\Programs\Python\Python39\lib\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)

指向错误的 Imgur 链接:https ://imgur.com/a/MQ0dtV​​c

解决方案:

我用dict.update(dict2)来组合两个字典。

这是我的代码。

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.channel.id == 782989981752098886:
        if message.author == bot.user:
            return
        else:

            if ''.join(message.content.split()).lower() == "egg":
                os.chdir(r'C:\Users\name\Desktop\Python\ProofOfConcept\JsonEgg')
                with open('EggData.json', 'r') as file:
                    data = loads(file.read())
                try:
                    author = message.author.mention
                    usernameList = data
                    authorsAmount = usernameList[author]
                    print(authorsAmount)
                    usernameList[author] += 1
                    print(usernameList[author])
                    print(usernameList)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(usernameList, outfile)
                    return
                except:
                    author = message.author.mention
                    usernameList = data
                    addUsersID = {f"{author}" : 1}
                    whatToAdd = usernameList
                    whatToAdd.update(addUsersID)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(whatToAdd, outfile)
                    return
            else:
                await message.channel.send("{} You fool. You absolute buffoon, it is illegal to say anything other than 'egg' in this channel. I hope you feel the shame in side you. Us only saying 'egg' in this channel brings peace to our server, and you thinking your above everyone? above ME? You {}, have messed up. I want you to take a long time to reflect your self.".format(message.author.mention, message.author.mention))
    else:
        return

Imgur 链接到我的代码:https ://imgur.com/a/1PgF6BQ

标签: pythonjsonpython-3.xdiscorddiscord.py-rewrite

解决方案


好的,这里有一个小错误。使用字典(AKA json)时,您根本不能使用 .append() 因为字典不能那样工作。字典(json)遵循键值配对系统,因此您需要分配一个键和值,如下所示...

正确的用法是:

my_dict["myvalue"]="another value"
#So in your case: 
usernameList[addUsersID]=#do something here...

您收到的错误可能是因为 json/ 格式中没有任何内容。我还注意到你正在制作一个不和谐的机器人。考虑加入 discord.py 服务器,您可以在那里获得进一步的支持。当我第一次开始制作机器人时,我发现它很有用。希望以上对您有所帮助!


推荐阅读