So what I did till now is, I added a register command which would look if the user's discord ID is in the.json file. If it isn't, it just adds it and also adds 2 attributes called "Wallet" and "Bank" and sets their values to the starting ones.
So the code for it is:
@bot.command()
async def register(ctx):
oh = False
await register_acc(ctx.author)
if (oh == False):
ctx.send(f'You already have an account dum dum')
else:
ctx.send(f'You have successfully registered an account.')
async def register_acc(user):
with open("users.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)]["Wallet"] = 0
users[str(user.id)]["Bank"] = 0
with open("users.json", "w") as f:
json.dump(users,f)
return True
Error I get:
File "C:\Users\janvf\Desktop\Bob\main.py", line 79, in register await register_acc(ctx.author)
File "C:\Users\janvf\Desktop\Bob\main.py", line 93, in register_acc users[str(user.id)]["Wallet"] = 0 KeyError: ' my discord id '
Is there something very obvious I am missing? I tried writing the json a bit different but then realized I did it completely wrong as well.
Change the else statement to this:
else:
users[str(user.id)] = {"Wallet": 0, "Bank": 0}
The KeyError
is caused because users[str(user.id)]["Bank"] = 0
is trying to change the value of the key "Bank" in the dictionary users[str(user.id)]
which does not exist. Instead, create the key users[str(user.id)]
and set it to a dictionary containing the value of "Wallet" and "Bank" as shown above.
I believe the error lies here
await register_acc(ctx.author)
I imagine this returns None in your code, because ctx does not have an attribute of author. You'd have to change this line to
await register_acc(ctx.message.author)
This will pass a Member object to your register_acc
method
Check the documentation on discordpy API here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.