如何解决如何使用discord.py v1.4.1发出天气命令
如果您想使用discord.py来执行weather
命令并为您的机器人添加了一些很棒的功能,那么我就覆盖了您,我在下面回答了如何创建weather
命令在discord.py中。
解决方法
我们将制作一个像这样的命令-
首先,我们将使用openweahtermap API,它需要一个API密钥,您可以通过简单地登录其website来免费获得一个。
获得API密钥后,一切都很好。
第二步是开始编码,除了discord.py,我们将导入两个模块requests
和json
。我们可以简单地导入它们-
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
命令!
如果您确实遇到任何错误或有任何疑问,请确保在下面对其进行注释。我会尽力提供帮助。
谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。