如何使用discord.py v1.4.1发出天气命令

问题描述

如果您想使用discord.py来执行weather命令并为您的机器人添加了一些很棒的功能,那么我就覆盖了您,我在下面回答了如何创建weather命令在discord.py中。

解决方法

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

example


首先,我们将使用openweahtermap API,它需要一个API密钥,您可以通过简单地登录其website来免费获得一个。

获得API密钥后,一切都很好。

第二步是开始编码,除了discord.py,我们将导入两个模块requestsjson。我们可以简单地导入它们-

import requests,get

导入后,我们可以定义以下内容,以便于使用。

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

现在,我们通过使用简单的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命令!

如果您确实遇到任何错误或有任何疑问,请确保在下面对其进行注释。我会尽力提供帮助。

谢谢!