Backup automatico script del 2026-07-26 07:00
This commit is contained in:
1 parent
4802b021fe
commit
a9bbb92090
19 files changed
+1086
-550
No files matched your search
@@ -52,6 +52,12 @@ TARGET_ZONES = {
|
||||
"EMR-D1": "Pianura bolognese",
|
||||
}
|
||||
|
||||
# Annotazioni territoriali (San Marino adotta il sistema Emilia-Romagna)
|
||||
ZONE_NOTES = {
|
||||
"Alta collina romagnola": "include Repubblica di San Marino",
|
||||
"Pianura romagnola": "area adiacente a San Marino",
|
||||
}
|
||||
|
||||
# Mappa codice zona regionale Arpae -> nome leggibile (deriva da TARGET_ZONES,
|
||||
# togliendo il prefisso "EMR-": es. EMR-D1 -> D1 "Pianura bolognese").
|
||||
REGIONAL_TARGET_ZONES = {code.split("-")[-1]: name for code, name in TARGET_ZONES.items()}
|
||||
@@ -177,15 +183,12 @@ def telegram_send_html(message_html: str, chat_ids: Optional[List[str]] = None)
|
||||
message_html = re.sub(r"<\s*br\s*/?\s*>", "\n", message_html, flags=re.IGNORECASE)
|
||||
|
||||
try:
|
||||
from telegram_gate import mirror_alert_to_web, telegram_alerts_enabled
|
||||
from telegram_gate import telegram_alerts_enabled
|
||||
except ImportError:
|
||||
telegram_alerts_enabled = lambda: True # type: ignore
|
||||
mirror_alert_to_web = lambda *a, **k: False # type: ignore
|
||||
|
||||
if not telegram_alerts_enabled():
|
||||
LOGGER.info("Telegram sospeso: skip civil_protection")
|
||||
if message_html:
|
||||
mirror_alert_to_web(message_html, "civil_protection", "warning", is_html=True)
|
||||
return False
|
||||
|
||||
token = load_bot_token()
|
||||
@@ -219,15 +222,6 @@ def telegram_send_html(message_html: str, chat_ids: Optional[List[str]] = None)
|
||||
except Exception as e:
|
||||
LOGGER.exception("Telegram exception chat_id=%s err=%s", chat_id, e)
|
||||
|
||||
if sent_ok:
|
||||
try:
|
||||
import sys
|
||||
sys.path.insert(0, "/home/daniely/docker/shared")
|
||||
from loogle_core.alert_dispatcher import mirror_to_web
|
||||
mirror_to_web(message_html, "civil_protection", "warning", is_html=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return sent_ok
|
||||
|
||||
def load_state() -> dict:
|
||||
@@ -441,7 +435,9 @@ def format_message(parsed: dict) -> str:
|
||||
|
||||
lines.append(f"📅 <b>{html_lib.escape(day.get('date_label',''))}</b>")
|
||||
for zone in sorted(alerts.keys()):
|
||||
lines.append(f"📍 <b>{html_lib.escape(zone)}</b>")
|
||||
note = ZONE_NOTES.get(zone)
|
||||
zlabel = f"{zone} · {note}" if note else zone
|
||||
lines.append(f"📍 <b>{html_lib.escape(zlabel)}</b>")
|
||||
for entry in alerts[zone]:
|
||||
lines.append(html_lib.escape(entry))
|
||||
lines.append("")
|
||||
@@ -452,7 +448,9 @@ def format_message(parsed: dict) -> str:
|
||||
lines.append(f"🗺️ <b>{html_lib.escape(titolo)}</b>")
|
||||
alerts = doc.get("alerts", {})
|
||||
for zone in sorted(alerts.keys()):
|
||||
lines.append(f"📍 <b>{html_lib.escape(zone)}</b>")
|
||||
note = ZONE_NOTES.get(zone)
|
||||
zlabel = f"{zone} · {note}" if note else zone
|
||||
lines.append(f"📍 <b>{html_lib.escape(zlabel)}</b>")
|
||||
for entry in alerts[zone]:
|
||||
lines.append(html_lib.escape(entry))
|
||||
lines.append("")
|
||||
@@ -462,6 +460,18 @@ def format_message(parsed: dict) -> str:
|
||||
lines.append("<i>Fonte: mappe.protezionecivile.gov.it</i>")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _web_body_without_header(plain: str) -> str:
|
||||
"""Rimuove la riga titolo 'PROTEZIONE CIVILE…' già usata come title WebApp."""
|
||||
lines = (plain or "").splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
first = lines[0].strip().upper()
|
||||
if "PROTEZIONE CIVILE" in first:
|
||||
return "\n".join(lines[1:]).strip()
|
||||
return plain.strip()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Main
|
||||
# =============================================================================
|
||||
@@ -521,16 +531,37 @@ def main(chat_ids: Optional[List[str]] = None, debug_mode: bool = False):
|
||||
# A questo punto: ci sono allerte e sono nuove -> prova invio
|
||||
msg = format_message(parsed)
|
||||
sent_ok = telegram_send_html(msg, chat_ids=chat_ids)
|
||||
web_ok = False
|
||||
st = {
|
||||
"date": today_str_italy(),
|
||||
"last_alert_signature": sig,
|
||||
}
|
||||
try:
|
||||
from webapp_alert import publish_web_alert, remember_summary, message_to_plain
|
||||
plain = message_to_plain(msg, is_html=True)
|
||||
card_body = _web_body_without_header(plain)
|
||||
remember_summary(st, card_body)
|
||||
web_ok = bool(
|
||||
publish_web_alert(
|
||||
card_body,
|
||||
"civil_protection",
|
||||
"warning",
|
||||
is_html=False,
|
||||
title="Allerta Protezione Civile / Arpae",
|
||||
state=st,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
LOGGER.debug("Web summary failed: %s", e)
|
||||
|
||||
if sent_ok:
|
||||
LOGGER.info("Notifica allerta inviata con successo.")
|
||||
save_state({
|
||||
"date": today_str_italy(),
|
||||
"last_alert_signature": sig,
|
||||
})
|
||||
if sent_ok or web_ok:
|
||||
LOGGER.info(
|
||||
"Notifica allerta consegnata (%s).",
|
||||
"Telegram+WebApp" if sent_ok and web_ok else ("Telegram" if sent_ok else "WebApp"),
|
||||
)
|
||||
save_state(st)
|
||||
else:
|
||||
# Non aggiorniamo lo stato: quando risolvi token/rete, reinvierà.
|
||||
LOGGER.warning("Invio non riuscito (token mancante o errore Telegram). Stato NON aggiornato.")
|
||||
LOGGER.warning("Invio non riuscito (Telegram/WebApp). Stato NON aggiornato.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Civil protection alert")
|
||||
|
||||
Reference in new issue
Block a user