Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

python - Encountering a weird key error, is this something to do with json or my statements?

Im writing a discord.py bot and this is the warns command, it gets warns logged by the warn cmd! Why do I get a key error? My JSON:

{"777618366894571530": {"1": "ROMO charged by ROMO#6714 for demo"}}

My script to get the warns:

if str(guildid) in warns:
    for value in warns.items():
        
        warnval = warns[str(guildid)][value]
        if user in warnval:
            embed.add_field(name=f"``Warn {value}``", value=f"{warnval}", inline=True)
        
else:
  await ctx.send("Guild has no warns!")

My full warns cmd to get warns from the json:

  @command()
  @cooldown(9, 20, BucketType.user)
  async def warns(self, ctx, user : discord.Member):
    guild = user.guild
    guildid = user.guild.id
    userid = user.id
    print("LOADING")
    warns = {}
    guildid = ctx.guild.id
    placing = (len(warns)+1)
    with open("./warns.json","r") as f:
      warns = json.load(f)

    embed = discord.Embed(title=f"Warns", description= f"Warns for user {user}", color=0x00ff00)

    
    if str(guildid) in warns:
      for value in warns.items():
        
        warnval = warns[str(guildid)][value]
        if user in warnval:
          embed.add_field(name=f"``Warn {value}``", value=f"{warnval}", inline=True)
        
    else:
      await ctx.send("Guild has no warns!")
    

    embed.set_footer(text=f"These are {user.display_name}'s warns.")
    await ctx.send(embed=embed)


question from:https://stackoverflow.com/questions/65848254/encountering-a-weird-key-error-is-this-something-to-do-with-json-or-my-statemen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this is what you want:

found_warning = False
if str(guildid) in warns:
    for key, warnval in warns[str(guildid)].items():
        if user.name in warnval:
            embed.add_field(name=f"``Warn {key}``", value=f"{warnval}", inline=True)
            found_warning = True
if not found_warning:
    await ctx.send("Guild has no warns!")

items() returns tuples containing the dictionary keys and values. You only want to search for the user in the value. You don't need to index the dictionary again, since it returns the values.

Use the found_warning variable to tell whether it found the user in any of the warnings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...