I am trying to create a discord bot that gives peoples wins and then stores it into a json file. When I run the command ?win @ I run into an error that displays their id within the error. I believe this is because their id is not in the json file. However I want my code to create an entry for their id and wins if it is not already inside the json file. Here are my functions and command.
open wins
async def open_wins(user):
users = await get_win_data()
if str(user.id) in users:
return False
users[str(user.id)] = {"Wins": 0}
with open('leaderboard.json',"w") as f:
json.dump(users,f)
return True
Get win data
async def get_win_data():
with open("leaderboard.json", "r") as f:
users = json.load(f)
return users
win code
@client.command()
@commands.has_role("Draft Manager")
async def win(ctx,member: discord.Member = None ):
if not member:
member = ctx.author
await open_wins(member)
users = await get_win_data()
user = member
onewin = 1
await ctx.send(f"You just gained {onewin} win ")
users[str(user.id)]["Wins"] = onewin
with open("leaderboard.json", "w") as f:
json.dump(users, f, indent=4)
Here is my json file
{
"325837218222440460": {
"Wins": 1
}
}
I would like to the note the win command only works when I do "?win" but when I do "?win <@user>" thats when I get an error.
CodePudding user response:
You use await open_wins(member)
only when member
is None.
But if you use "?win <@user>", @user
may be still not recorded to your file. So, you need to use await open_wins(member)
function in all cases.
@client.command()
@commands.has_role("Draft Manager")
async def win(ctx,member: discord.Member = None ):
if not member:
member = ctx.author
await open_wins(member)
users = await get_win_data()
user = member
onewin = 1
await ctx.send(f"You just gained {onewin} win ")
users[str(user.id)]["Wins"] = onewin
with open("leaderboard.json", "w") as f:
json.dump(users, f, indent=4)