python - 如何使用 discord.py v1.4.1 制作天气命令

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

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

最佳答案

我们将制作一个像这样工作的命令 -
example

开始,我们将使用 openweahtermap API,需要 API key ,您只需登录他们的 website 即可免费获得一个.
获得 API key 后,一切顺利。
第二步是开始编码,我们将导入除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 读取响应.我们还定义了使用命令的 channel 。
    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
现在,我们检查 city_name使用简单的 if 是一个有效的城市陈述。我们还使用 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命令!
如果您确实遇到任何错误或有任何疑问,请务必在下面发表评论。我会尽力提供帮助。
谢谢!

关于python - 如何使用 discord.py v1.4.1 制作天气命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63486570/

相关文章:

python - 使用 Dask 加载多个 CSV 文件时混合列

python过滤字符串以返回列表

python - Numpy:设置 false 左边的任何东西都是假的

python - python 将 RGB 转换为灰度

python - 使用 urllib 请求更改或创建超时

Python - 是否可以在 Discord.py-v1.0 中 wait_for 一个或另一个事件?

python - Discord Py 任务未按预期工作。不予返回

Python - 嵌套列表 - 有效检查

python - Discord bot python : discord. errors.ClientException: ffmpeg was not found

python - 如何根据传递给函数的数据类型调度 Python 2 函数?