Compare commits
2 Commits
7f16f53028
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ccb77c7ae | |||
| d06a8eddc3 |
@@ -6,19 +6,25 @@ import time
|
|||||||
from dateutil import parser
|
from dateutil import parser
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
# --- CONFIGURAZIONE ---
|
# --- CONFIGURAZIONE UTENTE ---
|
||||||
# 👇👇 INSERISCI QUI I TUOI DATI 👇👇
|
|
||||||
TELEGRAM_BOT_TOKEN = "8155587974:AAF9OekvBpixtk8ZH6KoIc0L8edbhdXt7A4"
|
TELEGRAM_BOT_TOKEN = "8155587974:AAF9OekvBpixtk8ZH6KoIc0L8edbhdXt7A4"
|
||||||
TELEGRAM_CHAT_IDS = ["64463169", "24827341", "132455422", "5405962012"]
|
TELEGRAM_CHAT_IDS = ["64463169", "24827341", "132455422", "5405962012"]
|
||||||
|
|
||||||
# Coordinate (San Marino)
|
# Coordinate (San Marino / Casa)
|
||||||
LAT = 43.9356
|
LAT = 43.9356
|
||||||
LON = 12.4296
|
LON = 12.4296
|
||||||
|
|
||||||
# SOGLIE DI ALLARME
|
# --- SOGLIE DI ALLARME ---
|
||||||
WIND_LIMIT_WARN = 60.0 # km/h (Vento Forte)
|
# Vento (Protezione Civile Emilia-Romagna)
|
||||||
WIND_LIMIT_CRIT = 90.0 # km/h (Burrasca)
|
WIND_YELLOW = 62.0 # km/h
|
||||||
RAIN_3H_LIMIT = 30.0 # mm in 3 ore (Rischio idrogeologico)
|
WIND_ORANGE = 75.0 # km/h
|
||||||
|
WIND_RED = 88.0 # km/h
|
||||||
|
|
||||||
|
# Pioggia
|
||||||
|
RAIN_3H_LIMIT = 25.0 # mm in 3 ore
|
||||||
|
|
||||||
|
# Codici WMO per Gelicidio (Freezing Rain)
|
||||||
|
FREEZING_CODES = [56, 57, 66, 67]
|
||||||
|
|
||||||
# File di stato
|
# File di stato
|
||||||
STATE_FILE = "/home/daniely/docker/telegram-bot/weather_state.json"
|
STATE_FILE = "/home/daniely/docker/telegram-bot/weather_state.json"
|
||||||
@@ -31,7 +37,7 @@ def send_telegram_message(message):
|
|||||||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
||||||
for chat_id in TELEGRAM_CHAT_IDS:
|
for chat_id in TELEGRAM_CHAT_IDS:
|
||||||
try:
|
try:
|
||||||
requests.post(url, json={"chat_id": chat_id, "text": message, "parse_mode": "Markdown"}, timeout=5)
|
requests.post(url, json={"chat_id": chat_id, "text": message, "parse_mode": "Markdown"}, timeout=10)
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
@@ -39,7 +45,7 @@ def get_forecast():
|
|||||||
url = "https://api.open-meteo.com/v1/forecast"
|
url = "https://api.open-meteo.com/v1/forecast"
|
||||||
params = {
|
params = {
|
||||||
"latitude": LAT, "longitude": LON,
|
"latitude": LAT, "longitude": LON,
|
||||||
"hourly": "precipitation,windgusts_10m",
|
"hourly": "precipitation,windgusts_10m,weathercode",
|
||||||
"models": "arome_france_hd",
|
"models": "arome_france_hd",
|
||||||
"timezone": "Europe/Rome",
|
"timezone": "Europe/Rome",
|
||||||
"forecast_days": 2
|
"forecast_days": 2
|
||||||
@@ -55,7 +61,7 @@ def load_state():
|
|||||||
try:
|
try:
|
||||||
with open(STATE_FILE, 'r') as f: return json.load(f)
|
with open(STATE_FILE, 'r') as f: return json.load(f)
|
||||||
except: pass
|
except: pass
|
||||||
return {"alert_active": False, "last_wind": 0, "last_rain": 0, "time": 0}
|
return {"alert_active": False, "last_wind": 0, "last_rain": 0, "wind_level": 0, "freezing_active": False}
|
||||||
|
|
||||||
def save_state(state):
|
def save_state(state):
|
||||||
try:
|
try:
|
||||||
@@ -63,6 +69,7 @@ def save_state(state):
|
|||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
def analyze():
|
def analyze():
|
||||||
|
print("--- Controllo Meteo Severo (Wind/Rain/Ice) ---")
|
||||||
data = get_forecast()
|
data = get_forecast()
|
||||||
if not data: return
|
if not data: return
|
||||||
|
|
||||||
@@ -70,6 +77,7 @@ def analyze():
|
|||||||
times = hourly.get("time", [])
|
times = hourly.get("time", [])
|
||||||
wind = hourly.get("windgusts_10m", [])
|
wind = hourly.get("windgusts_10m", [])
|
||||||
rain = hourly.get("precipitation", [])
|
rain = hourly.get("precipitation", [])
|
||||||
|
wcode = hourly.get("weathercode", [])
|
||||||
|
|
||||||
now = datetime.datetime.now(ZoneInfo("Europe/Rome"))
|
now = datetime.datetime.now(ZoneInfo("Europe/Rome"))
|
||||||
state = load_state()
|
state = load_state()
|
||||||
@@ -90,76 +98,93 @@ def analyze():
|
|||||||
max_wind_time = ""
|
max_wind_time = ""
|
||||||
sum_rain_3h = 0.0
|
sum_rain_3h = 0.0
|
||||||
|
|
||||||
# Cerca picco vento
|
freezing_rain_detected = False
|
||||||
|
freezing_time = ""
|
||||||
|
|
||||||
|
# Cerca picchi
|
||||||
for i in range(start_idx, end_idx):
|
for i in range(start_idx, end_idx):
|
||||||
|
# Vento
|
||||||
if wind[i] > max_wind:
|
if wind[i] > max_wind:
|
||||||
max_wind = wind[i]
|
max_wind = wind[i]
|
||||||
max_wind_time = parser.isoparse(times[i]).strftime('%H:%M')
|
max_wind_time = parser.isoparse(times[i]).strftime('%H:%M')
|
||||||
|
|
||||||
# Cerca picco pioggia (sliding window 3h)
|
# Gelicidio
|
||||||
|
if wcode[i] in FREEZING_CODES:
|
||||||
|
freezing_rain_detected = True
|
||||||
|
if not freezing_time: # Prendi il primo orario
|
||||||
|
freezing_time = parser.isoparse(times[i]).strftime('%H:%M')
|
||||||
|
|
||||||
|
# Pioggia (sliding window 3h)
|
||||||
for i in range(start_idx, end_idx - 3):
|
for i in range(start_idx, end_idx - 3):
|
||||||
current_sum = sum(rain[i:i+3])
|
current_sum = sum(rain[i:i+3])
|
||||||
if current_sum > sum_rain_3h:
|
if current_sum > sum_rain_3h:
|
||||||
sum_rain_3h = current_sum
|
sum_rain_3h = current_sum
|
||||||
|
|
||||||
# --- LOGICA DI DECISIONE ---
|
# --- CLASSIFICAZIONE ---
|
||||||
|
alerts = []
|
||||||
is_wind_alarm = max_wind > WIND_LIMIT_WARN
|
should_notify = False
|
||||||
is_rain_alarm = sum_rain_3h > RAIN_3H_LIMIT
|
|
||||||
IS_ALARM_NOW = is_wind_alarm or is_rain_alarm
|
|
||||||
|
|
||||||
WAS_ALARM = state.get("alert_active", False)
|
WAS_ALARM = state.get("alert_active", False)
|
||||||
|
|
||||||
alerts = []
|
# 1. GELO (Priorità Massima)
|
||||||
|
if freezing_rain_detected:
|
||||||
|
if not state.get("freezing_active", False):
|
||||||
|
alerts.append(f"🧊 **ALLARME GELICIDIO**\nPrevista pioggia che gela (Freezing Rain).\n🕒 Inizio previsto: {freezing_time}\n_Pericolo ghiaccio su strada!_")
|
||||||
|
should_notify = True
|
||||||
|
state["freezing_active"] = True
|
||||||
|
else:
|
||||||
|
state["freezing_active"] = False
|
||||||
|
|
||||||
# SCENARIO A: NUOVO ALLARME o PEGGIORAMENTO
|
# 2. VENTO
|
||||||
if IS_ALARM_NOW:
|
wind_level_curr = 0
|
||||||
should_notify = False
|
if max_wind > WIND_RED:
|
||||||
|
wind_level_curr = 3
|
||||||
|
msg = f"🔴 **TEMPESTA (Burrasca Fortissima)**\nRaffiche > {WIND_RED:.0f} km/h (Picco: **{max_wind:.0f}** km/h).\n🕒 Ore {max_wind_time}"
|
||||||
|
elif max_wind > WIND_ORANGE:
|
||||||
|
wind_level_curr = 2
|
||||||
|
msg = f"🟠 **VENTO MOLTO FORTE**\nRaffiche > {WIND_ORANGE:.0f} km/h (Picco: **{max_wind:.0f}** km/h).\n🕒 Ore {max_wind_time}"
|
||||||
|
elif max_wind > WIND_YELLOW:
|
||||||
|
wind_level_curr = 1
|
||||||
|
msg = f"🟡 **VENTO FORTE**\nRaffiche > {WIND_YELLOW:.0f} km/h (Picco: **{max_wind:.0f}** km/h).\n🕒 Ore {max_wind_time}"
|
||||||
|
|
||||||
# Logica Vento
|
if wind_level_curr > 0:
|
||||||
if is_wind_alarm:
|
if not WAS_ALARM or wind_level_curr > state.get("wind_level", 0):
|
||||||
# Notifica se è nuovo o se è peggiorato di 10km/h rispetto all'ultimo avviso
|
alerts.append(msg)
|
||||||
if not WAS_ALARM or max_wind > state.get("last_wind", 0) + 10:
|
should_notify = True
|
||||||
icon = "💨" if max_wind < WIND_LIMIT_CRIT else "🌪️ ⛔️"
|
state["wind_level"] = wind_level_curr
|
||||||
livello = "FORTE" if max_wind < WIND_LIMIT_CRIT else "BURRASCA"
|
state["last_wind"] = max_wind
|
||||||
alerts.append(f"{icon} **VENTO {livello}**\nRaffiche previste fino a **{max_wind:.0f} km/h** verso le {max_wind_time}.\n_Consiglio: Ritirare oggetti leggeri._")
|
|
||||||
state["last_wind"] = max_wind
|
|
||||||
should_notify = True
|
|
||||||
|
|
||||||
# Logica Pioggia
|
# 3. PIOGGIA
|
||||||
if is_rain_alarm:
|
if sum_rain_3h > RAIN_3H_LIMIT:
|
||||||
# Notifica se è nuovo o se è peggiorata di 10mm
|
if not WAS_ALARM or sum_rain_3h > state.get("last_rain", 0) + 10:
|
||||||
if not WAS_ALARM or sum_rain_3h > state.get("last_rain", 0) + 10:
|
alerts.append(f"🌧️ **PIOGGIA INTENSA**\nPrevisti **{sum_rain_3h:.1f} mm** in 3 ore.")
|
||||||
alerts.append(f"🌧️ **PIOGGIA INTENSA**\nPrevisti **{sum_rain_3h:.1f} mm** in 3 ore.\n_Rischio disagi idraulici._")
|
state["last_rain"] = sum_rain_3h
|
||||||
state["last_rain"] = sum_rain_3h
|
should_notify = True
|
||||||
should_notify = True
|
|
||||||
|
|
||||||
if should_notify:
|
# --- INVIO ---
|
||||||
full_msg = f"⚠️ **AVVISO METEO (Prossime 12h)**\n\n" + "\n\n".join(alerts)
|
IS_ALARM_NOW = (wind_level_curr > 0) or (sum_rain_3h > RAIN_3H_LIMIT) or freezing_rain_detected
|
||||||
send_telegram_message(full_msg)
|
|
||||||
state["alert_active"] = True
|
|
||||||
state["time"] = time.time()
|
|
||||||
save_state(state)
|
|
||||||
print("Allerta inviata.")
|
|
||||||
else:
|
|
||||||
print("Condizioni critiche ma stabili (già notificato).")
|
|
||||||
|
|
||||||
# SCENARIO B: ALLARME RIENTRATO
|
if should_notify and alerts:
|
||||||
elif WAS_ALARM and not IS_ALARM_NOW:
|
full_msg = f"⚠️ **AVVISO METEO SEVERO**\n\n" + "\n\n".join(alerts)
|
||||||
msg = (
|
send_telegram_message(full_msg)
|
||||||
f"🟢 **ALLERTA METEO RIENTRATA**\n"
|
state["alert_active"] = True
|
||||||
f"📅 _Aggiornamento ore {now.strftime('%H:%M')}_\n\n"
|
|
||||||
f"Vento e pioggia sono scesi sotto le soglie di guardia per le prossime 12 ore."
|
|
||||||
)
|
|
||||||
send_telegram_message(msg)
|
|
||||||
|
|
||||||
# Reset stato
|
|
||||||
state = {"alert_active": False, "last_wind": 0, "last_rain": 0, "time": time.time()}
|
|
||||||
save_state(state)
|
save_state(state)
|
||||||
print("Allarme rientrato inviato.")
|
print("Allerta inviata.")
|
||||||
|
|
||||||
|
elif WAS_ALARM and not IS_ALARM_NOW:
|
||||||
|
# Allarme rientrato
|
||||||
|
msg = f"🟢 **ALLERTA METEO RIENTRATA**\nLe condizioni sono tornate sotto le soglie di guardia."
|
||||||
|
send_telegram_message(msg)
|
||||||
|
state = {"alert_active": False, "last_wind": 0, "last_rain": 0, "wind_level": 0, "freezing_active": False}
|
||||||
|
save_state(state)
|
||||||
|
print("Allarme rientrato.")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(f"Situazione tranquilla. Vento: {max_wind:.1f}, Pioggia: {sum_rain_3h:.1f}")
|
# Aggiorna stato parziale se serve (es. vento calato ma ancora presente)
|
||||||
|
if not IS_ALARM_NOW:
|
||||||
|
state["alert_active"] = False
|
||||||
|
save_state(state)
|
||||||
|
print(f"Nessun nuovo allarme. W:{max_wind:.0f} R:{sum_rain_3h:.1f} Ice:{freezing_rain_detected}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
analyze()
|
analyze()
|
||||||
|
|||||||
Reference in New Issue
Block a user