如何处理 API - Discord.py 给出的 KeyError

How to Deal with a KeyError Given by an API - Discord.py

我正在尝试使用 TGRCode API 来制作一个 Discord 命令,其中 returns 关于 Super Mario Maker 2 关卡的信息。但是,我 运行 遇到了问题。

如果关卡没有,例如,Clear Condition,那么它会抛出一个 Key Error 并停止命令。我知道它是做什么的,因为它只是不存在于 API returns 的 JSON 中,而不是作为空字符串或任何东西。

但是,问题是我不知道该如何处理。

(我正在尝试使用 AIOHTTP 接收信息)

我试过使用

if clear_condition == None:
  clear_condition = "None"

那只是 returns 一个 KeyError 我也试过

if clear_condition_name not in response:
  clear_condition_name = "None"

只是 returns 一个错误说 ClientResponse 不可迭代。

我试过了(带引号和不带引号)

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

这只是吐出另一个关键错误。

我也检查了 this article by Career Karma,但它没有帮助,因为我不是定义字典的人。

这是我当前的代码:

@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}*")

因此,尽管我尝试了所有方法都没有帮助,但我希望能在这里找到一些帮助。 谢谢。

问题是您在声明 clear_condition_name 变量时试图读取该键。你应该检查响应数据字典是否有这样的键,像这样:

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