【问题标题】:How to make a weather command using discord.py v1.4.1如何使用 discord.py v1.4.1 制作天气命令
【发布时间】:2020-12-08 16:45:15
【问题描述】:

如果您想使用 discord.py 创建 weather 命令并为您的机器人添加一个很酷的补充,我已经为您提供了覆盖,我在下面回答了如何在 discord.py 中创建 weather 命令.

【问题讨论】:

标签: python python-3.x discord.py discord.py-rewrite openweathermap


【解决方案1】:

我们将创建一个像这样工作的命令 -


一开始,我们将使用openweahtermap API,它需要一个 API 密钥,您只需登录他们的website 即可免费获得一个。

获得 API 密钥后,一切顺利。

第二步是开始编码,我们将导入除discord.py之外的1个模块,即requests。我们可以简单地导入它 -

import requests

导入后我们可以定义如下的东西,以便于使用。

api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"

下一步将创建一个以city 作为参数的命令。

@client.command()
async def weather(ctx, *, city: str):

之后,我们可以使用requests获取网站的响应,然后使用json读取响应。我们还定义了使用命令的通道。

    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 语句检查city_name 是否为有效城市。我们还使用了async with channel.typing(),这表明机器人在从网站获取内容之前一直在打字。

    if x["cod"] != "404":
        async with channel.typing():

现在我们得到了有关天气的信息。

            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"]

现在,一旦我们获得信息,我们就将信息放入 discord.Embed 中,就像这样 -

            weather_description = z[0]["description"]
            embed = discord.Embed(title=f"Weather in {city_name}",
                              color=ctx.guild.me.top_role.color,
                              timestamp=ctx.message.created_at,)
            embed.add_field(name="Descripition", 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_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
            embed.set_footer(text=f"Requested by {ctx.author.name}")

构建嵌入后,我们发送它。

        await channel.send(embed=embed)
    else:
        await channel.send("City not found.")

我们还使用else 声明,如果 API 无法获取所提及城市的天气,则发送该城市未找到。


这样你就成功地发出了weather 命令!

如果您确实遇到任何错误或有任何疑问,请务必在下方发表评论。我会尽力提供帮助。

谢谢!

【讨论】:

  • 您可以尝试发送 Web 请求,也可以放入另一个可以帮助您进行天气预报的库。试试这个视频youtu.be/i0YSbE15fEM
  • 虽然,您可以添加一个名为 unit 的新变量,或者您想要的任何其他变量,而不是转换温度,这将包含所需的单位,如 unit = 'units=metric' ,完整的基本 URL 看起来像 complete_url= base_url + "appid=" + api_key + '&q=' + city_name + "&" + unit 这样你就不用费心转换了
猜你喜欢
  • 2021-11-19
  • 2021-09-02
  • 2021-07-12
  • 2021-08-17
  • 1970-01-01
  • 2021-07-20
  • 2022-06-11
  • 2020-09-10
  • 2021-08-30
相关资源
最近更新 更多