[英]How to print out api data to discord bot
I want to make a discord command to print a phone number out of a API.我想发出一个不和谐命令来从 API 中打印电话号码。 The Error I get is:
我得到的错误是:
if x["cod"] != "404":
KeyError: 'cod'
if anyone could help me on how to print the api data would be great如果有人可以帮助我如何打印 api 数据会很棒
@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)
the reason your getting KeyError: 'cod'
is because it can't find "cod" in the api url.您收到
KeyError: 'cod'
的原因是它在 api url 中找不到“cod”。
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.您还要检查的是,如果“cod”不等于字符串 404,则发送嵌入,但我认为您要检查的是 api 状态代码是否为 404,您可以使用
x.status_code
来检查它。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.