首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenWeather接口discord.py

OpenWeather接口discord.py
EN

Stack Overflow用户
提问于 2020-12-04 17:00:17
回答 1查看 623关注 0票数 0

我最近接触了OpeNweather应用程序接口,在这篇文章的帮助下我做了一个简单的当前天气命令:How to make a weather command using discord.py v1.4.1

我是API的新手,所以我需要使用Forecast API的帮助(文档可以在这里找到https://openweathermap.org/api/hourly-forecast)

我正在为我的机器人使用discord.py重写

EN

回答 1

Stack Overflow用户

发布于 2021-01-26 15:51:53

感谢您提供此命令的灵感。但是,通过一些研究和更多的细节/学习如何从API中检索数据,我来到了这里。我愿意提供帮助,并与您分享我的想法。

基本上,我使用了API提供的所有功能。在下面的代码中,它将查找空气中的温度、湿度和压力。它使用"get“方法来检索此数据,条件是命令中提供了一个有效的城市。

只需从站点获取密钥并复制粘贴到"api_key“字符串中即可。希望这对你的进步有所帮助,尽管我可能会帮助你,因为我让命令工作得很好。

代码语言:javascript
复制
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!")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65140606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档