简体   繁体   English

如何将错误消息添加到 API 调用 discord python

[英]How can i add error message to API call discord python

I have been working on a simple api call for my bot and it works just fine but if I enter the wrong input or the api is down the bot simply dose not reply我一直在为我的机器人处理一个简单的 api 调用,它工作得很好,但是如果我输入错误的输入或 api 出现故障,机器人根本不回复

Any way to get the bot to reply with an error message if the api has an error or 404 for example?例如,如果 api 出现错误或 404,有什么方法可以让机器人回复错误消息?

I tried to use an else command but I kept getting errors我尝试使用 else 命令,但我不断收到错误

My code so far:到目前为止我的代码:

@client.command()
async def zip(ctx, zip):
    url = ('http://api.zippopotam.us/us/' + zip)
    response = requests.get(url)
    placename = response.json()["places"][0]["place name"]
    lon = response.json()["places"][0]["longitude"]
    state = response.json()["places"][0]["state"]
    lat = response.json()["places"][0]["latitude"]

    embed = discord.Embed(title="Zip location info for " + zip, color=0x00ffff)
    embed.add_field(name="City:", value=f'{placename}', inline=True)
    embed.add_field(name="State:", value=f'{state}', inline=True)
    embed.add_field(name="Latitude:", value=f'{lat}', inline=True)
    embed.add_field(name="Longitude:", value=f'{lon}', inline=True)
    
    await ctx.send(embed=embed)

requests.get() returns a Response object with a status_code attribute, as shown in the requests documentation . requests.get()返回带有status_code属性的Response object,如requests文档中所示。

You can simply check whether status_code is equal to 404 , or whichever specific value you want to check:您可以简单地检查status_code是否等于404 ,或者您要检查的任何特定值:

response = requests.get(...)
# check if the status_code lies in user error range
if 400 <= response.status_code <= 499:
    # return error here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM