Compare commits
2 Commits
db7f479e71
...
7f16f53028
| Author | SHA1 | Date | |
|---|---|---|---|
| 7f16f53028 | |||
| 7cf8e285b6 |
@@ -18,7 +18,6 @@ NAS_USER = "daniely"
|
||||
MASTER_IP = "192.168.128.80"
|
||||
|
||||
# --- LISTE DISPOSITIVI ---
|
||||
# Core: Dispositivi intelligenti (SSH, CPU, RAM)
|
||||
CORE_DEVICES = [
|
||||
{"name": "🍓 Pi-1 (Master)", "ip": MASTER_IP, "type": "pi", "user": SSH_USER},
|
||||
{"name": "🍓 Pi-2 (Backup)", "ip": "127.0.0.1", "type": "local", "user": ""},
|
||||
@@ -26,7 +25,6 @@ CORE_DEVICES = [
|
||||
{"name": "🗄️ NAS 214", "ip": "192.168.128.90", "type": "nas", "user": NAS_USER}
|
||||
]
|
||||
|
||||
# Infra: Solo Ping e Riavvio (Switch, WiFi)
|
||||
INFRA_DEVICES = [
|
||||
{"name": "📡 Router", "ip": "192.168.128.1"},
|
||||
{"name": "📶 WiFi Sala", "ip": "192.168.128.101"},
|
||||
@@ -47,27 +45,41 @@ logger = logging.getLogger(__name__)
|
||||
def run_cmd(command, ip=None, user=None):
|
||||
try:
|
||||
if ip == "127.0.0.1" or ip is None:
|
||||
return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip()
|
||||
return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, timeout=5).decode('utf-8').strip()
|
||||
else:
|
||||
safe_cmd = command.replace("'", "'\\''")
|
||||
full_cmd = f"ssh -o LogLevel=ERROR -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=4 {user}@{ip} '{safe_cmd}'"
|
||||
return subprocess.check_output(full_cmd, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip()
|
||||
full_cmd = f"ssh -o LogLevel=ERROR -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=3 {user}@{ip} '{safe_cmd}'"
|
||||
return subprocess.check_output(full_cmd, shell=True, stderr=subprocess.STDOUT, timeout=8).decode('utf-8').strip()
|
||||
except Exception: return "Err"
|
||||
|
||||
def get_ping_icon(ip):
|
||||
print(f"DEBUG: Pinging {ip}...") # LOG PER CAPIRE DOVE SI BLOCCA
|
||||
try:
|
||||
# Ping ultra-rapido (Timeout 1s)
|
||||
subprocess.check_call(["ping", "-c", "1", "-W", "1", ip], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
# Timeout aggressivo: 0.5 secondi (-W 1 è il minimo di ping standard, ma Python taglia a 0.8)
|
||||
subprocess.run(
|
||||
["ping", "-c", "1", "-W", "1", ip],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=0.8, # Timeout Python brutale
|
||||
check=True
|
||||
)
|
||||
return "✅"
|
||||
except: return "🔴"
|
||||
except subprocess.TimeoutExpired:
|
||||
return "🔴" # Timeout Python
|
||||
except subprocess.CalledProcessError:
|
||||
return "🔴" # Risposta "Host Unreachable"
|
||||
except Exception as e:
|
||||
print(f"Errore Ping {ip}: {e}")
|
||||
return "❓"
|
||||
|
||||
def get_device_stats(device):
|
||||
ip, user, dtype = device['ip'], device['user'], device['type']
|
||||
uptime_raw = run_cmd("uptime -p 2>/dev/null || uptime", ip, user)
|
||||
if not uptime_raw or "Err" in uptime_raw: return "🔴 **OFFLINE**"
|
||||
uptime = uptime_raw.replace("up ", "").split(", load")[0].split(", ")[0]
|
||||
|
||||
uptime = uptime_raw.replace("up ", "").split(", load")[0].split(", ")[0]
|
||||
temp = "N/A"
|
||||
|
||||
if dtype in ["pi", "local"]:
|
||||
t = run_cmd("cat /sys/class/thermal/thermal_zone0/temp", ip, user)
|
||||
if t.isdigit(): temp = f"{int(t)/1000:.1f}°C"
|
||||
@@ -78,6 +90,7 @@ def get_device_stats(device):
|
||||
|
||||
if dtype == "nas": ram_cmd = "free | grep Mem | awk '{printf \"%.0f%%\", $3*100/$2}'"
|
||||
else: ram_cmd = "free -m | awk 'NR==2{if ($2>0) printf \"%.0f%%\", $3*100/$2; else print \"0%\"}'"
|
||||
|
||||
disk_path = "/" if dtype != "nas" else "/volume1"
|
||||
disk_cmd = f"df -h {disk_path} | awk 'NR==2{{print $5}}'"
|
||||
|
||||
@@ -92,7 +105,7 @@ def run_speedtest():
|
||||
try: return subprocess.check_output("speedtest-cli --simple", shell=True, timeout=50).decode('utf-8')
|
||||
except: return "Errore Speedtest"
|
||||
|
||||
# --- GESTIONE MENU ---
|
||||
# --- BOT HANDLERS ---
|
||||
def restricted(func):
|
||||
@wraps(func)
|
||||
async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
|
||||
@@ -102,18 +115,16 @@ def restricted(func):
|
||||
|
||||
@restricted
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
# MENU PRINCIPALE
|
||||
keyboard = [
|
||||
[InlineKeyboardButton("🖥️ Core Server", callback_data="menu_core"), InlineKeyboardButton("🔍 Scan LAN", callback_data="menu_lan")],
|
||||
[InlineKeyboardButton("🛡️ Pi-hole", callback_data="menu_pihole"), InlineKeyboardButton("🌐 Rete", callback_data="menu_net")],
|
||||
[InlineKeyboardButton("📜 Logs", callback_data="menu_logs")]
|
||||
]
|
||||
text = "🎛 **Loogle Control Center**\nSeleziona un pannello:"
|
||||
text = "🎛 **Loogle Control Center v6.2**\nSeleziona un pannello:"
|
||||
|
||||
if update.message:
|
||||
await update.message.reply_text(text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
else:
|
||||
# Se chiamato da un pulsante "Indietro", modifica il messaggio esistente
|
||||
await update.callback_query.edit_message_text(text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
|
||||
@restricted
|
||||
@@ -124,7 +135,6 @@ async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
|
||||
if data == "main_menu": await start(update, context)
|
||||
|
||||
# --- MENU CORE ---
|
||||
elif data == "menu_core":
|
||||
keyboard = []
|
||||
for i, dev in enumerate(CORE_DEVICES): keyboard.append([InlineKeyboardButton(dev['name'], callback_data=f"stat_{i}")])
|
||||
@@ -143,42 +153,43 @@ async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
await query.edit_message_text(f"⏳ Controllo {dev['name']}...", parse_mode="Markdown")
|
||||
await query.edit_message_text(f"🔹 **{dev['name']}**\n\n{get_device_stats(dev)}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Indietro", callback_data="menu_core")]]), parse_mode="Markdown")
|
||||
|
||||
# --- MENU LAN (DIAGNOSTICA) ---
|
||||
elif data == "menu_lan":
|
||||
await query.edit_message_text("⏳ **Ping test in corso...**", parse_mode="Markdown")
|
||||
|
||||
await query.edit_message_text("⏳ **Scansione LAN rapida...**", parse_mode="Markdown")
|
||||
report = "🔍 **DIAGNOSTICA LAN**\n\n"
|
||||
|
||||
# Genera tabella compatta
|
||||
for dev in INFRA_DEVICES:
|
||||
status = get_ping_icon(dev['ip'])
|
||||
# Aggiunge riga: Icona Nome (IP)
|
||||
report += f"{status} **{dev['name']}**\n`{dev['ip']}`\n"
|
||||
try:
|
||||
# Core Devices
|
||||
for dev in CORE_DEVICES:
|
||||
report += f"{get_ping_icon(dev['ip'])} `{dev['ip']}` - {dev['name']}\n"
|
||||
|
||||
report += "\n"
|
||||
|
||||
# Infra Devices
|
||||
for dev in INFRA_DEVICES:
|
||||
report += f"{get_ping_icon(dev['ip'])} `{dev['ip']}` - {dev['name']}\n"
|
||||
|
||||
except Exception as e:
|
||||
report += f"\n⚠️ Errore imprevisto durante scansione: {e}"
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton("⚡ Menu Riavvio Dispositivi", callback_data="menu_reboot")],
|
||||
[InlineKeyboardButton("🔄 Aggiorna", callback_data="menu_lan")],
|
||||
[InlineKeyboardButton("⬅️ Indietro", callback_data="main_menu")]
|
||||
[InlineKeyboardButton("⚡ Menu Riavvio", callback_data="menu_reboot")],
|
||||
[InlineKeyboardButton("🔄 Aggiorna", callback_data="menu_lan"), InlineKeyboardButton("⬅️ Indietro", callback_data="main_menu")]
|
||||
]
|
||||
await query.edit_message_text(report, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
|
||||
# --- MENU RIAVVIO ---
|
||||
elif data == "menu_reboot":
|
||||
keyboard = []
|
||||
for i, dev in enumerate(INFRA_DEVICES):
|
||||
if "Router" not in dev['name']: # Protezione router
|
||||
keyboard.append([InlineKeyboardButton(f"⚡ {dev['name']}", callback_data=f"reboot_{i}")])
|
||||
if "Router" not in dev['name']: keyboard.append([InlineKeyboardButton(f"⚡ {dev['name']}", callback_data=f"reboot_{i}")])
|
||||
keyboard.append([InlineKeyboardButton("⬅️ Indietro", callback_data="menu_lan")])
|
||||
await query.edit_message_text("⚠️ **RIAVVIO REMOTO**\nRichiede SSH configurato sul dispositivo target (admin).", reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
await query.edit_message_text("⚠️ **RIAVVIO REMOTO**\nFunziona solo se il dispositivo supporta SSH e hai le chiavi.", reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
|
||||
elif data.startswith("reboot_"):
|
||||
dev = INFRA_DEVICES[int(data.split("_")[1])]
|
||||
# Tenta riavvio con utente 'admin' (standard per Zyxel/AP)
|
||||
res = run_cmd("reboot", dev['ip'], "admin")
|
||||
|
||||
await query.edit_message_text(f"⚡ Comando inviato a {dev['name']}...\n\nRisposta:\n`{res}`", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Indietro", callback_data="menu_reboot")]]), parse_mode="Markdown")
|
||||
|
||||
# --- ALTRI MENU (Pi-hole, Net, Logs) ---
|
||||
# --- ALTRI MENU STANDARD ---
|
||||
elif data == "menu_pihole":
|
||||
status_raw = run_cmd("sudo pihole status", MASTER_IP, SSH_USER)
|
||||
icon = "✅" if "Enabled" in status_raw or "enabled" in status_raw else "🔴"
|
||||
@@ -198,7 +209,7 @@ async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
await query.edit_message_text(f"🌐 **Rete**\n🌍 IP: `{ip}`", reply_markup=InlineKeyboardMarkup(keyboard), parse_mode="Markdown")
|
||||
|
||||
elif data == "net_speedtest":
|
||||
await query.edit_message_text("🚀 **Speedtest...**", parse_mode="Markdown")
|
||||
await query.edit_message_text("🚀 **Speedtest in corso...**", parse_mode="Markdown")
|
||||
res = run_speedtest()
|
||||
await query.edit_message_text(f"🚀 **Risultato:**\n\n`{res}`", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Indietro", callback_data="menu_net")]]), parse_mode="Markdown")
|
||||
|
||||
|
||||
134
services/telegram-bot/freeze_alert.py
Normal file
134
services/telegram-bot/freeze_alert.py
Normal file
@@ -0,0 +1,134 @@
|
||||
import requests
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from dateutil import parser
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
# --- CONFIGURAZIONE UTENTE ---
|
||||
TELEGRAM_BOT_TOKEN = "8155587974:AAF9OekvBpixtk8ZH6KoIc0L8edbhdXt7A4"
|
||||
TELEGRAM_CHAT_IDS = ["64463169", "24827341", "132455422", "5405962012"]
|
||||
|
||||
# --- COORDINATE (Strada Cà Toro, 12 - San Marino) ---
|
||||
LAT = 43.9356
|
||||
LON = 12.4296
|
||||
LOCATION_NAME = "🏠 Casa (Strada Cà Toro)"
|
||||
|
||||
# Soglia Gelo (°C)
|
||||
SOGLIA_GELO = 0.0
|
||||
|
||||
# File di stato
|
||||
STATE_FILE = "/home/daniely/docker/telegram-bot/freeze_state.json"
|
||||
|
||||
def load_state():
|
||||
if os.path.exists(STATE_FILE):
|
||||
try:
|
||||
with open(STATE_FILE, 'r') as f: return json.load(f)
|
||||
except: pass
|
||||
return {"alert_active": False, "min_temp": 100.0}
|
||||
|
||||
def save_state(active, min_temp):
|
||||
try:
|
||||
with open(STATE_FILE, 'w') as f:
|
||||
json.dump({"alert_active": active, "min_temp": min_temp, "updated": str(datetime.datetime.now())}, f)
|
||||
except: pass
|
||||
|
||||
def send_telegram_message(message):
|
||||
if not TELEGRAM_BOT_TOKEN or "INSERISCI" in TELEGRAM_BOT_TOKEN:
|
||||
print(f"[TEST OUT] {message}")
|
||||
return
|
||||
|
||||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
||||
for chat_id in TELEGRAM_CHAT_IDS:
|
||||
try:
|
||||
requests.post(url, json={"chat_id": chat_id, "text": message, "parse_mode": "Markdown"}, timeout=10)
|
||||
time.sleep(0.2)
|
||||
except: pass
|
||||
|
||||
def get_forecast():
|
||||
url = "https://api.open-meteo.com/v1/forecast"
|
||||
params = {
|
||||
"latitude": LAT, "longitude": LON,
|
||||
"hourly": "temperature_2m",
|
||||
"timezone": "Europe/Rome",
|
||||
"forecast_days": 3 # Prendiamo 3 giorni per coprire bene le 48h
|
||||
}
|
||||
try:
|
||||
r = requests.get(url, params=params, timeout=10)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except: return None
|
||||
|
||||
def analyze_freeze():
|
||||
print("--- Controllo Gelo ---")
|
||||
data = get_forecast()
|
||||
if not data: return
|
||||
|
||||
hourly = data.get("hourly", {})
|
||||
times = hourly.get("time", [])
|
||||
temps = hourly.get("temperature_2m", [])
|
||||
|
||||
now = datetime.datetime.now(ZoneInfo("Europe/Rome"))
|
||||
limit_time = now + datetime.timedelta(hours=48)
|
||||
|
||||
min_temp_val = 100.0
|
||||
min_temp_time = None
|
||||
|
||||
# Cerca la minima nelle prossime 48 ore
|
||||
for i, t_str in enumerate(times):
|
||||
t_obj = parser.isoparse(t_str).replace(tzinfo=ZoneInfo("Europe/Rome"))
|
||||
|
||||
# Filtra solo futuro prossimo (da adesso a +48h)
|
||||
if t_obj > now and t_obj <= limit_time:
|
||||
temp = temps[i]
|
||||
if temp < min_temp_val:
|
||||
min_temp_val = temp
|
||||
min_temp_time = t_obj
|
||||
|
||||
# --- LOGICA ALLARME ---
|
||||
state = load_state()
|
||||
was_active = state.get("alert_active", False)
|
||||
|
||||
# C'è rischio gelo?
|
||||
is_freezing = min_temp_val < SOGLIA_GELO
|
||||
|
||||
if is_freezing:
|
||||
# Formatta orario
|
||||
time_str = min_temp_time.strftime('%d/%m alle %H:%M')
|
||||
|
||||
# SCENARIO A: NUOVO GELO (o peggioramento significativo di 2 gradi)
|
||||
if not was_active or min_temp_val < state.get("min_temp", 0) - 2.0:
|
||||
msg = (
|
||||
f"❄️ **ALLERTA GELO**\n"
|
||||
f"📍 {LOCATION_NAME}\n\n"
|
||||
f"Prevista temperatura minima di **{min_temp_val:.1f}°C**\n"
|
||||
f"📅 Quando: {time_str}\n\n"
|
||||
f"_Proteggere piante e tubature esterne._"
|
||||
)
|
||||
send_telegram_message(msg)
|
||||
save_state(True, min_temp_val)
|
||||
print(f"Allerta inviata: {min_temp_val}°C")
|
||||
else:
|
||||
print(f"Gelo già notificato ({min_temp_val}°C).")
|
||||
# Aggiorniamo comunque la minima registrata nel file
|
||||
save_state(True, min(min_temp_val, state.get("min_temp", 100)))
|
||||
|
||||
# SCENARIO B: ALLARME RIENTRATO
|
||||
elif was_active and not is_freezing:
|
||||
msg = (
|
||||
f"☀️ **RISCHIO GELO RIENTRATO**\n"
|
||||
f"📍 {LOCATION_NAME}\n\n"
|
||||
f"Le previsioni per le prossime 48 ore indicano temperature sopra lo zero.\n"
|
||||
f"Minima prevista: {min_temp_val:.1f}°C."
|
||||
)
|
||||
send_telegram_message(msg)
|
||||
save_state(False, min_temp_val)
|
||||
print("Allarme rientrato.")
|
||||
|
||||
else:
|
||||
save_state(False, min_temp_val)
|
||||
print(f"Nessun gelo. Minima: {min_temp_val}°C")
|
||||
|
||||
if __name__ == "__main__":
|
||||
analyze_freeze()
|
||||
Reference in New Issue
Block a user