Home > front end >  How to Deal with a KeyError Given by an API - Discord.py
How to Deal with a KeyError Given by an API - Discord.py

Time:05-09

I'm trying to use the TGRCode API to make a Discord command which returns information about a level in Super Mario Maker 2. However, I'm running into a problem.

If the level has no, for example, Clear Condition, then it throws a Key Error and stops the command. I know what it does that, because it just isn't present in the JSON that the API returns, and not as a empty string or anything.

However, the problem is that I am not sure how to deal with it.

(I am trying to receive the information using AIOHTTP)

I have tried using

if clear_condition == None:
  clear_condition = "None"

That just returns a KeyError I have also tried

if clear_condition_name not in response:
  clear_condition_name = "None"

That just returns an error saying ClientResponse is not iterable.

I tried (with and without the quotation marks)

if "clear_condition_name" not in response.json():
  clear_condition_name = "None"

And that just spits out another Key Error.

I have also checked this article by Career Karma, but it does not help as I am not the one defining the dictionary.

Here is my current code:

@commands.command()
  async def smm2_lookup_level(self, ctx, code):
    await ctx.reply(f"Getting level information of level with code `{code}`")
    print(f"{ctx.author.name} has requested to get all information for {code}.")

    MAIN = f"https://tgrcode.com/mm2/level_info/{code}"


    async with request("GET", MAIN, headers={}) as response:
      if response.status == 200:
        print("The TGRCode API returned OK; getting info...")
        data = await response.json()
        title = data["name"]
        description = data["description"]
        upload_date = data["uploaded_pretty"]
        course_id = data["course_id"]
        style = data["game_style_name"]
        theme = data["theme_name"]
        difficulty = data["difficulty_name"]
        tags = data["tags_name"]
        upload_time = data["upload_time_pretty"]
        number_of_comments = data["num_comments"]
        clear_condition_name = data["clear_condition_name"]
        clear_condition_magnitude = data["clear_condition_magnitude"]
        clears = data["clears"]
        attempts = data["attempts"]
        clear_rate = data["clear_rate"]
        plays = data["plays"]
        likes = data["likes"]
        boos = data["boos"]
        thumbnail = f"https://tgrcode.com/mm2/level_thumbnail/{code}"
        map = f"https://tgrcode.com/mm2/level_entire_thumbnail/{code}"

        if clear_condition_name not in response.json():
          clear_condition_name = "None"
          clear_condition_magnitude = ""

        if "clear_condition_magnitude" not in response.json():
          clear_condition_name = "None"
          clear_condition_magnitude = ""
        
        if "description" not in response.json():
          description = ""

        if "tags" not in response.json():
          tags = "None"
        

        embed = discord.Embed(title="SMM2 Level Information.")
        embed.add_field(name="Level Name", value=title, inline=True)
        embed.add_field(name="Level Description", value=description, inline=True)
        embed.add_field(name="Level Code", value=course_id, inline=True)
        embed.add_field(name="Level Style", value=style, inline=True)
        embed.add_field(name="Level Theme", value=theme, inline=True)
        embed.add_field(name="Level Difficulty", value=difficulty, inline=True)
        embed.add_field(name="Tags", value=tags, inline=True)
        embed.add_field(name="Upload Date", value=upload_date, inline=True)
        embed.add_field(name="Time taken to Clearcheck Course", value=upload_time, inline=True)
        embed.add_field(name="Clear Condition Information", value=f"{clear_condition_name} {clear_condition_magnitude}.", inline=True)
        embed.add_field(name="Clear Information", value=f"Clears: {clears}\nAttemps: {attempts}\nPlays: {plays}\nClear Rate: {clear_rate}.")
        embed.add_field(name="Number of Comments", value=number_of_comments, inline=True)
        embed.set_thumbnail(url=thumbnail)
        embed.set_image(url=map)
        embed.add_field(name="Like:Boo Ratio", value=f"{likes}:{boos}")

        await ctx.send(f"{ctx.author.mention} Here's the information for level with code `{code}`:", embed=embed)

      else:
        await ctx.send(f"I was unable to retrieve the information. Try again, if not the TGRCode API may be down, or there is an error on my end.\n*Response Status: {response.status}*")
        print(f"I was unable to retrieve the information from TGRCode.\n*Response Status: {response.status}*")

So, with all of what I have tried resulting in no help, I'm hoping I can find some here. Thanks.

CodePudding user response:

The problem is you are trying to read that key when you declare the clear_condition_name variable. You should check if the response data dictionary has such a key, like this:

clear_condition_name = data["clear_condition_name"] if "clear_condition_name" in data.keys() else "None"
  • Related