Home > database >  Hi, how do you print API url data to discord bot
Hi, how do you print API url data to discord bot

Time:10-13

i want to make a discord command to print a phone number out of a API. The code says there is something wrong with if x["cod"] != "404": does anyone know how to fix this? or maybe have something other to print API data to the discord bot.

@client.command()
async def o(ctx):
 channel = ctx.message.channel
   url = "https://random-data-api.com/api/phone_number/random_phone_number"
response = requests.get(url)
x = response.json()
 channel = ctx.message.channel
if x["cod"] != "404":
      async with channel.typing():
      y = x["id"]
     cell_phone = y["phone"]
     embed = discord.Embed(title=f"Het weer in {cell_phone}",
     color=0x00FFFF,
     timestamp=ctx.message.created_at,)
return   await channel.send(embed=embed)

CodePudding user response:

the reason your getting KeyError: 'cod' is because it can't find "cod" in the api url.

What your checking also is that if "cod" does not equal to string 404 then send the embed, but what I think your trying to check is if the api status code is 404 which you can use x.status_code to check that.

This would be the correct code to get phone number:

@bot.command()
async def o(ctx):
    channel = ctx.message.channel
    x = requests.get("https://random-data-api.com/api/phone_number/random_phone_number")
    y = x.json()
    channel = ctx.message.channel
    if x.status_code != 404:
        async with channel.typing():
            cell_phone = y["phone_number"]
        embed = discord.Embed(title=f"Het weer in {cell_phone}",
        color=0x00FFFF,
        timestamp=ctx.message.created_at,)
    return await channel.send(embed=embed)
  • Related