【问题标题】:Cannot add/append element to JSON File无法将元素添加/附加到 JSON 文件
【发布时间】:2022-01-20 18:46:07
【问题描述】:

所以,我正在为一个紧急情况下有 4k 成员的 RP 服务器制作一个不和谐机器人。 我的目标是将律师数据库存储在一个 json 文件中,该文件将托管在我的一台计算机上进行测试。这是我的代码:

import discord
import datetime
from typing_extensions import IntVar
from discord import member
from discord.embeds import Embed
import json
from discord.ext import commands
from discord.colour import Color
import asyncio

#Vars
lawyersdict = {}
prefix = "<"
client = commands.Bot(command_prefix=prefix)

#Misc Stuff
client.remove_command("help")

#Embeds-
#RegEmbed
regembed = discord.Embed (
        colour = discord.colour.Color.from_rgb(64, 255, 0),
        title = 'Success',
        description = 'Successfully registered you in the database as a lawyer!'
    )
regembed.set_author(name='GVRP. Co',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
regembed.timestamp = datetime.datetime.utcnow()

#Invalid
factembed = discord.Embed (
        colour = discord.colour.Color.from_rgb(255, 64, 0),
        title = 'Uh oh',
        description = 'Seems like an error occured! Please try again.'
    )
factembed.set_author(name='UselessFacts',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
factembed.timestamp = datetime.datetime.utcnow()

#CMDS-
#Register Command
@client.command(aliases=['reg'])
async def register(ctx):
    if ctx.author == client.user:
        return
    else:
        if isinstance(ctx.channel, discord.channel.DMChannel):
            await ctx.send("Sorry, you cannot use this command in a DM for security reasons.")
        else:
            channel = await ctx.author.create_dm()
            def check(m):
                return m.content is not None and m.channel == channel
            await channel.send(f"Hello {ctx.author.mention}! Please tell a little bit about yourself! You have 5 minutes. (To cancel the command, type 'cancel')")
            await asyncio.sleep(0.3)
            descmsg = await client.wait_for('message', check=check, timeout=300)
            if descmsg.content == "cancel":
                await channel.send(f"Cancelled command!")
            else:
                await channel.send(f"Almost there! You just need to enter the hiring price! You have 2 minutes. (between 450$ & 50,000$)")
                await asyncio.sleep(0.3)
                pricemsg = await client.wait_for('message', check=check, timeout=180)
                if any(c.isalpha() for c in pricemsg.content):
                    if any(c.isalpha() for c in pricemsg.content):
                        await channel.send("Oops, you didnt typed a number! Make sure you didnt typed it without a coma! Please re-send the command.")
                else:
                    def PrcCheck(num: int):
                        if num <= 50000 and num >= 450:
                            return True
                        else:
                            return False
                    if PrcCheck(int(pricemsg.content)):
                        desc = {
                            f"{str(ctx.author.id)}" : {
                                "Description" : f"{descmsg.content}",
                                "Price" : int(pricemsg.content),
                                "IsActive" : "true"
                            }
                        }
                        jsonobj = json.dumps(desc, indent=4, sort_keys= True)
                        with open('lawyers.json', mode='w') as outfile:
                            obj = json.load(json.dump(lawyersdict, outfile))
                            obj.append(desc)
                            obj.write(jsonobj, outfile)
                        await channel.send(embed=regembed)
                    else:
                        await channel.send(f"The price you entered is too low or too high! Price entered: ``{pricemsg.content}``. Please re-send the command.")


            

@client.event
async def on_ready():
    print(f"Ready! Logged in as {client.user}")

client.run("Bot Token")

这是编译器错误(Python 3.9):

Ignoring exception in command register:
Traceback (most recent call last):
  File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\theli\OneDrive\Bureau\Discord Bots\GVRP. Co UtilBot\launcher.py", line 82, in register
    obj = json.load(json.dump(lawyersdict, outfile))
  File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'

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

Traceback (most recent call last):
  File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\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: AttributeError: 'NoneType' object has no attribute 'read'

我尝试查看其他帖子以查看是否有解决方案。但这是 2015 年的一篇帖子,并没有解决我的问题。

我的目标是添加有关输入信息并输入我的注册命令的 Discord 用户的详细信息。

感谢您阅读这篇文章

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    没关系,我只是发现错误,看了一点后我重写了代码块以进行附加!

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    正如约翰戈登在上面所说的转储返回无,因此你不能加载它。

    要继续您的评论,那么是的,json.load(outfile) 是您需要做的,但只是稍后。 该文件为 w (写入)打开并且它当前是一个打开的文件,因此您可以立即执行此操作,但在 with 语句之后,通过使用 with 上下文或仅使用 open. 创建另一个 io 打开调用

    【讨论】:

    • 所以基本上,我应该首先使用with 上下文打开文件,但是如果我不首先加载它,我应该如何查看文件呢? (对不起,如果这个问题很愚蠢)
    【解决方案3】:
    obj = json.load(json.dump(lawyersdict, outfile))
    

    您使用json.dump() 的结果作为json.load() 的参数。

    但是json.dump() 没有返回任何东西。所以你实际上是在打电话给json.load(None)

    【讨论】:

    • 所以基本上我只需要使用json.load(outfile)?
    • 这不是 OP 代码的唯一问题。
    • 我尝试删除 obj = json.load(json.dump(lawyersdict, outfile))) 并将其替换为 obj = json.load(outfile) 现在它说:JSONDecodeError: Expecting value: line 1 column 1 (char 0) 这没有任何意义,因为 JSON 文件以 @987654330 开头(至少我认为) @
    • 你能告诉我另一个错误@gre_gor 吗?
    猜你喜欢
    • 2014-04-13
    • 2022-11-16
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2012-09-19
    • 2018-09-14
    • 2022-12-18
    • 2018-01-21
    相关资源
    最近更新 更多