我最近接触了OpeNweather应用程序接口,在这篇文章的帮助下我做了一个简单的当前天气命令:How to make a weather command using discord.py v1.4.1
我是API的新手,所以我需要使用Forecast API的帮助(文档可以在这里找到https://openweathermap.org/api/hourly-forecast)
我正在为我的机器人使用discord.py重写
发布于 2021-01-26 15:51:53
感谢您提供此命令的灵感。但是,通过一些研究和更多的细节/学习如何从API中检索数据,我来到了这里。我愿意提供帮助,并与您分享我的想法。
基本上,我使用了API提供的所有功能。在下面的代码中,它将查找空气中的温度、湿度和压力。它使用"get“方法来检索此数据,条件是命令中提供了一个有效的城市。
只需从站点获取密钥并复制粘贴到"api_key“字符串中即可。希望这对你的进步有所帮助,尽管我可能会帮助你,因为我让命令工作得很好。
api_key = "123abcmyweathercodeapitoken"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
@client.command()
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message.channel
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature_celsiuis = str(round(current_temperature - 273.15))
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
embed = discord.Embed(
title=f"Weather forecast - {city_name}",
color=0x7289DA,
timestamp=ctx.message.created_at,
)
embed.add_field(
name="Description",
value=f"**{weather_description}**",
inline=False)
embed.add_field(
name="Temperature(C)",
value=f"**{current_temperature_celsiuis}°C**",
inline=False)
embed.add_field(
name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(
name="Atmospheric Pressure(hPa)",
value=f"**{current_pressure}hPa**",
inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send(
f"There was no results about this place!")https://stackoverflow.com/questions/65140606
复制相似问题