API данных: боты сохраняют всё в папку проекта
POST /data/<коллекция> — запись документа, GET /data/<коллекция> — чтение, POST /export — выгрузка в /root/buryan-infra/data/. Боты при любом пожелании пишут его в коллекцию wishes (кто, какой бот, номер, текст). Команда !export выгружает коллекцию из чата. Каждый день в 23:00 cron выгружает wishes, dialog, events и копирует журналы. Проверено: пожелание от @polina легло в API и в файл, !export вернул путь, в папке проекта 6 файлов (wishes, dialog, events, logs).
This commit is contained in:
1 parent
cc7c98dad7
commit
e0309080bc
11 files changed
+364
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# dialog
|
||||
|
||||
записей: 0
|
||||
@@ -0,0 +1,3 @@
|
||||
# events
|
||||
|
||||
записей: 0
|
||||
@@ -0,0 +1,5 @@
|
||||
{"id": 1, "at": "2026-10-19T20:11:55", "bot": "media", "from": "@polina:matrix.buryans.ru", "kind": "пожелание", "text": "хочу больше мультфильмов про кота"}
|
||||
{"id": 2, "at": "2026-10-19T20:11:55", "bot": "book", "from": "@sergey:matrix.buryans.ru", "kind": "пожелание", "text": "добавьте больше фантастики"}
|
||||
{"id": 3, "at": "2026-10-19T20:12:21", "bot": "media", "from": "@polina:matrix.buryans.ru", "kind": "пожелание", "text": "хочу больше мультфильмов про кота"}
|
||||
{"id": 4, "at": "2026-10-19T20:12:21", "bot": "book", "from": "@sergey:matrix.buryans.ru", "kind": "пожелание", "text": "добавьте больше фантастики"}
|
||||
{"id": 5, "at": "2026-10-19T20:13:05", "bot": "media", "from": "@polina:matrix.buryans.ru", "kind": "пожелание", "text": "хочу сериал про космос"}
|
||||
@@ -0,0 +1 @@
|
||||
{"at": "2026-10-19T19:26:09", "bot": "media", "q": "расскажи как дела у нашей медиатеки", "a": "Понял: расскажи как дела у нашей медиатеки. Это заглушка."}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"collection": "wishes",
|
||||
"exported_at": "2026-10-19 20:11:24.911993",
|
||||
"count": 2,
|
||||
"items": [
|
||||
{
|
||||
"id": 2,
|
||||
"key": "wish-002",
|
||||
"payload": {
|
||||
"от": "Сергей",
|
||||
"бот": "cam",
|
||||
"текст": "добавить камеры во двор"
|
||||
},
|
||||
"tags": [
|
||||
"пожелание"
|
||||
],
|
||||
"updated_at": "2026-10-19 17:11:24.853757+00:00"
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"key": "wish-001",
|
||||
"payload": {
|
||||
"от": "Полина",
|
||||
"бот": "media",
|
||||
"текст": "хочу мультфильмы про кота"
|
||||
},
|
||||
"tags": [
|
||||
"пожелание",
|
||||
"семья"
|
||||
],
|
||||
"updated_at": "2026-10-19 17:11:24.834397+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# wishes
|
||||
|
||||
записей: 3
|
||||
|
||||
## 7bd8e6589111cdcf
|
||||
обновлено: 2026-10-19 17:13:05.235512+00:00
|
||||
* **от**: @polina:matrix.buryans.ru
|
||||
* **бот**: media
|
||||
* **номер**: 5
|
||||
* **текст**: хочу сериал про космос
|
||||
|
||||
## wish-002
|
||||
обновлено: 2026-10-19 17:11:24.853757+00:00
|
||||
* **от**: Сергей
|
||||
* **бот**: cam
|
||||
* **текст**: добавить камеры во двор
|
||||
|
||||
## wish-001
|
||||
обновлено: 2026-10-19 17:11:24.834397+00:00
|
||||
* **от**: Полина
|
||||
* **бот**: media
|
||||
* **текст**: хочу мультфильмы про кота
|
||||
@@ -0,0 +1,51 @@
|
||||
# API данных: боты пишут в папку проекта
|
||||
|
||||
Любой бот (и любой сервис) может сохранить данные в ядро — они лягут
|
||||
в папку проекта `/root/buryan-infra/data/`.
|
||||
|
||||
## Записать
|
||||
|
||||
```
|
||||
POST /data/<коллекция>
|
||||
{"key": "уникальный-ключ", "payload": {"любые": "поля"}, "tags": ["метка"]}
|
||||
```
|
||||
|
||||
Повторная запись с тем же ключом обновляет документ.
|
||||
|
||||
## Прочитать
|
||||
|
||||
```
|
||||
GET /data/<коллекция>?limit=50&tag=пожелание
|
||||
```
|
||||
|
||||
## Выгрузить в папку проекта
|
||||
|
||||
```
|
||||
POST /export
|
||||
{"collection": "wishes", "format": "md"} # или json
|
||||
```
|
||||
|
||||
Файл появится в `/root/buryan-infra/data/<коллекция>/`.
|
||||
|
||||
## Что уже пишется автоматически
|
||||
|
||||
| Что | Куда |
|
||||
|---|---|
|
||||
| Пожелания из любого бота | коллекция `wishes` |
|
||||
| Диалоги с моделью | `/var/lib/hub-bots/dialog.jsonl` → `data/logs/` |
|
||||
| Входящие пожелания | `/var/lib/hub-bots/inbox/*.jsonl` → `data/logs/` |
|
||||
| События системы | коллекция `events` |
|
||||
|
||||
Ежедневно в 23:00 (`/etc/cron.d/hub-export`) всё выгружается в репозиторий.
|
||||
|
||||
## Команда бота
|
||||
|
||||
`!export wishes` — выгрузить коллекцию прямо из чата, бот вернёт путь.
|
||||
|
||||
## Проверено
|
||||
|
||||
* пожелание «хочу сериал про космос» от @polina легло в `wishes`
|
||||
с полями от/бот/номер/текст;
|
||||
* `!export wishes` выгрузил файл и вернул путь;
|
||||
* в папке проекта: `data/wishes/`, `data/dialog/`, `data/events/`,
|
||||
`data/logs/` (6 файлов).
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Клиент API ядра для ботов."""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
||||
|
||||
|
||||
def _get(path, params=None, timeout=10):
|
||||
url = f"{CORE}{path}"
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def _post(path, payload, timeout=15):
|
||||
req = urllib.request.Request(f"{CORE}{path}", data=json.dumps(payload).encode(),
|
||||
method="POST", headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def alive():
|
||||
data, err = _get("/health", timeout=5)
|
||||
return bool(data and data.get("ok")), err
|
||||
|
||||
|
||||
def search(q, limit=20):
|
||||
return _get("/search", {"q": q})
|
||||
|
||||
|
||||
def card(eid):
|
||||
return _get(f"/entity/{eid}")
|
||||
|
||||
|
||||
def events(limit=30):
|
||||
return _get("/events")
|
||||
|
||||
|
||||
def stats():
|
||||
return _get("/health")
|
||||
|
||||
|
||||
def save_data(collection, key, payload, tags=None):
|
||||
"""Сохранить документ в коллекцию."""
|
||||
return _post(f"/data/{collection}", {"key": key, "payload": payload, "tags": tags or []})
|
||||
|
||||
|
||||
def get_data(collection, limit=100, tag=None):
|
||||
params = {"limit": limit}
|
||||
if tag:
|
||||
params["tag"] = tag
|
||||
return _get(f"/data/{collection}", params)
|
||||
|
||||
|
||||
def export_data(collection, fmt="md", filename=None):
|
||||
"""Выгрузить коллекцию в папку проекта."""
|
||||
body = {"collection": collection, "format": fmt}
|
||||
if filename:
|
||||
body["filename"] = filename
|
||||
return _post("/export", body)
|
||||
@@ -231,6 +231,8 @@ class Bot:
|
||||
|
||||
def dispatch(self, text, in_dm=False):
|
||||
cmd, arg, raw = self._parse(text, in_dm)
|
||||
if (cmd is None and raw.lower().startswith("export")) or cmd == "export":
|
||||
return self._export((raw[6:].strip() if raw.lower().startswith("export") else arg))
|
||||
if cmd is None:
|
||||
if not in_dm:
|
||||
return None
|
||||
@@ -301,11 +303,40 @@ class Bot:
|
||||
num = inbox.add(self.name, self.last_sender or "?", text)
|
||||
if num is None:
|
||||
return "Принял, но сегодня уже слишком много сообщений. Попробуйте завтра."
|
||||
self._export_data("wishes", {
|
||||
"от": self.last_sender or "неизвестно",
|
||||
"бот": self.name,
|
||||
"номер": num,
|
||||
"текст": text[:1000],
|
||||
}, tags=["пожелание"])
|
||||
self.notify_owner(text, num)
|
||||
return (f"Принял: «{text[:200]}»\n\n"
|
||||
f"Это не команда, поэтому передал владельцу и агенту — "
|
||||
f"запись №{num}. Ответ придёт, когда её посмотрят.")
|
||||
|
||||
|
||||
def _export_data(self, collection, payload, tags=None):
|
||||
"""Отправить данные в ядро — они лягут в папку проекта."""
|
||||
try:
|
||||
from . import core_api
|
||||
import hashlib, time
|
||||
key = hashlib.sha1(
|
||||
(self.name + str(payload) + str(time.time())).encode()).hexdigest()[:16]
|
||||
core_api.save_data(collection, key, payload, tags or [])
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _export(self, arg):
|
||||
"""Выгрузить коллекцию в папку проекта."""
|
||||
from . import core_api
|
||||
collection = (arg or "").strip() or "wishes"
|
||||
data, err = core_api.export_data(collection, "md")
|
||||
if err:
|
||||
return f"Не получилось выгрузить: {err}"
|
||||
return (f"Выгружено в папку проекта:\n`{data.get('path')}`\n"
|
||||
f"записей: {data.get('count')}")
|
||||
|
||||
def notify_owner(self, text, num):
|
||||
"""Копия просьбы уходит владельцу, чтобы её не потерять."""
|
||||
owner = self.owner
|
||||
|
||||
@@ -121,6 +121,109 @@ def do_entity(eid):
|
||||
return {"card": card, "links": links, "history": history}
|
||||
|
||||
|
||||
|
||||
|
||||
DATA_DIR = os.environ.get("PROJECT_DATA", "/root/buryan-infra/data")
|
||||
|
||||
|
||||
def _ensure_doc_table():
|
||||
con = db()
|
||||
with con.cursor() as cur:
|
||||
cur.execute("""
|
||||
create table if not exists data_docs (
|
||||
id bigserial primary key,
|
||||
collection text not null,
|
||||
key text not null,
|
||||
payload jsonb not null,
|
||||
tags text[] not null default '{}',
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
unique (collection, key)
|
||||
)""")
|
||||
cur.execute("create index if not exists idx_docs_collection on data_docs (collection)")
|
||||
con.close()
|
||||
|
||||
|
||||
def do_data_put(collection, data):
|
||||
"""Сохранить документ: {key, payload, tags}."""
|
||||
_ensure_doc_table()
|
||||
key = str(data.get("key") or "").strip()
|
||||
if not key:
|
||||
return None, "нужен key"
|
||||
payload = data.get("payload") or {}
|
||||
tags = data.get("tags") or []
|
||||
con = db()
|
||||
cur = con.cursor()
|
||||
cur.execute("""insert into data_docs (collection, key, payload, tags)
|
||||
values (%s, %s, %s, %s)
|
||||
on conflict (collection, key) do update
|
||||
set payload = excluded.payload,
|
||||
tags = excluded.tags,
|
||||
updated_at = now()
|
||||
returning id, updated_at""",
|
||||
(collection, key, json.dumps(payload, ensure_ascii=False), tags))
|
||||
row = cur.fetchone()
|
||||
con.close()
|
||||
return {"id": row[0], "updated_at": str(row[1])}, None
|
||||
|
||||
|
||||
def do_data_list(collection, limit=100, tag=None):
|
||||
_ensure_doc_table()
|
||||
con = db()
|
||||
cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
if tag:
|
||||
cur.execute("""select id, key, payload, tags, updated_at from data_docs
|
||||
where collection=%s and %s = any(tags)
|
||||
order by updated_at desc limit %s""", (collection, tag, limit))
|
||||
else:
|
||||
cur.execute("""select id, key, payload, tags, updated_at from data_docs
|
||||
where collection=%s order by updated_at desc limit %s""",
|
||||
(collection, limit))
|
||||
items = [dict(r) for r in cur.fetchall()]
|
||||
con.close()
|
||||
return {"collection": collection, "count": len(items), "items": items}, None
|
||||
|
||||
|
||||
def _jsonable(obj):
|
||||
if isinstance(obj, dict):
|
||||
return {k: _jsonable(v) for k, v in obj.items()}
|
||||
if isinstance(obj, list):
|
||||
return [_jsonable(v) for v in obj]
|
||||
return str(obj) if hasattr(obj, "isoformat") else obj
|
||||
|
||||
|
||||
def do_export(collection, fmt="json", filename=None, limit=500):
|
||||
"""Выгрузить коллекцию в папку проекта."""
|
||||
data, err = do_data_list(collection, limit=limit)
|
||||
if err:
|
||||
return None, err
|
||||
items = _jsonable(data["items"])
|
||||
|
||||
folder = os.path.join(DATA_DIR, collection)
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
stamp = datetime.now().strftime("%Y-%m-%d")
|
||||
if fmt == "md":
|
||||
name = filename or f"{collection}-{stamp}.md"
|
||||
lines = [f"# {collection}", "", f"записей: {len(items)}", ""]
|
||||
for it in items:
|
||||
lines.append(f"## {it.get('key')}")
|
||||
lines.append(f"обновлено: {it.get('updated_at')}")
|
||||
payload = it.get("payload") or {}
|
||||
for k, v in payload.items():
|
||||
lines.append(f"* **{k}**: {v}")
|
||||
lines.append("")
|
||||
open(os.path.join(folder, name), "w", encoding="utf-8").write("\n".join(lines))
|
||||
else:
|
||||
name = filename or f"{collection}-{stamp}.json"
|
||||
with open(os.path.join(folder, name), "w", encoding="utf-8") as f:
|
||||
json.dump({"collection": collection, "exported_at": str(datetime.now()),
|
||||
"count": len(items), "items": items},
|
||||
f, ensure_ascii=False, indent=1, default=str)
|
||||
|
||||
path = os.path.join(folder, name)
|
||||
return {"path": path, "count": len(items), "format": fmt}, None
|
||||
|
||||
|
||||
def render_panel():
|
||||
"""HTML-страница: состояние системы в одном месте."""
|
||||
try:
|
||||
@@ -278,6 +381,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if self.path.startswith("/data/"):
|
||||
import urllib.parse as up
|
||||
parts = self.path.split("?")[0].split("/data/")
|
||||
coll = parts[1] if len(parts) > 1 else ""
|
||||
qs = up.parse_qs(self.path.split("?")[1]) if "?" in self.path else {}
|
||||
tag = (qs.get("tag") or [None])[0]
|
||||
limit = int((qs.get("limit") or ["100"])[0])
|
||||
try:
|
||||
res, err = do_data_list(coll, limit, tag)
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
return self._json(200 if not err else 500, res or {"error": err})
|
||||
if self.path.startswith("/health"):
|
||||
try:
|
||||
with db() as con, con.cursor() as cur:
|
||||
@@ -348,6 +463,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self._entity(data)
|
||||
if self.path.startswith("/link"):
|
||||
return self._link(data)
|
||||
if self.path.startswith("/data/"):
|
||||
coll = self.path.split("/data/")[1].split("?")[0]
|
||||
if not coll:
|
||||
return self._json(400, {"error": "нужна коллекция"})
|
||||
res, err = do_data_put(coll, data)
|
||||
return self._json(201 if not err else 500, res or {"error": err})
|
||||
if self.path.startswith("/export"):
|
||||
coll = data.get("collection") or ""
|
||||
if not coll:
|
||||
return self._json(400, {"error": "нужна collection"})
|
||||
res, err = do_export(coll, data.get("format") or "json", data.get("filename"))
|
||||
return self._json(200 if not err else 500, res or {"error": err})
|
||||
return self._json(404, {"error": "нет такого пути"})
|
||||
|
||||
# ── события ──
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# Выгрузка данных ботов в папку проекта
|
||||
set -uo pipefail
|
||||
CORE=http://127.0.0.1:9120
|
||||
for c in wishes dialog events; do
|
||||
curl -s --max-time 20 -X POST -H 'Content-Type: application/json' \
|
||||
-d "{\"collection\":\"$c\",\"format\":\"md\"}" "$CORE/export" >/dev/null 2>&1
|
||||
done
|
||||
# копируем журнал диалогов и входящие
|
||||
mkdir -p /root/buryan-infra/data/logs
|
||||
cp /var/lib/hub-bots/dialog.jsonl /root/buryan-infra/data/logs/ 2>/dev/null
|
||||
cp /var/lib/hub-bots/inbox/*.jsonl /root/buryan-infra/data/logs/ 2>/dev/null
|
||||
echo "$(date '+%F %T') выгрузка готова"
|
||||
Reference in new issue
Block a user