skip to Main Content

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


  1. Chosen as BEST ANSWER

    After a little tinkering, I figured it out myself!

        @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)
          for user_id, user_data in inventory.items():
            if 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!")
    

    worked.


  2. 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:

    with open("cogs/inventory.json", "r") as f:
                inventory = json.load(f)
    
            # Update the law_tuition for each user
            for user_id, user_data in inventory.items():
                if user_id in inventory:
                    inventory[user_id]["law_tuition"] = 0
    
            # Write the updated inventory back to the file
            with open("cogs/inventory.json", "w") as f:
                json.dump(inventory, f)
    
            # Send a message indicating that the update is done
            await ctx.send("Done!")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search