Files
buryan-infra/ops/scripts/secretary_brief.py
T

98 lines
3.9 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
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.
#!/usr/bin/env python3
"""Утренний брифинг секретаря: статус, алерты, бэкапы, календарь, медиа.
Детерминированный: без LLM, без прогонов. Отправляет в Matrix (Секретарь-Бета).
"""
import json
import os
import subprocess
import sys
import time
import urllib.request
GW = "http://127.0.0.1:9140"
ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0"
HS = "http://192.168.1.155:8008"
def call(tool, args=None):
tok = open("/root/.tool-gateway-owner-token").read().strip()
body = json.dumps({"tool": tool, "args": args or {}}).encode()
req = urllib.request.Request(GW + "/call", data=body,
headers={"Content-Type": "application/json",
"X-Gateway-Token": tok}, method="POST")
with urllib.request.urlopen(req, timeout=40) as r:
d = json.loads(r.read().decode())
return d.get("result") if d.get("ok") else d
def matrix(text):
tok = open("/root/.matrix-admin-token").read().strip()
txn = "brief-%d" % int(time.time() * 1000)
body = json.dumps({"msgtype": "m.text", "body": text}).encode()
url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s" % (HS, ROOM, txn, tok)
req = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"}, method="PUT")
with urllib.request.urlopen(req, timeout=20) as r:
return r.status
def main():
lines = ["☀️ **Утренний брифинг** — " + time.strftime("%d.%m.%Y %H:%M")]
try:
h = call("hub.status")
down = h.get("down") or []
lines.append("• Сервисы: **%s**, лежит: **%s**" % (h.get("total"), len(down) or "0"))
if down:
lines.append(" ⚠️ " + ", ".join(down[:8]))
except Exception as e:
lines.append("• Сервисы: ошибка (%s)" % str(e)[:80])
try:
a = call("alerts.active")
lines.append("• Алерты: **%s**" % a.get("count", "?"))
except Exception as e:
lines.append("• Алерты: ошибка (%s)" % str(e)[:80])
try:
b = call("backup.status")
jobs = b.get("jobs") or []
bad = [j for j in jobs if j.get("status") != "ok"]
lines.append("• Бэкап: **%s**" % ("ok" if not bad else "проблемы: " + ", ".join(j["name"] for j in bad)))
except Exception as e:
lines.append("• Бэкап: ошибка (%s)" % str(e)[:80])
try:
c = call("calendar.list", {"days": 7, "calendar": "Семья"})
ev = c.get("events") or []
lines.append("• Календарь (7 дней): **%s**" % c.get("count", len(ev)))
for x in ev[:3]:
lines.append(" – %s" % (x.get("summary") or x.get("start")))
except Exception as e:
lines.append("• Календарь: ошибка (%s)" % str(e)[:80])
try:
q = call("media.queue")
parts = []
for k in ("radarr", "sonarr"):
v = q.get(k) or {}
parts.append("%s %s" % (k, v.get("total", "?")))
lines.append("• Медиа-очередь: " + ", ".join(parts))
except Exception as e:
lines.append("• Медиа: ошибка (%s)" % str(e)[:80])
try:
r = call("media.recent")
items = r.get("items") or []
if items:
lines.append("• Новое в Jellyfin: " + ", ".join(items[:3]))
except Exception:
pass
text = "\n".join(lines)
try:
st = matrix(text)
print("sent", st)
except Exception as e:
print("matrix failed:", e)
subprocess.run(["/opt/buryan-hub/scripts/notify.py", "--priority", "normal",
"--title", "Утренний брифинг", text], timeout=30)
return 0
if __name__ == "__main__":
sys.exit(main())