"""Клиент 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")