Home > Enterprise >  Cannot add/append element to JSON File
Cannot add/append element to JSON File

Time:12-18

So, I was making a discord bot for an RP server with 4k members in emergency. My goal was to store the lawyers database in a json file that would be hosted on one of my computers for testing. Here is my code:

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")

Here is the Compiler Error (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'

I tried to look at other posts to see if there was a solution. But it was a post from 2015 which didn't solve my problem.

My goal here was to append details about the Discord User who entered the info and has entered my command to register.

Thank you for reading this post

CodePudding user response:

obj = json.load(json.dump(lawyersdict, outfile))

You're using the result of json.dump() as the argument to json.load().

But json.dump() doesn't return anything. So you're effectively calling json.load(None).

CodePudding user response:

As John Gordon said above dump return None therefore you cant load it .

To continue your comment, then yes json.load(outfile) is what you need to do but only later. the file is open for w (write) and its currently an open file, so you can do it right away but after the with statement, by creating another io open call using the with context or with just an open.

  • Related