-
Notifications
You must be signed in to change notification settings - Fork 0
/
meteo.py
executable file
·339 lines (299 loc) · 12 KB
/
meteo.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import datetime
import requests
from telegram import Update
from telegram.ext import ContextTypes
import config
from utils import no_can_do, printlog, get_user_settings
async def ora(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if await no_can_do(update, context):
return
# print(f'{get_now()} {await get_display_name(update.effective_user)} in {await get_chat_name(update.message.chat.id)} chiede l\'ora')
await printlog(update, "chiede l'ora")
if not context.args:
await update.message.reply_text("Inserisci una città")
return
API_KEY = config.OWM_API_KEY
if len(context.args) == 1:
citta = context.args[0]
elif len(context.args) > 1:
citta = " ".join(context.args)
else:
await update.message.reply_text("Devi inserire una città.")
return
# citta += ",,it"
geocoding_url = "http://api.openweathermap.org/geo/1.0/direct"
query = {"q": citta, "appid": API_KEY}
geocoding = requests.get(geocoding_url, query)
geodata = geocoding.json()
if not geodata:
await update.message.reply_text("Nessuna città trovata.")
return
lat = geodata[0]["lat"]
lon = geodata[0]["lon"]
country = geodata[0]["country"]
name = geodata[0]["name"]
print(f"[Open Weather Map] Cerco: {name}, {country} [{lat}, {lon}]")
weather_url = "https://api.openweathermap.org/data/3.0/onecall"
weather_query = {
"lon": lon,
"lat": lat,
"units": "metric",
"lang": "it",
"exclude": "minutely,hourly",
"appid": API_KEY,
}
weather = requests.get(weather_url, weather_query)
data = weather.json()
try:
meteo = data["current"]
except KeyError:
# data['error']
await update.message.reply_text("Errore.")
return
ora = f"Sono le {datetime.datetime.utcfromtimestamp(meteo['dt'] + data['timezone_offset']).strftime('%H:%M')} del {datetime.datetime.utcfromtimestamp(meteo['dt']+ data['timezone_offset']).strftime('%d/%m')}"
await update.message.reply_text(ora)
async def prometeo_oggi(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if await no_can_do(update, context):
return
if len(context.args) == 1:
citta = context.args[0]
elif len(context.args) > 1:
citta = " ".join(context.args)
else:
citta = ""
user_settings = get_user_settings(context, user_id=update.effective_user.id)
pref_city = user_settings.get("prometeo_city", None)
citta = pref_city
API_KEY = config.OWM_API_KEY
await printlog(update, "chiede prometeo di oggi", citta)
# citta += ",,it"
geocoding_url = "http://api.openweathermap.org/geo/1.0/direct"
query = {"q": citta, "appid": API_KEY}
geocoding = requests.get(geocoding_url, query)
geodata = geocoding.json()
if not geodata:
await update.message.reply_text("Nessuna città trovata.")
return
lat = geodata[0]["lat"]
lon = geodata[0]["lon"]
country = geodata[0]["country"]
name = geodata[0]["name"]
# print(f"[Open Weather Map] Cerco: {name}, {country} [{lat}, {lon}]")
weather_url = "https://api.openweathermap.org/data/3.0/onecall"
weather_query = {
"lon": lon,
"lat": lat,
"units": "metric",
"lang": "it",
"exclude": "minutely,hourly",
"appid": API_KEY,
}
weather = requests.get(weather_url, weather_query)
data = weather.json()
try:
meteo = data["current"]
except KeyError:
await update.message.reply_text("Errore.")
return
air_url = "http://api.openweathermap.org/data/2.5/air_pollution"
air_query = {"lon": lon, "lat": lat, "appid": API_KEY}
airdata = requests.get(air_url, air_query)
air = airdata.json()
H = meteo["humidity"]
T = meteo["temp"]
THOM = T - 0.55 * (1 - (0.01 * H)) * (T - 14.5)
if THOM <= 21:
disagio = f"😊 [{round(THOM)}] benessere"
elif THOM <= 24:
disagio = f"😐 [{round(THOM)}] leggero disagio"
elif THOM <= 27:
disagio = f"🥺 [{round(THOM)}] crescente disagio"
elif THOM <= 29:
disagio = f"😵 [{round(THOM)}] disagio"
elif THOM <= 32:
disagio = f"🥵 [{round(THOM)}] forte disagio"
elif THOM > 32:
disagio = f"☠️ [{round(THOM)}] emergenza medica"
else:
disagio = "sconosciuto"
aqi = air["list"][0]["main"]["aqi"]
if aqi == 1:
aria = f"🟢 [{aqi}] buona"
elif aqi == 2:
aria = f"🔵 [{aqi}] moderata"
elif aqi == 3:
aria = f"🟡 [{aqi}] leggermente malsana"
elif aqi == 4:
aria = f"🟠 [{aqi}] malsana"
elif aqi == 5:
aria = f"🔴 [{aqi}] molto malsana"
elif aqi == 6:
aria = f"☠️ [{aqi}] pericolosa"
else:
aria = "sconosciuta"
emojis = {
"01": "☀️", # sole
"02": "⛅", # sole nuvole
"03": "🌥️", # nuvole
"04": "☁️", # nuvolacce
"09": "🌧️", # nuvolacce e pioggia
"10": "🌦️", # nuvole pioggia e sole
"11": "🌩️", # nuvolacce e fulmini
"13": "🌨️", # neve
"50": "🌫️", # fog
}
uv = meteo["uvi"]
if uv < 3:
uvi = f"🟩 [{uv}] basso"
elif uv < 6:
uvi = f"🟨 [{uv}] medio"
elif uv < 7:
uvi = f"🟧 [{uv}] alto"
elif uv < 11:
uvi = f"🟥 [{uv}] molto alto"
elif uv >= 11:
uvi = f"☠️ [{uv}] estremamente alto"
else:
uvi = "sconosciuto"
meteo_oggi = ""
meteo_oggi += f"<b>{name}, {country}</b> {'🌞' if meteo['sunrise'] < meteo['dt'] < meteo['sunset'] else '🌜'} {datetime.datetime.utcfromtimestamp(meteo['dt']+data['timezone_offset']).strftime('%H:%M')} del {datetime.datetime.utcfromtimestamp(meteo['dt']+data['timezone_offset']).strftime('%d/%m')}\n"
meteo_oggi += f"{'🌙' if meteo['weather'][0]['icon'] == '01n' else emojis[meteo['weather'][0]['icon'][:2]]} {str(meteo['weather'][0]['description']).capitalize()}, percepiti {meteo['feels_like']}°C\n\n"
meteo_oggi += f"Temperatura: {meteo['temp']}°C - Umidità: {meteo['humidity']}%\n"
meteo_oggi += f"Disagio climatico: {disagio}\n"
meteo_oggi += f"Qualità dell'aria: {aria}\n"
meteo_oggi += f"Indice UV: {uvi}"
await update.message.reply_html(meteo_oggi, disable_web_page_preview=True)
async def meteo_oggi(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if await no_can_do(update, context):
return
citta = ""
if not context.args:
if "default_meteo_city" in context.user_data:
citta = context.user_data["default_meteo_city"]
else:
await update.message.reply_html(
"Inserisci una città.\nSe vuoi impostare una città di default puoi usare <code>-setdefault [città]</code>, ad esempio: <code>/meteo -setdefault Napoli</code>"
)
return
else:
if context.args[0] == "-setdefault":
default_city = " ".join(context.args[1:])
context.user_data["default_meteo_city"] = default_city
await update.message.reply_text(f"Salvata: {default_city}")
return
API_KEY = config.OWM_API_KEY
if not citta:
if len(context.args) == 1:
citta = context.args[0]
elif len(context.args) > 1:
citta = " ".join(context.args)
else:
await update.message.reply_text("Devi inserire una città.")
return
# print(f'{get_now()} {await get_display_name(update.effective_user)} in {await get_chat_name(update.message.chat.id)} chiede il meteo semplice di oggi: {citta}')
await printlog(update, "chiede meteo di oggi", citta)
geocoding_url = "http://api.openweathermap.org/geo/1.0/direct"
query = {"q": citta, "appid": API_KEY}
geocoding = requests.get(geocoding_url, query)
geodata = geocoding.json()
if not geodata:
await update.message.reply_text("Nessuna città trovata.")
return
lat = geodata[0]["lat"]
lon = geodata[0]["lon"]
country = geodata[0]["country"]
name = geodata[0]["name"]
# print(f"[Open Weather Map] Cerco: {name}, {country} [{lat}, {lon}]")
weather_url = "https://api.openweathermap.org/data/3.0/onecall"
weather_query = {
"lon": lon,
"lat": lat,
"units": "metric",
"lang": "it",
"exclude": "minutely,hourly",
"appid": API_KEY,
}
weather = requests.get(weather_url, weather_query)
data = weather.json()
try:
meteo = data["current"]
except KeyError:
await update.message.reply_text("Errore.")
return
emojis = {
"01": "☀️", # sole
"02": "⛅", # sole nuvole
"03": "🌥️", # nuvole
"04": "☁️", # nuvolacce
"09": "🌧️", # nuvolacce e pioggia
"10": "🌦️", # nuvole pioggia e sole
"11": "🌩️", # nuvolacce e fulmini
"13": "🌨️", # neve
"50": "🌫️", # fog
}
meteo_oggi = ""
meteo_oggi += f"<b>{name}, {country}</b> {'🌞' if meteo['sunrise'] < meteo['dt'] < meteo['sunset'] else '🌜'} {datetime.datetime.utcfromtimestamp(meteo['dt']+data['timezone_offset']).strftime('%H:%M')} del {datetime.datetime.utcfromtimestamp(meteo['dt']+data['timezone_offset']).strftime('%d/%m')}\n"
meteo_oggi += f"{'🌙' if meteo['weather'][0]['icon'] == '01n' else emojis[meteo['weather'][0]['icon'][:2]]} {str(meteo['weather'][0]['description']).capitalize()}, percepiti {meteo['feels_like']}°C\n"
meteo_oggi += f"Temperatura: {meteo['temp']}°C - Umidità: {meteo['humidity']}%\n"
await update.message.reply_html(meteo_oggi, disable_web_page_preview=True)
async def forecast(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if await no_can_do(update, context):
return
# print(f'{get_now()} {await get_display_name(update.effective_user)} in {await get_chat_name(update.message.chat.id)} chiede il forecast metereologico')
if not context.args:
await update.message.reply_text("Inserisci una città")
return
API_KEY = config.OWM_API_KEY
citta = " ".join(context.args)
citta += ",,it"
geocoding_url = "http://api.openweathermap.org/geo/1.0/direct"
query = {"q": citta, "appid": API_KEY}
geocoding = requests.get(geocoding_url, query)
geodata = geocoding.json()
if not geodata:
await update.message.reply_text("Nessuna città trovata.")
return
await printlog(update, "chiede le previsioni metereologiche", citta)
lat = geodata[0]["lat"]
lon = geodata[0]["lon"]
country = geodata[0]["country"]
name = geodata[0]["name"]
print(f"[Open Weather Map] Cerco: {name}, {country} [{lat}, {lon}]")
weather_url = "https://api.openweathermap.org/data/3.0/onecall"
weather_query = {
"lon": lon,
"lat": lat,
"units": "metric",
"lang": "it",
"exclude": "minutely,hourly",
"appid": API_KEY,
}
weather = requests.get(weather_url, weather_query)
data = weather.json()
giorni = [0, 1, 2, 3]
emojis = {
"01d": "☀️", # sole
"02d": "⛅", # sole nuvole
"03d": "🌥️", # nuvole
"04d": "☁️", # nuvolacce
"09d": "🌧️", # nuvolacce e pioggia
"10d": "🌦️", # nuvole pioggia e sole
"11d": "🌩️", # nuvolacce e fulmini
"13d": "🌨️", # neve
"50d": "🌫️", # fog
}
meteo_oggi = ""
meteo_oggi += f"Città: {name}, {country}.\n"
for day in giorni:
try:
meteo = data["daily"][day]
except KeyError:
await update.message.reply_text("Errore.")
return
temp_min = round(meteo["temp"]["min"])
temp_max = round(meteo["temp"]["max"])
icon = meteo["weather"][0]["icon"]
aspetto = f"{emojis[icon]} {meteo['weather'][0]['description']}"
dt = datetime.datetime.utcfromtimestamp(meteo["dt"] + data["timezone_offset"]).strftime("%d/%m")
meteo_oggi += f"{dt} - {temp_max}/{temp_min}°C - {aspetto}\n"
await update.message.reply_text(meteo_oggi)