Vid*_*ero 3 python python-3.x openweathermap discord.py discord.py-rewrite
如果您想weather使用 discord.py创建命令并为您的机器人添加一个很酷的功能,我已经为您提供了帮助,我已经在下面回答了如何weather在 discord.py 中创建命令的问题。
我们将制作一个这样的命令 -
首先,我们将使用openweahtermap API,它需要一个 API 密钥,您只需登录他们的网站即可免费获得一个。
获得 API 密钥后,您就可以开始使用了。
第二步将是开始编码,我们将导入除 discord.py 之外的 1 个模块,即requests. 我们可以简单地导入它 -
import requests
Run Code Online (Sandbox Code Playgroud)
导入后,我们可以定义以下内容,以便更容易使用它们。
api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
Run Code Online (Sandbox Code Playgroud)
下一步将是创建一个city作为参数的命令。
@client.command()
async def weather(ctx, *, city: str):
Run Code Online (Sandbox Code Playgroud)
之后,我们可以使用 获取网站的响应,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
Run Code Online (Sandbox Code Playgroud)
现在,我们city_name使用一个简单的if语句来检查它是否是一个有效的城市。我们还使用async with channel.typing()which 显示机器人正在输入,直到它从网站获取内容为止。
if x["cod"] != "404":
async with channel.typing():
Run Code Online (Sandbox Code Playgroud)
现在我们得到了关于天气的信息。
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"]
Run Code Online (Sandbox Code Playgroud)
现在,一旦我们有了信息,我们就把信息放在一个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}")
Run Code Online (Sandbox Code Playgroud)
构建嵌入后,我们发送它。
await channel.send(embed=embed)
else:
await channel.send("City not found.")
Run Code Online (Sandbox Code Playgroud)
else如果 API 无法获取提到的城市的天气,我们还使用一个语句发送该城市未找到。
这样你就成功地发出了weather命令!
如果您确实遇到任何错误或有任何疑问,请务必在下面发表评论。我会尽力提供帮助。
谢谢!