feat(applications): add keyboard flow and export outbox

This commit is contained in:
nyan404 committed 2026-08-21 13:25:33 +03:00
1 parent cfeee5a814
commit 27bcc291db
11 files changed
+255 -10

No files matched your search

+76 -5
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import os
import sqlite3
import time
from pathlib import Path
from typing import Any
@@ -110,6 +109,12 @@ class ApplicationStore:
connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT")
except sqlite3.OperationalError:
pass
connection.execute("""CREATE TABLE IF NOT EXISTS application_export_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, application_id INTEGER NOT NULL,
event_type TEXT NOT NULL, payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, delivered_at TEXT, last_error TEXT
)""")
def _ensure_postgres_schema(self) -> None:
with self._psycopg.connect(self.database_url) as connection:
@@ -119,6 +124,12 @@ class ApplicationStore:
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ
)""")
connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ")
connection.execute("""CREATE TABLE IF NOT EXISTS belki_application_export_events (
id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL,
event_type TEXT NOT NULL, payload_json JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), delivered_at TIMESTAMPTZ, last_error TEXT
)""")
def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int:
if self.database_url.startswith(("postgres://", "postgresql://")):
@@ -127,12 +138,20 @@ class ApplicationStore:
row = connection.execute("""INSERT INTO belki_applications
(actor_id, reply_peer_id, source, application_json) VALUES (%s, %s, %s, %s) RETURNING id""",
(actor_id, reply_peer_id, source, Jsonb(application))).fetchone()
return int(row[0])
application_id = int(row[0])
self.enqueue_export(application_id, "application_created", {
"id": application_id, "source": source, "status": "pending", "application": application,
})
return application_id
with sqlite3.connect(self.sqlite_path) as connection:
cursor = connection.execute("""INSERT INTO applications
(actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""",
(actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False)))
return int(cursor.lastrowid)
application_id = int(cursor.lastrowid)
self.enqueue_export(application_id, "application_created", {
"id": application_id, "source": source, "status": "pending", "application": application,
})
return application_id
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]:
if status not in (None, "pending", "accepted"):
@@ -172,11 +191,63 @@ class ApplicationStore:
cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,))
if not cursor.rowcount:
return None
return next((item for item in self.list(limit=500) if item["id"] == application_id), None)
application = next((item for item in self.list(limit=500) if item["id"] == application_id), None)
if application:
self.enqueue_export(application_id, "application_accepted", application)
return application
if row is None:
return None
return {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3],
application = {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3],
"application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()}
self.enqueue_export(application_id, "application_accepted", application)
return application
def enqueue_export(self, application_id: int, event_type: str, snapshot: dict[str, Any]) -> int:
"""Сохраняет событие для будущего экспорта до любого сетевого вызова."""
payload = {"schema_version": 1, "event_type": event_type, "application": snapshot}
if self.database_url.startswith(("postgres://", "postgresql://")):
from psycopg.types.json import Jsonb
with self._psycopg.connect(self.database_url) as connection:
row = connection.execute("""INSERT INTO belki_application_export_events
(application_id, event_type, payload_json) VALUES (%s, %s, %s) RETURNING id""",
(application_id, event_type, Jsonb(payload))).fetchone()
return int(row[0])
with sqlite3.connect(self.sqlite_path) as connection:
cursor = connection.execute("""INSERT INTO application_export_events
(application_id, event_type, payload_json) VALUES (?, ?, ?)""",
(application_id, event_type, json.dumps(payload, ensure_ascii=False)))
return int(cursor.lastrowid)
def pending_exports(self, *, limit: int = 100) -> list[dict[str, Any]]:
"""Возвращает недоставленные события в порядке их создания."""
limit = max(1, min(int(limit), 500))
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts
FROM belki_application_export_events WHERE status = 'pending' ORDER BY id LIMIT %s""", (limit,)).fetchall()
else:
with sqlite3.connect(self.sqlite_path) as connection:
rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts
FROM application_export_events WHERE status = 'pending' ORDER BY id LIMIT ?""", (limit,)).fetchall()
return [{"id": row[0], "application_id": row[1], "event_type": row[2],
"payload": row[3] if isinstance(row[3], dict) else json.loads(row[3]), "attempts": row[4]} for row in rows]
def mark_exported(self, event_id: int) -> None:
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
connection.execute("UPDATE belki_application_export_events SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1, last_error = NULL WHERE id = %s", (event_id,))
else:
with sqlite3.connect(self.sqlite_path) as connection:
connection.execute("UPDATE application_export_events SET status = 'delivered', delivered_at = CURRENT_TIMESTAMP, attempts = attempts + 1, last_error = NULL WHERE id = ?", (event_id,))
def record_export_failure(self, event_id: int, message: str) -> None:
message = message[:1000]
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
connection.execute("UPDATE belki_application_export_events SET attempts = attempts + 1, last_error = %s WHERE id = %s", (message, event_id))
else:
with sqlite3.connect(self.sqlite_path) as connection:
connection.execute("UPDATE application_export_events SET attempts = attempts + 1, last_error = ? WHERE id = ?", (message, event_id))
def pending_notifications(self) -> list[dict[str, Any]]:
"""Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление."""
+62
View File
@@ -0,0 +1,62 @@
"""Выключенный по умолчанию экспорт заявок в Google Sheets через Apps Script."""
from __future__ import annotations
import json
import os
from dataclasses import dataclass
from urllib.error import URLError
from urllib.request import Request, urlopen
from .applications import ApplicationStore
@dataclass(frozen=True)
class GoogleSheetsExportConfig:
"""Настройки webhook-а Apps Script; отсутствие любой обязательной выключает экспорт."""
enabled: bool
url: str
token: str
@classmethod
def from_environment(cls) -> "GoogleSheetsExportConfig":
return cls(
enabled=os.getenv("BELKI_GOOGLE_EXPORT_ENABLED", "0") == "1",
url=os.getenv("BELKI_GOOGLE_EXPORT_URL", "").strip(),
token=os.getenv("BELKI_GOOGLE_EXPORT_TOKEN", "").strip(),
)
@property
def ready(self) -> bool:
return self.enabled and bool(self.url)
class GoogleSheetsExportService:
"""Доставляет outbox-события; при выключенной интеграции ничего не делает."""
def __init__(self, store: ApplicationStore, config: GoogleSheetsExportConfig | None = None) -> None:
self.store = store
self.config = config or GoogleSheetsExportConfig.from_environment()
def sync_pending(self, *, limit: int = 100) -> int:
"""Пытается доставить события по порядку и возвращает число успешных отправок."""
if not self.config.ready:
return 0
delivered = 0
for event in self.store.pending_exports(limit=limit):
body = json.dumps(event["payload"], ensure_ascii=False).encode("utf-8")
headers = {"Content-Type": "application/json; charset=utf-8"}
if self.config.token:
headers["Authorization"] = f"Bearer {self.config.token}"
request = Request(self.config.url, data=body, headers=headers, method="POST")
try:
with urlopen(request, timeout=15) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Google export returned HTTP {response.status}")
except (OSError, URLError, RuntimeError, ValueError) as exc:
self.store.record_export_failure(event["id"], str(exc))
break
self.store.mark_exported(event["id"])
delivered += 1
return delivered
+56 -3
View File
@@ -16,6 +16,7 @@ from .history import CalculationStore
from .image_host import ImageHostClient
from .identity import Identity, IdentityDirectory
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
from .google_sheets_export import GoogleSheetsExportService
"""
Обработка VK-бота:
@@ -445,6 +446,47 @@ class ApplicationDialog:
def active(self, actor_id: int) -> bool:
return actor_id in self.states
@classmethod
def is_application_command(cls, text: str) -> bool:
return text.strip().lower() in {"/заявка", "/заявки", *cls._commands}
@staticmethod
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
return {
"action": {"type": "text", "label": label, "payload": json.dumps({"command": payload}, ensure_ascii=False)},
"color": color,
}
def keyboard_for(self, actor_id: int) -> dict[str, Any] | None:
"""Контекстная VK-клавиатура для всех выбираемых шагов заявки."""
state = self.states.get(actor_id)
if not state:
return None
cancel = self._button("Отмена", "menu:cancel", "negative")
if state.get("application_menu"):
return {"one_time": False, "buttons": [
[self._button("Пожертвовать перо", "application:feathers", "secondary")],
[self._button("Стать бельчонком", "application:kitten", "primary")],
[self._button("Стать летягой", "application:flying", "primary")],
[self._button("Стать куратором", "application:curator", "primary")],
[cancel],
]}
if "name" not in state:
return {"one_time": False, "buttons": [[cancel]]}
if state["type"] in ("kitten", "curator"):
return {"one_time": False, "buttons": [
[self._button("Готово", "application:done", "positive")], [cancel],
]}
if state["type"] == "flying_squirrel":
if "vk_link" not in state:
return {"one_time": False, "buttons": [[self._button("Нет ссылки VK", "application:skip-vk")], [cancel]]}
if "practiced_before" not in state:
return {"one_time": False, "buttons": [[
self._button("Да", "application:practice-yes", "positive"),
self._button("Нет", "application:practice-no", "negative"),
], [cancel]]}
return {"one_time": False, "buttons": [[cancel]]}
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
if actor_id in self.states:
target = self.states[actor_id].setdefault("attachments", [])
@@ -505,6 +547,7 @@ class ApplicationDialog:
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
command = text.strip().lower()
if command in ("/заявка", "/заявки"):
self.states[actor_id] = {"application_menu": True}
return self._menu()
if command in self._commands:
return self._start(actor_id, self._commands[command])
@@ -555,6 +598,7 @@ class BelkiBot:
)
self.application_store = ApplicationStore.from_environment()
self.application_dialog = ApplicationDialog(identities, self.application_store)
self.application_exporter = GoogleSheetsExportService(self.application_store)
def response_for_text(self, text: str) -> str:
"""Обработка текстового сообщения и возврат ответа."""
@@ -581,16 +625,20 @@ class BelkiBot:
if peer_id is not None:
sender = int(sender_id or peer_id)
photos = extract_photo_attachments(message)
if self.application_dialog.is_application_command(text):
self.dialog._reset(sender)
if photos:
self.dialog.queue_attachments(sender, photos)
self.application_dialog.queue_attachments(sender, photos)
if self.application_dialog.active(sender) or self.application_dialog.is_application_command(text):
self.application_dialog.queue_attachments(sender, photos)
else:
self.dialog.queue_attachments(sender, photos)
if text:
response = self.application_dialog.handle(sender, int(peer_id), text)
if response is None:
response = self.dialog.handle(int(peer_id), text, user_id=sender)
keyboard = self.dialog.keyboard_for(sender)
else:
keyboard = None
keyboard = self.application_dialog.keyboard_for(sender) or self.dialog.keyboard_for(sender)
self.client.send(int(peer_id), response, keyboard=keyboard)
def notify_accepted_applications(self) -> None:
@@ -619,6 +667,10 @@ class BelkiBot:
return {
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
"application:feathers": "/перо", "application:kitten": "/бельчонок",
"application:flying": "/летяга", "application:curator": "/куратор",
"application:skip-vk": "нет", "application:practice-yes": "да", "application:practice-no": "нет",
"application:done": "готово",
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
"place:hollow": "дупло", "place:crevice": "расщелина",
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
@@ -653,6 +705,7 @@ class BelkiBot:
def notification_loop() -> None:
while True:
self.notify_accepted_applications()
self.application_exporter.sync_pending()
time.sleep(15)
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
for event in self.events():