Skip to content
Advertisement

Cannot add/append element to JSON File

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:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:UserstheliOneDriveBureauDiscord BotsGVRP. Co UtilBotlauncher.py", line 82, in register
    obj = json.load(json.dump(lawyersdict, outfile))
  File "C:UserstheliAppDataLocalProgramsPythonPython39libjson__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:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandsbot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement