docs: document VK bot workflow helpers
This commit is contained in:
1 parent
a1dee5ae57
commit
808fe8268b
1 file changed
+19
-1
+19
-1
@@ -177,6 +177,7 @@ def _normalise_natural_text(text: str) -> str:
|
|||||||
text = re.sub(r"(?i)\b(?:id|айди|№)\s*(?=\d)", "", text)
|
text = re.sub(r"(?i)\b(?:id|айди|№)\s*(?=\d)", "", text)
|
||||||
text = _SPACED_ID_RE.sub(lambda match: match.group(1).replace(" ", ""), text)
|
text = _SPACED_ID_RE.sub(lambda match: match.group(1).replace(" ", ""), text)
|
||||||
def normalise_written_date(match: re.Match[str]) -> str:
|
def normalise_written_date(match: re.Match[str]) -> str:
|
||||||
|
"""Приводит словесную дату из свободного текста к формату ДД.ММ."""
|
||||||
return f"{int(match.group('day'))}.{_RUSSIAN_MONTHS[match.group('month').casefold()]:02d}"
|
return f"{int(match.group('day'))}.{_RUSSIAN_MONTHS[match.group('month').casefold()]:02d}"
|
||||||
|
|
||||||
text = re.sub(
|
text = re.sub(
|
||||||
@@ -191,6 +192,7 @@ def _normalise_natural_text(text: str) -> str:
|
|||||||
date_match = re.search(r"\b(?:[12]?\d|3[01])\.(?:0?\d|1[0-2])\b", text)
|
date_match = re.search(r"\b(?:[12]?\d|3[01])\.(?:0?\d|1[0-2])\b", text)
|
||||||
|
|
||||||
def normalise_dotted_time(match: re.Match[str]) -> str:
|
def normalise_dotted_time(match: re.Match[str]) -> str:
|
||||||
|
"""Дополняет часы и минуты в точечном времени до HH:MM."""
|
||||||
if date_match is not None and match.start() == date_match.start():
|
if date_match is not None and match.start() == date_match.start():
|
||||||
return match.group(0)
|
return match.group(0)
|
||||||
return f"{match.group(1)}:{match.group(2)}"
|
return f"{match.group(1)}:{match.group(2)}"
|
||||||
@@ -200,6 +202,7 @@ def _normalise_natural_text(text: str) -> str:
|
|||||||
text = re.sub(r"(?<![\d.])([01]?\d|2[0-3])\s*-\s*([0-5]\d)\b", r"\1:\2", text)
|
text = re.sub(r"(?<![\d.])([01]?\d|2[0-3])\s*-\s*([0-5]\d)\b", r"\1:\2", text)
|
||||||
|
|
||||||
def correct_role(match: re.Match[str]) -> str:
|
def correct_role(match: re.Match[str]) -> str:
|
||||||
|
"""Исправляет распространённую опечатку в названии роли сопровождающего."""
|
||||||
word = match.group(0)
|
word = match.group(0)
|
||||||
candidate = max(_ROLE_TYPO_WORDS, key=lambda role: SequenceMatcher(None, word.casefold(), role).ratio())
|
candidate = max(_ROLE_TYPO_WORDS, key=lambda role: SequenceMatcher(None, word.casefold(), role).ratio())
|
||||||
return candidate if SequenceMatcher(None, word.casefold(), candidate).ratio() >= 0.84 else word
|
return candidate if SequenceMatcher(None, word.casefold(), candidate).ratio() >= 0.84 else word
|
||||||
@@ -251,6 +254,7 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
|
|||||||
|
|
||||||
|
|
||||||
def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
|
def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
|
||||||
|
"""Проверяет совместимость статусов самостоятельности с выбранным навыком."""
|
||||||
statuses = (primary,) + tuple(independence for _, _, independence in extras)
|
statuses = (primary,) + tuple(independence for _, _, independence in extras)
|
||||||
if len(statuses) > MAX_COACHING_KITTENS:
|
if len(statuses) > MAX_COACHING_KITTENS:
|
||||||
raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят")
|
raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят")
|
||||||
@@ -580,6 +584,7 @@ class VkApiClient:
|
|||||||
"""Клиент для работы с VK API."""
|
"""Клиент для работы с VK API."""
|
||||||
|
|
||||||
def __init__(self, access_token: str, api_version: str = "5.199") -> None:
|
def __init__(self, access_token: str, api_version: str = "5.199") -> None:
|
||||||
|
"""Сохраняет реквизиты VK API-клиента для последующих вызовов."""
|
||||||
"""
|
"""
|
||||||
Инициализация клиента.
|
Инициализация клиента.
|
||||||
|
|
||||||
@@ -630,18 +635,22 @@ class ApplicationDialog:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, identities: IdentityDirectory, store: ApplicationStore) -> None:
|
def __init__(self, identities: IdentityDirectory, store: ApplicationStore) -> None:
|
||||||
|
"""Создаёт интерактивный обработчик заявок с каталогом персонажей и БД."""
|
||||||
self.identities, self.store = identities, store
|
self.identities, self.store = identities, store
|
||||||
self.states: dict[int, dict[str, Any]] = {}
|
self.states: dict[int, dict[str, Any]] = {}
|
||||||
|
|
||||||
def active(self, actor_id: int) -> bool:
|
def active(self, actor_id: int) -> bool:
|
||||||
|
"""Возвращает, есть ли у пользователя незавершённая интерактивная заявка."""
|
||||||
return actor_id in self.states
|
return actor_id in self.states
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def is_application_command(cls, text: str) -> bool:
|
def is_application_command(cls, text: str) -> bool:
|
||||||
|
"""Распознаёт команды запуска мастера заявок по префиксу текста."""
|
||||||
return text.strip().lower() in {"/заявка", "/заявки", *cls._commands}
|
return text.strip().lower() in {"/заявка", "/заявки", *cls._commands}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
|
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
|
||||||
|
"""Формирует описание callback-кнопки VK-клавиатуры."""
|
||||||
return {
|
return {
|
||||||
"action": {"type": "text", "label": label, "payload": json.dumps({"command": payload}, ensure_ascii=False)},
|
"action": {"type": "text", "label": label, "payload": json.dumps({"command": payload}, ensure_ascii=False)},
|
||||||
"color": color,
|
"color": color,
|
||||||
@@ -678,6 +687,7 @@ class ApplicationDialog:
|
|||||||
return {"one_time": False, "buttons": [[cancel]]}
|
return {"one_time": False, "buttons": [[cancel]]}
|
||||||
|
|
||||||
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
||||||
|
"""Добавляет вложения к ожидающей заявке указанного пользователя."""
|
||||||
if actor_id in self.states:
|
if actor_id in self.states:
|
||||||
target = self.states[actor_id].setdefault("attachments", [])
|
target = self.states[actor_id].setdefault("attachments", [])
|
||||||
target.extend(attachments)
|
target.extend(attachments)
|
||||||
@@ -685,6 +695,7 @@ class ApplicationDialog:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _menu() -> str:
|
def _menu() -> str:
|
||||||
|
"""Возвращает текст меню выбора типа заявки."""
|
||||||
return ("Какую заявку хотите подать?\n"
|
return ("Какую заявку хотите подать?\n"
|
||||||
"• /перо — пожертвовать перо отряду\n"
|
"• /перо — пожертвовать перо отряду\n"
|
||||||
"• /бельчонок — стать бельчонком\n"
|
"• /бельчонок — стать бельчонком\n"
|
||||||
@@ -692,6 +703,7 @@ class ApplicationDialog:
|
|||||||
"• /куратор — стать куратором")
|
"• /куратор — стать куратором")
|
||||||
|
|
||||||
def _start(self, actor_id: int, application_type: str) -> str:
|
def _start(self, actor_id: int, application_type: str) -> str:
|
||||||
|
"""Создаёт состояние мастера и возвращает первый вопрос пользователю."""
|
||||||
profile = self.identities.profile(actor_id=actor_id)
|
profile = self.identities.profile(actor_id=actor_id)
|
||||||
state: dict[str, Any] = {"type": application_type, "attachments": []}
|
state: dict[str, Any] = {"type": application_type, "attachments": []}
|
||||||
if profile:
|
if profile:
|
||||||
@@ -703,6 +715,7 @@ class ApplicationDialog:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _next(state: dict[str, Any]) -> str:
|
def _next(state: dict[str, Any]) -> str:
|
||||||
|
"""Определяет следующий незаполненный шаг мастера заявки."""
|
||||||
kind = state["type"]
|
kind = state["type"]
|
||||||
if kind == "feather_donation":
|
if kind == "feather_donation":
|
||||||
return "Перечислите перья через запятую: количество цвет — источник добычи.\nНапример: 2 синие — личные запасы, 1 чёрное — осмотр дупла."
|
return "Перечислите перья через запятую: количество цвет — источник добычи.\nНапример: 2 синие — личные запасы, 1 чёрное — осмотр дупла."
|
||||||
@@ -720,6 +733,7 @@ class ApplicationDialog:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_feathers(text: str) -> list[dict[str, Any]]:
|
def _parse_feathers(text: str) -> list[dict[str, Any]]:
|
||||||
|
"""Разбирает строку с ресурсами перьев в структурированный список."""
|
||||||
feathers = []
|
feathers = []
|
||||||
for part in text.split(","):
|
for part in text.split(","):
|
||||||
match = re.fullmatch(r"\s*(\d+)\s+(.+?)\s*[—-]\s*(.+?)\s*", part)
|
match = re.fullmatch(r"\s*(\d+)\s+(.+?)\s*[—-]\s*(.+?)\s*", part)
|
||||||
@@ -729,12 +743,14 @@ class ApplicationDialog:
|
|||||||
return feathers
|
return feathers
|
||||||
|
|
||||||
def _save(self, actor_id: int, peer_id: int, state: dict[str, Any]) -> str:
|
def _save(self, actor_id: int, peer_id: int, state: dict[str, Any]) -> str:
|
||||||
|
"""Валидирует состояние, сохраняет заявку и очищает сессию мастера."""
|
||||||
application = validate_application(state)
|
application = validate_application(state)
|
||||||
application_id = self.store.create(application=application, actor_id=actor_id, reply_peer_id=peer_id, source="vk")
|
application_id = self.store.create(application=application, actor_id=actor_id, reply_peer_id=peer_id, source="vk")
|
||||||
self.states.pop(actor_id, None)
|
self.states.pop(actor_id, None)
|
||||||
return f"Заявка №{application_id} отправлена на рассмотрение. Я напишу сюда, когда её примут."
|
return f"Заявка №{application_id} отправлена на рассмотрение. Я напишу сюда, когда её примут."
|
||||||
|
|
||||||
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
|
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
|
||||||
|
"""Обрабатывает очередной ввод пользователя и возвращает ответ мастера."""
|
||||||
command = text.strip().lower()
|
command = text.strip().lower()
|
||||||
if command in ("/заявка", "/заявки"):
|
if command in ("/заявка", "/заявки"):
|
||||||
self.states[actor_id] = {"application_menu": True}
|
self.states[actor_id] = {"application_menu": True}
|
||||||
@@ -892,7 +908,8 @@ class BelkiBot:
|
|||||||
|
|
||||||
def run_forever(self) -> None:
|
def run_forever(self) -> None:
|
||||||
"""Бесконечный цикл обработки событий."""
|
"""Бесконечный цикл обработки событий."""
|
||||||
def notification_loop() -> None:
|
def notification_loop() -> None:
|
||||||
|
"""Периодически отправляет уведомления о принятых заявках."""
|
||||||
while True:
|
while True:
|
||||||
self.notify_accepted_applications()
|
self.notify_accepted_applications()
|
||||||
self.application_exporter.sync_pending()
|
self.application_exporter.sync_pending()
|
||||||
@@ -1565,6 +1582,7 @@ class BelkiDialog:
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
"""Запускает VK-бота, настроив API-клиент, хранилища и цикл событий."""
|
||||||
token = os.environ["VK_GROUP_TOKEN"]
|
token = os.environ["VK_GROUP_TOKEN"]
|
||||||
group_id = int(os.environ["VK_GROUP_ID"])
|
group_id = int(os.environ["VK_GROUP_ID"])
|
||||||
version = os.getenv("VK_API_VERSION", "5.199")
|
version = os.getenv("VK_API_VERSION", "5.199")
|
||||||
|
|||||||
Reference in new issue
Block a user