-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.py
97 lines (75 loc) · 2.55 KB
/
weather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import requests
import json
def get_cities(city_name):
base_url = "https://geocoding-api.open-meteo.com/v1/search"
params = {
"name": city_name,
"count": 10,
"format": "json",
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
if response.json()["results"]:
return response.json()["results"]
else:
print("No matching locations found for", city_name)
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
return None
def get_city_data(cities):
if not isinstance(cities, (list, dict)):
raise TypeError("Input 'cities' must be a list or a dictionary.")
city_data = []
if isinstance(cities, list):
for city in cities:
city_info = {
"id": city.get("id", ""),
"name": city.get("name", ""),
"timezone": city.get("timezone", ""),
"lat": city.get("latitude", ""),
"long": city.get("longitude", ""),
"country_code": city.get("country_code", ""),
}
city_data.append(city_info)
else:
return city_data
def get_forecast(lat, long):
base_url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": long,
"hourly": ["temperature_2m", "precipitation", "windspeed_10m"],
"daily": ["temperature_2m_max", "temperature_2m_min", "precipitation_sum"],
"forecast_days": 1
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()
if isinstance(data, list):
print("Multiple locations found. Processing the first location...")
data = data[0]
return data
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
def forecast(name):
# testing
result = ""
# data = get_cities(str(msg))
data = get_cities(name)
# print("="*100)
c = get_city_data(data)
for index, city in enumerate(c):
result += f"{index+1} - {city['name']} - {city['country_code']}\n"
# print("="*100)
# choice = int(input("> "))
# lat = c[choice]['lat']
# long = c[choice]['long']
# print("="*100)
return result
# return json.dumps(get_forecast(52.52437, 13.41053), indent=4)
# if __name__ == "__main__":
# main()
# 'lat': 52.52437, 'long': 13.41053,