feat: add context-aware VK keyboards

This commit is contained in:
nyan404 committed 2026-08-16 15:21:55 +03:00
1 parent 4dab6e8624
commit dfc5e2826a
6 files changed
+91 -8

No files matched your search

+66 -7
View File
@@ -233,14 +233,17 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
def build_message_request(peer_id: int, message: str, access_token: str, api_version: str,
random_id: int | None = None) -> dict[str, Any]:
return {
random_id: int | None = None, keyboard: dict[str, Any] | None = None) -> dict[str, Any]:
request = {
"peer_id": peer_id,
"message": message,
"random_id": random_id if random_id is not None else random.randint(1, 2**31 - 1),
"access_token": access_token,
"v": api_version,
}
if keyboard is not None:
request["keyboard"] = json.dumps(keyboard, ensure_ascii=False)
return request
class VkApiClient:
@@ -261,9 +264,11 @@ class VkApiClient:
raise VkError(payload["error"].get("error_msg", "VK API error"))
return payload.get("response", {})
def send(self, peer_id: int, message: str) -> dict[str, Any]:
return self.call("messages.send", {"peer_id": peer_id, "message": message,
"random_id": random.randint(1, 2**31 - 1)})
def send(self, peer_id: int, message: str, keyboard: dict[str, Any] | None = None) -> dict[str, Any]:
return self.call("messages.send", build_message_request(
peer_id, message, self.access_token, self.api_version,
random_id=random.randint(1, 2**31 - 1), keyboard=keyboard,
))
class BelkiBot:
@@ -291,9 +296,29 @@ class BelkiBot:
message = event.get("object", {}).get("message", event.get("object", {}))
peer_id = message.get("peer_id")
sender_id = message.get("from_id", message.get("sender_id", peer_id))
text = message.get("text", "")
text = self._button_text(message) or message.get("text", "")
if peer_id is not None and text:
self.client.send(int(peer_id), self.dialog.handle(int(peer_id), text, user_id=int(sender_id)))
sender = int(sender_id or peer_id)
response = self.dialog.handle(int(peer_id), text, user_id=sender)
self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(sender))
@staticmethod
def _button_text(message: dict[str, Any]) -> str | None:
payload = message.get("payload")
if not payload:
return None
if isinstance(payload, str):
try:
payload = json.loads(payload)
except json.JSONDecodeError:
pass
value = payload.get("command") if isinstance(payload, dict) else payload
return {
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена",
"confirm:yes": "да", "confirm:no": "нет",
"independence:self": "сам", "independence:nonself": "несам",
}.get(str(value))
def events(self) -> Iterator[dict[str, Any]]:
poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id})
@@ -351,6 +376,40 @@ class BelkiDialog:
def _reset(self, peer_id: int) -> None:
self._states.pop(peer_id, None)
@staticmethod
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
return {"action": {"type": "text", "label": label, "payload": payload}, "color": color}
def keyboard_for(self, actor_id: int) -> dict[str, Any]:
"""Return a context-aware VK keyboard for the author's current dialog state."""
state = self._states.get(actor_id)
if state and state.get("onboarding"):
return {"one_time": True, "buttons": [[self._button("Отмена", "menu:cancel", "negative")]]}
if state and state.get("confirm"):
return {
"one_time": True,
"buttons": [[self._button("Да", "confirm:yes", "positive"), self._button("Нет", "confirm:no", "negative")]],
}
if state and state.get("mode") == "coaching":
next_key = next((key for key, _ in self._ORDERS["coaching"] if not self._has_field(state, key)), None)
if next_key == "independence":
return {
"one_time": False,
"buttons": [[self._button("Сам", "independence:self", "positive"), self._button("Несам", "independence:nonself", "secondary")],
[self._button("Отмена", "menu:cancel", "negative")]],
}
return {"one_time": False, "buttons": [[self._button("Отмена", "menu:cancel", "negative")]]}
if state:
return {"one_time": False, "buttons": [[self._button("Отмена", "menu:cancel", "negative")]]}
return {
"one_time": False,
"buttons": [
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
[self._button("Помощь", "menu:help", "secondary")],
],
}
@staticmethod
def _independence(value: str) -> str | None:
normalized = re.sub(r"[^а-яё]", "", value.lower().replace("ё", "е"))