feat: migrate VK bot to Callback API
This commit is contained in:
1 parent
2794546974
commit
a04498d634
10 files changed
+438
-58
No files matched your search
@@ -86,6 +86,9 @@ class VkConversationStore:
|
||||
"""CREATE TABLE IF NOT EXISTS vk_dialog_states (
|
||||
actor_id BIGINT PRIMARY KEY, state_json TEXT NOT NULL, pending_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""",
|
||||
"""CREATE TABLE IF NOT EXISTS vk_callback_events (
|
||||
event_id TEXT PRIMARY KEY, event_type TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""",
|
||||
]
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
@@ -164,6 +167,41 @@ class VkConversationStore:
|
||||
"""Remove a completed or cancelled dialog from durable storage."""
|
||||
self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),))
|
||||
|
||||
def claim_callback_event(self, event_id: str, event_type: str) -> bool:
|
||||
"""Claim a callback event once, preventing duplicate VK deliveries."""
|
||||
if not event_id.strip():
|
||||
return True
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
self._execute(
|
||||
"INSERT INTO vk_callback_events(event_id,event_type,received_at) VALUES(?,?,?)",
|
||||
(event_id[:255], event_type[:100], now.isoformat()),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
# A unique-key collision is a duplicate; an unavailable database
|
||||
# must propagate so VK retries the callback instead of losing it.
|
||||
rows = self._execute(
|
||||
"SELECT event_id FROM vk_callback_events WHERE event_id=?",
|
||||
(event_id[:255],), fetch=True,
|
||||
) or []
|
||||
if rows:
|
||||
return False
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
self._execute(
|
||||
"DELETE FROM vk_callback_events WHERE received_at<?",
|
||||
((now - timedelta(days=7)).isoformat(),),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def release_callback_event(self, event_id: str) -> None:
|
||||
"""Release a failed callback claim so VK can retry the event."""
|
||||
if event_id.strip():
|
||||
self._execute("DELETE FROM vk_callback_events WHERE event_id=?", (event_id[:255],))
|
||||
|
||||
def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int:
|
||||
if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов")
|
||||
rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True)
|
||||
|
||||
Reference in new issue
Block a user