fix: keep VK bot alive across long poll failures
This commit is contained in:
1 parent
e33de2114a
commit
2d9aa2126c
8 files changed
+157
-15
No files matched your search
@@ -83,6 +83,9 @@ class VkConversationStore:
|
||||
id INTEGER PRIMARY KEY, schedule_id INTEGER NOT NULL, planned_for TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending', attempted_at TEXT, attempts INTEGER NOT NULL DEFAULT 0,
|
||||
vk_result TEXT, error TEXT, UNIQUE(schedule_id, planned_for))""",
|
||||
"""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)""",
|
||||
]
|
||||
if self._postgres:
|
||||
with self._psycopg.connect(self.database_url) as conn:
|
||||
@@ -128,6 +131,39 @@ class VkConversationStore:
|
||||
keys = ("peer_id", "chat_id", "title", "status", "mailing_enabled", "added_at", "invited_by", "removed_at", "removal_reason", "last_success_at", "last_error")
|
||||
return dict(zip(keys, row))
|
||||
|
||||
def load_dialog_state(self, actor_id: int) -> tuple[dict | None, list[dict]]:
|
||||
"""Load an unfinished private dialog and photos queued before its next text event."""
|
||||
rows = self._execute(
|
||||
"SELECT state_json,pending_json FROM vk_dialog_states WHERE actor_id=?",
|
||||
(int(actor_id),), fetch=True,
|
||||
) or []
|
||||
if not rows:
|
||||
return None, []
|
||||
try:
|
||||
state = json.loads(rows[0][0]) if rows[0][0] else None
|
||||
pending = json.loads(rows[0][1]) if rows[0][1] else []
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
return None, []
|
||||
return (state if isinstance(state, dict) else None,
|
||||
pending if isinstance(pending, list) else [])
|
||||
|
||||
def save_dialog_state(self, actor_id: int, state: dict | None, pending: list[dict]) -> None:
|
||||
"""Atomically persist the current dialog state and queued photos."""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
state_json = json.dumps(state, ensure_ascii=False) if state is not None else ""
|
||||
pending_json = json.dumps(pending, ensure_ascii=False)
|
||||
self._execute(
|
||||
"""INSERT INTO vk_dialog_states(actor_id,state_json,pending_json,updated_at)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(actor_id) DO UPDATE SET state_json=excluded.state_json,
|
||||
pending_json=excluded.pending_json, updated_at=excluded.updated_at""",
|
||||
(int(actor_id), state_json, pending_json, now),
|
||||
)
|
||||
|
||||
def delete_dialog_state(self, actor_id: int) -> None:
|
||||
"""Remove a completed or cancelled dialog from durable storage."""
|
||||
self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),))
|
||||
|
||||
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