"""Дневной дайджест по событиям ядра.""" import json import os import sys import urllib.parse import urllib.request from datetime import datetime, timezone import psycopg2 DSN = os.environ.get("CORE_DSN", "dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8") MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru") TOKEN = os.environ.get("NOTIFY_TOKEN", "") ROOM = os.environ.get("NOTIFY_ROOM", "") def send(text): if not (TOKEN and ROOM): print("нет настроек Matrix") return False txn = int(datetime.now().timestamp() * 1000) rid = urllib.parse.quote(ROOM, safe="") body = json.dumps({"msgtype": "m.text", "body": text, "format": "org.matrix.custom.html", "formatted_body": text.replace("\n", "
")}).encode() req = urllib.request.Request( f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}", data=body, method="PUT", headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=15): return True except Exception as e: print("не отправилось:", str(e)[:100]) return False def main(): con = psycopg2.connect(DSN, connect_timeout=10) cur = con.cursor() cur.execute("""select source, type, count(*) from events where at > now() - interval '24 hours' group by source, type order by 3 desc""") rows = cur.fetchall() cur.execute("""select count(*) from entities""") entities = cur.fetchone()[0] cur.execute("""select count(*) from problems where resolved_at is null""") open_problems = cur.fetchone()[0] cur.execute("""select count(*) from actions where at > now() - interval '24 hours'""") actions = cur.fetchone()[0] cur.execute("""select source, type, entity->>'title' from events where at > now() - interval '24 hours' and type in ('media.imported','media.requested','service.alert','document.added','book.added') order by id desc limit 8""") notable = cur.fetchall() con.close() lines = [f"**Сводка · {datetime.now(timezone.utc).strftime('%d.%m')}**", ""] if not rows: lines.append("_За сутки событий не было._") else: total = sum(r[2] for r in rows) lines.append(f"**Событий за сутки: {total}**") for src, typ, n in rows[:8]: lines.append(f"• {src}: {typ} — {n}") if notable: lines.append("\n**Заметное**") for src, typ, title in notable: lines.append(f"• {title or '—'} ({typ}, {src})") lines.append("") lines.append(f"Карточек: {entities} · открытых проблем: {open_problems} · действий: {actions}") text = "\n".join(lines) ok = send(text) print(text.replace("\n", " | ")[:500]) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())