如何将API代码添加到Discord.py命令中



所以我从一个朋友那里得到了制作天气命令的想法,我今天就开始着手了。安装软件包,设置代码等等。因此,下面是我的天气API代码的代码,我想将其放入命令中。(!天气(。DPY公会中有人推荐了aiohttp,这看起来太难了,因为我是一个新程序员。有什么解决办法可以让人用勺子喂我吗?API代码如下:

import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

def weather(city):
city = city.replace(" ", "+")
res = requests.get(
f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8', headers=headers)
print("Searching...n")
soup = BeautifulSoup(res.text, 'html.parser')
location = soup.select('#wob_loc')[0].getText().strip()
time = soup.select('#wob_dts')[0].getText().strip()
info = soup.select('#wob_dc')[0].getText().strip()
weather = soup.select('#wob_tm')[0].getText().strip()
print(location)
print(time)
print(info)
print(weather+"°C")

city = input("Enter the Name of City -> ")
city = city+" weather"
weather(city)
print("Have a Nice Day:)")
# This code is contributed by adityatri

从weathermap网站获取API密钥。这是一个例子,说明这可能是什么样子。它很容易翻译成命令。

如果你想让它成为自己的函数,你可以使用这段代码。将返回的是一个元组。

list_weather = weatherFrog()
print(list_weather[0]) 

0表示温度,1表示湿度,2表示描述。

代码:

def weatherFrog(city):
api_key = YOUR_API_KEY
base_url = "https://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_humidiy = str(y["humidity"]) + "%"
z = x["weather"]
current_temperaturetwo = str(round(current_temperature - 273.15, 2)) + " Degrees Celsius"
en_weather_description = z[0]["description"]
return current_temperaturetwo, current_humidiy, en_weather_description

最新更新