Files
loogle-scripts/services/telegram-bot/daily_report.py

128 lines
3.7 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sqlite3
import os
import datetime
import urllib.request
import urllib.parse
import json
# --- CONFIGURAZIONE ---
BOT_TOKEN = os.environ.get('BOT_TOKEN')
CHAT_ID = os.environ.get('ALLOWED_USER_ID')
DB_PATH = "/data/speedtest.sqlite"
# SOGLIE DI ALLARME (Mbps)
WARN_DOWN = 400
WARN_UP = 100
def send_telegram_message(message):
if not message: return
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "Markdown"
}
try:
data = urllib.parse.urlencode(payload).encode('utf-8')
req = urllib.request.Request(url, data=data)
with urllib.request.urlopen(req) as response:
if response.status == 200:
print("✅ Report inviato.")
except Exception as e:
print(f"❌ Errore invio Telegram: {e}")
def generate_report():
if not os.path.exists(DB_PATH):
print(f"❌ Database non trovato: {DB_PATH}")
return None
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Timezone UTC per la query
yesterday = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=24)
query = "SELECT download, upload, ping, created_at FROM results WHERE created_at > ? AND status = 'completed' ORDER BY created_at ASC"
cursor.execute(query, (yesterday,))
rows = cursor.fetchall()
except Exception as e:
print(f"❌ Errore DB: {str(e)}")
return None
finally:
if 'conn' in locals(): conn.close()
if not rows:
print(" Nessun test trovato.")
return None
# Variabili
total_down = 0
total_up = 0
count = 0
issues = 0
# Intestazione
now_local = datetime.datetime.now()
msg = f"📊 **REPORT VELOCITÀ 24H**\n📅 {now_local.strftime('%d/%m/%Y')}\n\n"
# Inizio Tabella Monospazio
# Allarghiamo le colonne per farci stare "Mb"
# ORA (5) | DOWN (6) | UP (5)
msg += "```text\n"
msg += "ORA | DOWN | UP \n"
msg += "------+--------+------\n"
for row in rows:
d_val = (int(row[0]) * 8) / 1000000
u_val = (int(row[1]) * 8) / 1000000
total_down += d_val
total_up += u_val
count += 1
marker = ""
if d_val < WARN_DOWN or u_val < WARN_UP:
issues += 1
marker = "!"
try:
d_str = row[3].split(".")[0].replace("T", " ")
dt_utc = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=datetime.timezone.utc)
dt_local = dt_utc.astimezone()
time_str = dt_local.strftime('%H:%M')
except:
time_str = "--:--"
# FORMATTAZIONE CON UNITÀ
# Creiamo stringhe tipo "850Mb"
d_text = f"{int(d_val)}Mb"
u_text = f"{int(u_val)}Mb"
# Allineamento:
# :>6 significa "occupa 6 spazi allineato a destra"
row_str = f"{time_str} | {d_text:>6} | {u_text:>5} {marker}"
msg += f"{row_str}\n"
msg += "```\n"
if count > 0:
avg_d = total_down / count
avg_u = total_up / count
icon_d = "" if avg_d >= WARN_DOWN else "⚠️"
icon_u = "" if avg_u >= WARN_UP else "⚠️"
# Media su una riga sola con "Mb"
msg += f"📈 **MEDIA:** ⬇️{icon_d}`{avg_d:.0f}Mb` ⬆️{icon_u}`{avg_u:.0f}Mb`"
if issues > 0:
msg += f"\n\n⚠️ **{issues}** test sotto soglia (!)"
return msg
if __name__ == "__main__":
report = generate_report()
if report:
send_telegram_message(report)