[英]How do I print out an“AttributeError” error with my Discord bot?
[英]How to print out api data to discord bot
我想發出一個不和諧命令來從 API 中打印電話號碼。 我得到的錯誤是:
if x["cod"] != "404":
KeyError: 'cod'
如果有人可以幫助我如何打印 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)
您收到KeyError: 'cod'
的原因是它在 api url 中找不到“cod”。
您還要檢查的是,如果“cod”不等於字符串 404,則發送嵌入,但我認為您要檢查的是 api 狀態代碼是否為 404,您可以使用x.status_code
來檢查它。
這將是獲取電話號碼的正確代碼:
@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.