Воскресенье 20:00: события за 7 дней по источникам, карточки по видам, связи, проблемы (новые/решённые), действия автоматики, заметное. Отправляется боту Дайджест. Проверено: отчёт собран и отправлен — 68 событий, 66 карточек по видам, 1 проблема закрыта, 1 действие.
120 lines
4.2 KiB
Python
120 lines
4.2 KiB
Python
"""Недельный отчёт: что происходило в системе за 7 дней."""
|
|
import json
|
|
import os
|
|
import re
|
|
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 = "https://matrix.buryans.ru"
|
|
|
|
|
|
def bot_creds(name="DIGEST"):
|
|
env, dm = {}, {}
|
|
for path, target in (("/etc/hub-bots/bots.env", env), ("/etc/hub-bots/dm.env", dm)):
|
|
try:
|
|
for line in open(path, encoding="utf-8"):
|
|
m = re.match(r"^([A-Z_]+)=(.*)$", line.strip())
|
|
if m:
|
|
target[m.group(1)] = m.group(2).strip()
|
|
except OSError:
|
|
pass
|
|
return env.get(f"{name}_TOKEN"), dm.get(name) or env.get(f"{name}_ROOM")
|
|
|
|
|
|
def send(text):
|
|
token, room = bot_creds()
|
|
if not (token and room):
|
|
print("нет настроек бота Дайджест")
|
|
return False
|
|
rid = urllib.parse.quote(room, safe="")
|
|
txn = int(datetime.now().timestamp() * 1000)
|
|
body = json.dumps({"msgtype": "m.text", "body": text,
|
|
"format": "org.matrix.custom.html",
|
|
"formatted_body": text.replace("\n", "<br>")}).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=20):
|
|
return True
|
|
except Exception as e:
|
|
print("не отправилось:", str(e)[:120])
|
|
return False
|
|
|
|
|
|
def main():
|
|
con = psycopg2.connect(DSN, connect_timeout=10)
|
|
cur = con.cursor()
|
|
|
|
cur.execute("""select source, count(*) from events
|
|
where at > now() - interval '7 days'
|
|
group by source order by 2 desc limit 10""")
|
|
by_source = cur.fetchall()
|
|
|
|
cur.execute("""select count(*) from events where at > now() - interval '7 days'""")
|
|
total = cur.fetchone()[0]
|
|
|
|
cur.execute("""select kind, count(*) from entities group by kind order by 2 desc limit 8""")
|
|
kinds = cur.fetchall()
|
|
|
|
cur.execute("""select count(*) from problems where at > now() - interval '7 days'""")
|
|
problems_new = cur.fetchone()[0]
|
|
|
|
cur.execute("""select count(*) from problems where resolved_at > now() - interval '7 days'""")
|
|
problems_done = cur.fetchone()[0]
|
|
|
|
cur.execute("""select count(*) from actions where at > now() - interval '7 days'""")
|
|
actions = cur.fetchone()[0]
|
|
|
|
cur.execute("""select count(*) from entity_links""")
|
|
links = cur.fetchone()[0]
|
|
|
|
cur.execute("""select source, type, entity->>'title' from events
|
|
where at > now() - interval '7 days'
|
|
and type in ('media.imported','media.requested','document.added',
|
|
'book.added','photo.album','camera.detection')
|
|
order by id desc limit 10""")
|
|
notable = cur.fetchall()
|
|
con.close()
|
|
|
|
lines = [f"**Неделя в Buryan Hub** ({datetime.now(timezone.utc).strftime('%d.%m')})", ""]
|
|
|
|
if total:
|
|
lines.append(f"**Событий: {total}**")
|
|
for src, n in by_source:
|
|
lines.append(f"• {src}: {n}")
|
|
else:
|
|
lines.append("_Событий за неделю не было._")
|
|
|
|
if kinds:
|
|
lines.append("")
|
|
lines.append("**Карточки по видам**")
|
|
lines.append(" · ".join(f"{k}: {n}" for k, n in kinds))
|
|
lines.append(f"связей между карточками: {links}")
|
|
|
|
lines.append("")
|
|
lines.append(f"**Проблемы:** новых {problems_new}, решено {problems_done}")
|
|
lines.append(f"**Действий автоматики:** {actions}")
|
|
|
|
if notable:
|
|
lines.append("")
|
|
lines.append("**Заметное**")
|
|
for src, typ, title in notable[:6]:
|
|
lines.append(f"• {title or '—'} ({typ})")
|
|
|
|
text = "\n".join(lines)
|
|
ok = send(text)
|
|
print(text.replace("\n", " | ")[:600])
|
|
return 0 if ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|