I’m trying to add a new item to a shop in my discord, and I have it set to where people have to open an account before they can participate in the economy. Here is what I currently have in way of code to add this new item:
@commands.hybrid_command(name = "update_shop", description = "An administrative command used to update everyone's inventories when the shop is updated!")
@commands.has_role("*")
async def update_shop(self, ctx: commands.Context) -> None:
with open("cogs/inventory.json", "r") as f:
inventory = json.load(f)
if f"{user.id}" in inventory:
inventory[user.id]["law_tuition"] = 0
with open("cogs/inventory.json", "w") as f:
json.dump(inventory, f)
await ctx.send("Done!")
I don’t get any errors, but the JSON also doesn’t update. I don’t even get the "Done!" message!
Edit: Below is a sample of JSON:
{"[USER ID, REDACTED FOR PRIVACY": {"small_apartment": 0, "news_station": 0, "empty_storefront": 0, "business_down_payment": 0}...}
2
Answers
After a little tinkering, I figured it out myself!
worked.
your solution is very inefficient. Like someone in the comments pointed out, you are writing to the file in each iteration.
To optimize the code and write to the file only once, you can move the file writing outside of the loop. This way, the file is opened and written to only once after all updates have been made to the inventory dictionary, which is more efficient.
Do this instead: