Added apps

This commit is contained in:
nyan404 committed 2026-08-21 13:18:34 +03:00
1 parent 540c393258
commit cfeee5a814
11 files changed
+548 -12

No files matched your search

+145 -4
View File
@@ -4,6 +4,8 @@ import json
import os
import random
import re
import threading
import time
from datetime import datetime
from typing import Any, Iterator
from urllib.parse import urlencode
@@ -13,6 +15,7 @@ from .api import ApiError, calculate_payload
from .history import CalculationStore
from .image_host import ImageHostClient
from .identity import Identity, IdentityDirectory
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
"""
Обработка VK-бота:
@@ -425,18 +428,133 @@ class VkApiClient:
))
class ApplicationDialog:
"""Небольшой пошаговый опросник для заявок, не смешанный с расчётами."""
_commands = {
"/перо": "feather_donation", "/пожертвовать": "feather_donation",
"/бельчонок": "kitten", "/бельчата": "kitten",
"/летяга": "flying_squirrel", "/белка-летяга": "flying_squirrel",
"/куратор": "curator",
}
def __init__(self, identities: IdentityDirectory, store: ApplicationStore) -> None:
self.identities, self.store = identities, store
self.states: dict[int, dict[str, Any]] = {}
def active(self, actor_id: int) -> bool:
return actor_id in self.states
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", [])
target.extend(attachments)
del target[:-10]
@staticmethod
def _menu() -> str:
return ("Какую заявку хотите подать?\n"
"• /перо — пожертвовать перо отряду\n"
"• /бельчонок — стать бельчонком\n"
"• /летяга — стать белкой-летягой\n"
"• /куратор — стать куратором")
def _start(self, actor_id: int, application_type: str) -> str:
profile = self.identities.profile(actor_id=actor_id)
state: dict[str, Any] = {"type": application_type, "attachments": []}
if profile:
state.update(name=profile.name, character_id=profile.character_id)
self.states[actor_id] = state
if not profile:
return "Укажите имя и ID персонажа: Имя [12345]."
return self._next(state)
@staticmethod
def _next(state: dict[str, Any]) -> str:
kind = state["type"]
if kind == "feather_donation":
return "Перечислите перья через запятую: количество цвет — источник добычи.\nНапример: 2 синие — личные запасы, 1 чёрное — осмотр дупла."
if kind == "kitten":
return "Пришлите скриншот активности. Когда закончите, напишите «готово»."
if kind == "curator":
return "Пришлите скриншот ЛУ с дробью. Когда закончите, напишите «готово»."
if "vk_link" not in state:
return "Пришлите ссылку на страницу VK или напишите «нет»."
if "practiced_before" not in state:
return "Сдавали практику ранее? Ответьте «да» или «нет»."
if state["practiced_before"] and "practice_review_link" not in state:
return "Пришлите ссылку на комментарий ответственного/куратора с прошлой практики."
return ""
@staticmethod
def _parse_feathers(text: str) -> list[dict[str, Any]]:
feathers = []
for part in text.split(","):
match = re.fullmatch(r"\s*(\d+)\s+(.+?)\s*[—-]\s*(.+?)\s*", part)
if not match:
raise ApplicationError("Не смог разобрать перья. Используйте: 2 синие — личные запасы")
feathers.append({"amount": int(match.group(1)), "color": match.group(2), "source": match.group(3)})
return feathers
def _save(self, actor_id: int, peer_id: int, state: dict[str, Any]) -> str:
application = validate_application(state)
application_id = self.store.create(application=application, actor_id=actor_id, reply_peer_id=peer_id, source="vk")
self.states.pop(actor_id, None)
return f"Заявка №{application_id} отправлена на рассмотрение. Я напишу сюда, когда её примут."
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
command = text.strip().lower()
if command in ("/заявка", "/заявки"):
return self._menu()
if command in self._commands:
return self._start(actor_id, self._commands[command])
state = self.states.get(actor_id)
if state is None:
return None
if command in ("/отмена", "отмена"):
self.states.pop(actor_id, None)
return "Заявка отменена."
try:
if "name" not in state:
state["name"], state["character_id"] = _person(text)
self.identities.remember_profile(actor_id=actor_id, name=state["name"], character_id=state["character_id"])
return self._next(state)
if state["type"] == "feather_donation":
state["feathers"] = self._parse_feathers(text)
return self._save(actor_id, peer_id, state)
if state["type"] in ("kitten", "curator"):
if command != "готово":
return "Пришлите скриншот, затем напишите «готово»."
return self._save(actor_id, peer_id, state)
if "vk_link" not in state:
state["vk_link"] = "" if command in ("нет", "неа", "-") else text.strip()
return self._next(state)
if "practiced_before" not in state:
if command not in ("да", "нет"):
return "Ответьте «да» или «нет»."
state["practiced_before"] = command == "да"
return self._next(state) if state["practiced_before"] else self._save(actor_id, peer_id, state)
state["practice_review_link"] = text.strip()
return self._save(actor_id, peer_id, state)
except ApplicationError as exc:
return str(exc)
class BelkiBot:
"""Основной класс бота, обрабатывающий события VK."""
def __init__(self, client: VkApiClient, group_id: int) -> None:
"""Инициализация бота с клиентом VK и ID группы."""
self.client = client
self.group_id = group_id
identities = IdentityDirectory.from_environment(persistent=True)
self.dialog = BelkiDialog(
IdentityDirectory.from_environment(persistent=True),
identities,
onboarding=True,
calculation_store=CalculationStore.from_environment(),
attachment_mirror=ImageHostClient().mirror,
)
self.application_store = ApplicationStore.from_environment()
self.application_dialog = ApplicationDialog(identities, self.application_store)
def response_for_text(self, text: str) -> str:
"""Обработка текстового сообщения и возврат ответа."""
@@ -465,9 +583,26 @@ class BelkiBot:
photos = extract_photo_attachments(message)
if photos:
self.dialog.queue_attachments(sender, photos)
self.application_dialog.queue_attachments(sender, photos)
if text:
response = self.dialog.handle(int(peer_id), text, user_id=sender)
self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(sender))
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
self.client.send(int(peer_id), response, keyboard=keyboard)
def notify_accepted_applications(self) -> None:
"""Отправляет пользователям принятые админом заявки и отмечает доставку."""
for item in self.application_store.pending_notifications():
application = item["application"]
label = APPLICATION_TYPES.get(application.get("type"), "Заявка")
try:
self.client.send(int(item["reply_peer_id"]), f"Ваша заявка «{label}» принята. Спасибо!")
except (VkError, OSError):
continue
self.application_store.mark_notified(int(item["id"]))
@staticmethod
def _button_text(message: dict[str, Any]) -> str | None:
@@ -483,7 +618,7 @@ class BelkiBot:
value = payload.get("command") if isinstance(payload, dict) else payload
return {
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена",
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
"place:hollow": "дупло", "place:crevice": "расщелина",
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
@@ -515,6 +650,11 @@ class BelkiBot:
def run_forever(self) -> None:
"""Бесконечный цикл обработки событий."""
def notification_loop() -> None:
while True:
self.notify_accepted_applications()
time.sleep(15)
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
for event in self.events():
self.handle_event(event)
@@ -677,6 +817,7 @@ class BelkiDialog:
"buttons": [
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
[self._button("Подать заявку", "menu:application", "secondary")],
[self._button("Помощь", "menu:help", "secondary")],
],
}