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:
JavaScript
x
96
96
1
import discord
2
import datetime
3
from typing_extensions import IntVar
4
from discord import member
5
from discord.embeds import Embed
6
import json
7
from discord.ext import commands
8
from discord.colour import Color
9
import asyncio
10
11
#Vars
12
lawyersdict = {}
13
prefix = "<"
14
client = commands.Bot(command_prefix=prefix)
15
16
#Misc Stuff
17
client.remove_command("help")
18
19
#Embeds-
20
#RegEmbed
21
regembed = discord.Embed (
22
colour = discord.colour.Color.from_rgb(64, 255, 0),
23
title = 'Success',
24
description = 'Successfully registered you in the database as a lawyer!'
25
)
26
regembed.set_author(name='GVRP. Co',
27
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
28
regembed.timestamp = datetime.datetime.utcnow()
29
30
#Invalid
31
factembed = discord.Embed (
32
colour = discord.colour.Color.from_rgb(255, 64, 0),
33
title = 'Uh oh',
34
description = 'Seems like an error occured! Please try again.'
35
)
36
factembed.set_author(name='UselessFacts',
37
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
38
factembed.timestamp = datetime.datetime.utcnow()
39
40
#CMDS-
41
#Register Command
42
@client.command(aliases=['reg'])
43
async def register(ctx):
44
if ctx.author == client.user:
45
return
46
else:
47
if isinstance(ctx.channel, discord.channel.DMChannel):
48
await ctx.send("Sorry, you cannot use this command in a DM for security reasons.")
49
else:
50
channel = await ctx.author.create_dm()
51
def check(m):
52
return m.content is not None and m.channel == channel
53
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')")
54
await asyncio.sleep(0.3)
55
descmsg = await client.wait_for('message', check=check, timeout=300)
56
if descmsg.content == "cancel":
57
await channel.send(f"Cancelled command!")
58
else:
59
await channel.send(f"Almost there! You just need to enter the hiring price! You have 2 minutes. (between 450$ & 50,000$)")
60
await asyncio.sleep(0.3)
61
pricemsg = await client.wait_for('message', check=check, timeout=180)
62
if any(c.isalpha() for c in pricemsg.content):
63
if any(c.isalpha() for c in pricemsg.content):
64
await channel.send("Oops, you didnt typed a number! Make sure you didnt typed it without a coma! Please re-send the command.")
65
else:
66
def PrcCheck(num: int):
67
if num <= 50000 and num >= 450:
68
return True
69
else:
70
return False
71
if PrcCheck(int(pricemsg.content)):
72
desc = {
73
f"{str(ctx.author.id)}" : {
74
"Description" : f"{descmsg.content}",
75
"Price" : int(pricemsg.content),
76
"IsActive" : "true"
77
}
78
}
79
jsonobj = json.dumps(desc, indent=4, sort_keys= True)
80
with open('lawyers.json', mode='w') as outfile:
81
obj = json.load(json.dump(lawyersdict, outfile))
82
obj.append(desc)
83
obj.write(jsonobj, outfile)
84
await channel.send(embed=regembed)
85
else:
86
await channel.send(f"The price you entered is too low or too high! Price entered: ``{pricemsg.content}``. Please re-send the command.")
87
88
89
90
91
@client.event
92
async def on_ready():
93
print(f"Ready! Logged in as {client.user}")
94
95
client.run("Bot Token")
96
Here is the Compiler Error (Python 3.9):
JavaScript
1
21
21
1
Ignoring exception in command register:
2
Traceback (most recent call last):
3
File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 85, in wrapped
4
ret = await coro(*args, **kwargs)
5
File "c:UserstheliOneDriveBureauDiscord BotsGVRP. Co UtilBotlauncher.py", line 82, in register
6
obj = json.load(json.dump(lawyersdict, outfile))
7
File "C:UserstheliAppDataLocalProgramsPythonPython39libjson__init__.py", line 293, in load
8
return loads(fp.read(),
9
AttributeError: 'NoneType' object has no attribute 'read'
10
11
The above exception was the direct cause of the following exception:
12
13
Traceback (most recent call last):
14
File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandsbot.py", line 939, in invoke
15
await ctx.command.invoke(ctx)
16
File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 863, in invoke
17
await injected(*ctx.args, **ctx.kwargs)
18
File "C:UserstheliAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 94, in wrapped
19
raise CommandInvokeError(exc) from exc
20
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'read'
21
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
JavaScript
1
2
1
obj = json.load(json.dump(lawyersdict, outfile))
2
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)
.