I’m developing a Discord economy bot by following a tutorial, but I’m encountering an error when users attempt to check their balance:
Exception raised: KeyError: ‘892547163729485267’
In “economy.py”, line 18, while executing check_balance
coins = player_info[str(member.id)][“coins”]
Here’s the problematic code segment:
@bot.command()
async def check_balance(ctx):
await initialize_account(ctx.author)
member = ctx.author
player_info = await retrieve_economy_data()
coins = player_info[str(member.id)]["coins"]
savings = player_info[str(member.id)]["savings"]
embed = discord.Embed(title=f"{ctx.author.name}'s Wallet", color=discord.Color.green())
embed.add_field(name="Coins", value=coins)
embed.add_field(name="Savings", value=savings)
await ctx.send(embed=embed)
async def initialize_account(member):
player_info = await retrieve_economy_data()
if str(member.id) in player_info:
return False
else:
player_info[str(member.id)] = {}
player_info[str(member.id)]["coins"] = 0
player_info[str(member.id)]["savings"] = 0
The bot crashes every time someone tries to use the balance command. I suspect there might be a problem with the way I’m managing the user data, but I can’t identify the exact issue. Any suggestions on how to resolve this?
looks like your initialize_account function isnt actually saving the data back to wherever you store it. you’re modifying player_info locally but not persisting it, so when check_balance runs the user still doesn’t exist in the saved data. make sure initialize_account writes the updated player_info back to your file/database after creating the new user entry.
The issue is that your initialize_account
function creates the user data but never saves it permanently. You’re modifying the player_info
dictionary in memory, but when check_balance
calls retrieve_economy_data()
again, it’s loading the original data from storage without your changes. You need to add a save operation at the end of initialize_account
- something like await save_economy_data(player_info)
or whatever your save function is called. Also consider adding error handling in check_balance
as a backup, maybe wrap the coin access in a try-except block that calls initialize_account
if the KeyError occurs.
I’ve run into this exact problem before when working on my own Discord bot. The root cause is that you’re calling retrieve_economy_data()
twice - once in initialize_account
and again in check_balance
. When you modify the dictionary in initialize_account
, those changes only exist in that local copy, but check_balance
fetches a fresh copy from your data source which doesn’t include the new user data. You need to either return the modified player_info from initialize_account
and reuse it, or make sure initialize_account
actually commits the changes to your storage before returning. I’d recommend restructuring so that initialize_account
returns the updated data dictionary, then use that same dictionary in check_balance
instead of calling retrieve_economy_data()
again.