feat: require screenshots before report confirmation
This commit is contained in:
1 parent
f6c2275af3
commit
4183d99376
3 files changed
+52
-15
No files matched your search
@@ -29,7 +29,7 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Секреты не записываются в репозиторий. VK-команды перечислены в `/help`.
|
Секреты не записываются в репозиторий. VK-команды перечислены в `/help`.
|
||||||
|
|
||||||
Бот поддерживает два способа ввода. После каждого ответа он показывает VK-клавиатуру: главное меню содержит «Прокачка ЛУ», «Прокачка ЗУ», «Тренировка», «Осмотр» и «Помощь», а во время сценария появляются контекстные кнопки подтверждения, самостоятельности и отмены. Команды `/лу`, `/зу`, `/урок` и `/осмотр` остаются запасным способом запуска. Либо пришлите данные одной строкой без `|`, например `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140` или `урок Дикая Вишня 1604614 Серолап 1617140`: бот распознает заполненные поля и спросит недостающие. Полный формат команд с разделителями также поддерживается. Перед созданием отчёта бот показывает распознанные данные и ждёт подтверждения. Для персонажа в осмотре можно ввести только имя или только ID: сохранённая связка подставит вторую часть, а при её отсутствии бот попросит добавить недостающее значение. Незавершённый сценарий хранится отдельно для каждого VK `peer_id`; `/отмена` его сбрасывает.
|
Бот поддерживает два способа ввода. После каждого ответа он показывает VK-клавиатуру: главное меню содержит «Прокачка ЛУ», «Прокачка ЗУ», «Тренировка», «Осмотр» и «Помощь», а во время сценария появляются контекстные кнопки подтверждения, самостоятельности и отмены. Команды `/лу`, `/зу`, `/урок` и `/осмотр` остаются запасным способом запуска. Либо пришлите данные одной строкой без `|`, например `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140` или `урок Дикая Вишня 1604614 Серолап 1617140`: бот распознает заполненные поля и спросит недостающие. Полный формат команд с разделителями также поддерживается. Перед созданием отчёта бот просит прислать хотя бы один скриншот, затем показывает распознанные данные и ждёт подтверждения. Для персонажа в осмотре можно ввести только имя или только ID: сохранённая связка подставит вторую часть, а при её отсутствии бот попросит добавить недостающее значение. Незавершённый сценарий хранится отдельно для каждого VK `peer_id`; `/отмена` его сбрасывает.
|
||||||
|
|
||||||
При первом сообщении бот попросит представиться (`Имя [ID]`), запомнит профиль по автору VK и дальше будет приветствовать по имени. Профиль хранится в SQLite вместе со связками персонажей. Для самостоятельности принимаются полные формы и короткие ответы `сам`/`несам`.
|
При первом сообщении бот попросит представиться (`Имя [ID]`), запомнит профиль по автору VK и дальше будет приветствовать по имени. Профиль хранится в SQLite вместе со связками персонажей. Для самостоятельности принимаются полные формы и короткие ответы `сам`/`несам`.
|
||||||
|
|
||||||
|
|||||||
+21
-4
@@ -353,6 +353,7 @@ class BelkiBot:
|
|||||||
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
|
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
|
||||||
"place:hollow": "дупло", "place:crevice": "расщелина",
|
"place:hollow": "дупло", "place:crevice": "расщелина",
|
||||||
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
|
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
|
||||||
|
"attachments:done": "готово",
|
||||||
"confirm:yes": "да", "confirm:no": "нет",
|
"confirm:yes": "да", "confirm:no": "нет",
|
||||||
"independence:self": "сам", "independence:nonself": "несам",
|
"independence:self": "сам", "independence:nonself": "несам",
|
||||||
}.get(str(value))
|
}.get(str(value))
|
||||||
@@ -446,6 +447,11 @@ class BelkiDialog:
|
|||||||
state = self._states.get(actor_id)
|
state = self._states.get(actor_id)
|
||||||
if state and state.get("onboarding"):
|
if state and state.get("onboarding"):
|
||||||
return {"one_time": True, "buttons": [[self._button("Отмена", "menu:cancel", "negative")]]}
|
return {"one_time": True, "buttons": [[self._button("Отмена", "menu:cancel", "negative")]]}
|
||||||
|
if state and state.get("awaiting_attachments"):
|
||||||
|
return {"one_time": False, "buttons": [
|
||||||
|
[self._button("Готово", "attachments:done", "positive")],
|
||||||
|
[self._button("Отмена", "menu:cancel", "negative")],
|
||||||
|
]}
|
||||||
if state and state.get("confirm"):
|
if state and state.get("confirm"):
|
||||||
return {
|
return {
|
||||||
"one_time": True,
|
"one_time": True,
|
||||||
@@ -538,8 +544,11 @@ class BelkiDialog:
|
|||||||
if key == "character" and state.get("character_name"):
|
if key == "character" and state.get("character_name"):
|
||||||
return "Связка не найдена. Введите ID персонажа, чтобы добавить его к имени."
|
return "Связка не найдена. Введите ID персонажа, чтобы добавить его к имени."
|
||||||
return prompt
|
return prompt
|
||||||
state["confirm"] = True
|
state["awaiting_attachments"] = True
|
||||||
return self._confirmation(state)
|
return (
|
||||||
|
"Пришлите сюда скриншоты для этого отчёта. "
|
||||||
|
"После загрузки всех фотографий нажмите «Готово»."
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _has_field(state: dict[str, Any], key: str) -> bool:
|
def _has_field(state: dict[str, Any], key: str) -> bool:
|
||||||
@@ -608,8 +617,8 @@ class BelkiDialog:
|
|||||||
parsed["mode"] = "coaching"
|
parsed["mode"] = "coaching"
|
||||||
self._states[peer_id] = parsed
|
self._states[peer_id] = parsed
|
||||||
return "Данные распознаны, но не указан статус котёнка. Ответьте: самостоятельно или несамостоятельно."
|
return "Данные распознаны, но не указан статус котёнка. Ответьте: самостоятельно или несамостоятельно."
|
||||||
self._states[peer_id] = {**parsed, "confirm": True}
|
self._states[peer_id] = {**parsed, "awaiting_attachments": True}
|
||||||
return self._confirmation(self._states[peer_id])
|
return "Пришлите сюда скриншоты для этого отчёта. После загрузки всех фотографий нажмите «Готово»."
|
||||||
if command.lower() in ("/урок", "/тренировка"):
|
if command.lower() in ("/урок", "/тренировка"):
|
||||||
self._states[peer_id] = {"mode": "training"}
|
self._states[peer_id] = {"mode": "training"}
|
||||||
return self._ask_next(self._states[peer_id])
|
return self._ask_next(self._states[peer_id])
|
||||||
@@ -755,6 +764,14 @@ class BelkiDialog:
|
|||||||
state = self._states.get(actor_id)
|
state = self._states.get(actor_id)
|
||||||
if state:
|
if state:
|
||||||
self._attach_pending(actor_id)
|
self._attach_pending(actor_id)
|
||||||
|
if state and state.get("awaiting_attachments"):
|
||||||
|
if text.lower() in ("готово", "дальше", "продолжить"):
|
||||||
|
if not state.get("attachments"):
|
||||||
|
return "Я пока не вижу скриншотов. Пришлите хотя бы одну фотографию, затем нажмите «Готово»."
|
||||||
|
state.pop("awaiting_attachments", None)
|
||||||
|
state["confirm"] = True
|
||||||
|
return self._confirmation(state)
|
||||||
|
return "Сначала пришлите скриншоты, затем нажмите «Готово» или используйте кнопку."
|
||||||
if state and state.get("confirm"):
|
if state and state.get("confirm"):
|
||||||
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
||||||
if self.attachment_mirror:
|
if self.attachment_mirror:
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text
|
|||||||
|
|
||||||
|
|
||||||
class VkConversationTests(unittest.TestCase):
|
class VkConversationTests(unittest.TestCase):
|
||||||
|
@staticmethod
|
||||||
|
def add_screenshot(dialog, actor_id):
|
||||||
|
dialog.queue_attachments(actor_id, [{"type": "photo", "url": "https://example.test/screenshot.jpg"}])
|
||||||
|
return dialog.handle(actor_id, "готово")
|
||||||
|
|
||||||
def test_help_is_a_neutral_faq(self):
|
def test_help_is_a_neutral_faq(self):
|
||||||
self.assertIn("Беличья нора — помощь", HELP_TEXT)
|
self.assertIn("Беличья нора — помощь", HELP_TEXT)
|
||||||
self.assertIn("Как отправить данные", HELP_TEXT)
|
self.assertIn("Как отправить данные", HELP_TEXT)
|
||||||
@@ -21,7 +26,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
self.assertIn("сопровождающ", dialog.handle(77, "11:20").lower())
|
self.assertIn("сопровождающ", dialog.handle(77, "11:20").lower())
|
||||||
self.assertIn("котён", dialog.handle(77, "Дикая Вишня [1604614]").lower())
|
self.assertIn("котён", dialog.handle(77, "Дикая Вишня [1604614]").lower())
|
||||||
self.assertIn("самостоятель", dialog.handle(77, "Серолап [1617140]").lower())
|
self.assertIn("самостоятель", dialog.handle(77, "Серолап [1617140]").lower())
|
||||||
confirmation = dialog.handle(77, "самостоятельно")
|
self.assertIn("скриншот", dialog.handle(77, "самостоятельно").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 77)
|
||||||
self.assertIn("подтверд", confirmation.lower())
|
self.assertIn("подтверд", confirmation.lower())
|
||||||
report = dialog.handle(77, "да")
|
report = dialog.handle(77, "да")
|
||||||
self.assertIn("Баллы белки: 4 баллы.", report)
|
self.assertIn("Баллы белки: 4 баллы.", report)
|
||||||
@@ -32,6 +38,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
88,
|
88,
|
||||||
"/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно",
|
"/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно",
|
||||||
)
|
)
|
||||||
|
self.assertIn("скриншот", confirmation.lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 88)
|
||||||
self.assertIn("распознал", confirmation.lower())
|
self.assertIn("распознал", confirmation.lower())
|
||||||
self.assertIn("11:00", confirmation)
|
self.assertIn("11:00", confirmation)
|
||||||
self.assertIn("подтверд", confirmation.lower())
|
self.assertIn("подтверд", confirmation.lower())
|
||||||
@@ -68,17 +76,20 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
response = dialog.handle(101, "ЛУ")
|
response = dialog.handle(101, "ЛУ")
|
||||||
self.assertIn("самостоятель", response.lower())
|
self.assertIn("самостоятель", response.lower())
|
||||||
response = dialog.handle(101, "самостоятельно")
|
response = dialog.handle(101, "самостоятельно")
|
||||||
self.assertIn("подтверд", response.lower())
|
self.assertIn("скриншот", response.lower())
|
||||||
|
|
||||||
def test_training_supports_stepwise_and_natural_bulk(self):
|
def test_training_supports_stepwise_and_natural_bulk(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
|
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
|
||||||
self.assertIn("котён", dialog.handle(102, "Дикая Вишня [1604614]").lower())
|
self.assertIn("котён", dialog.handle(102, "Дикая Вишня [1604614]").lower())
|
||||||
confirmation = dialog.handle(102, "Серолап [1617140]")
|
self.assertIn("скриншот", dialog.handle(102, "Серолап [1617140]").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 102)
|
||||||
self.assertIn("25", confirmation)
|
self.assertIn("25", confirmation)
|
||||||
self.assertIn("#урок", dialog.handle(102, "да"))
|
self.assertIn("#урок", dialog.handle(102, "да"))
|
||||||
|
|
||||||
natural = dialog.handle(103, "урок Дикая Вишня 1604614 Серолап 1617140")
|
natural = dialog.handle(103, "урок Дикая Вишня 1604614 Серолап 1617140")
|
||||||
|
self.assertIn("скриншот", natural.lower())
|
||||||
|
natural = self.add_screenshot(dialog, 103)
|
||||||
self.assertIn("25", natural)
|
self.assertIn("25", natural)
|
||||||
self.assertIn("подтверд", natural.lower())
|
self.assertIn("подтверд", natural.lower())
|
||||||
|
|
||||||
@@ -89,7 +100,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
self.assertIn("сколько", dialog.handle(104, "дупло").lower())
|
self.assertIn("сколько", dialog.handle(104, "дупло").lower())
|
||||||
self.assertIn("персонаж", dialog.handle(104, "6").lower())
|
self.assertIn("персонаж", dialog.handle(104, "6").lower())
|
||||||
self.assertIn("ресурс", dialog.handle(104, "1617140").lower())
|
self.assertIn("ресурс", dialog.handle(104, "1617140").lower())
|
||||||
confirmation = dialog.handle(104, "без ресурсов")
|
self.assertIn("скриншот", dialog.handle(104, "без ресурсов").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 104)
|
||||||
self.assertIn("Серолап", confirmation)
|
self.assertIn("Серолап", confirmation)
|
||||||
self.assertIn("подтверд", confirmation.lower())
|
self.assertIn("подтверд", confirmation.lower())
|
||||||
|
|
||||||
@@ -101,7 +113,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
response = dialog.handle(105, "1617140")
|
response = dialog.handle(105, "1617140")
|
||||||
self.assertIn("связк", response.lower())
|
self.assertIn("связк", response.lower())
|
||||||
dialog.handle(105, "Серолап")
|
dialog.handle(105, "Серолап")
|
||||||
confirmation = dialog.handle(105, "без ресурсов")
|
dialog.handle(105, "без ресурсов")
|
||||||
|
confirmation = self.add_screenshot(dialog, 105)
|
||||||
self.assertIn("Серолап", confirmation)
|
self.assertIn("Серолап", confirmation)
|
||||||
|
|
||||||
def test_inspection_resources_use_signed_amount_before_name(self):
|
def test_inspection_resources_use_signed_amount_before_name(self):
|
||||||
@@ -110,7 +123,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(106, "дупло")
|
dialog.handle(106, "дупло")
|
||||||
dialog.handle(106, "6")
|
dialog.handle(106, "6")
|
||||||
dialog.handle(106, "Серолап [1617140]")
|
dialog.handle(106, "Серолап [1617140]")
|
||||||
confirmation = dialog.handle(106, "-1 вьюнок, + 3 паук")
|
self.assertIn("скриншот", dialog.handle(106, "-1 вьюнок, + 3 паук").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 106)
|
||||||
self.assertIn("вьюнок=-1", confirmation)
|
self.assertIn("вьюнок=-1", confirmation)
|
||||||
self.assertIn("паук=3", confirmation)
|
self.assertIn("паук=3", confirmation)
|
||||||
|
|
||||||
@@ -119,7 +133,8 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.queue_attachments(107, [{"type": "photo", "url": "https://example.test/photo.jpg"}])
|
dialog.queue_attachments(107, [{"type": "photo", "url": "https://example.test/photo.jpg"}])
|
||||||
dialog.handle(107, "/урок")
|
dialog.handle(107, "/урок")
|
||||||
dialog.handle(107, "Белка [1]")
|
dialog.handle(107, "Белка [1]")
|
||||||
confirmation = dialog.handle(107, "Котёнок [2]")
|
self.assertIn("скриншот", dialog.handle(107, "Котёнок [2]").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 107)
|
||||||
self.assertIn("подтверд", confirmation.lower())
|
self.assertIn("подтверд", confirmation.lower())
|
||||||
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
|
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
|
||||||
|
|
||||||
@@ -135,8 +150,9 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(108, "/урок")
|
dialog.handle(108, "/урок")
|
||||||
dialog.handle(108, "Белка [1]")
|
dialog.handle(108, "Белка [1]")
|
||||||
dialog.handle(108, "Котёнок [2]")
|
dialog.handle(108, "Котёнок [2]")
|
||||||
|
self.add_screenshot(dialog, 108)
|
||||||
dialog.handle(108, "да")
|
dialog.handle(108, "да")
|
||||||
self.assertEqual(mirrored, ["https://vk.example/photo.jpg"])
|
self.assertEqual(mirrored[0], "https://vk.example/photo.jpg")
|
||||||
|
|
||||||
def test_natural_inspection_accepts_character_id_without_name(self):
|
def test_natural_inspection_accepts_character_id_without_name(self):
|
||||||
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
||||||
@@ -170,13 +186,14 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(501, "/лу")
|
dialog.handle(501, "/лу")
|
||||||
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
||||||
dialog.handle(501, answer)
|
dialog.handle(501, answer)
|
||||||
confirmation = dialog.handle(501, "Самостоятельный")
|
self.assertIn("скриншот", dialog.handle(501, "Самостоятельный").lower())
|
||||||
|
confirmation = self.add_screenshot(dialog, 501)
|
||||||
self.assertIn("самостоятельно", confirmation.lower())
|
self.assertIn("самостоятельно", confirmation.lower())
|
||||||
|
|
||||||
dialog.handle(502, "/лу")
|
dialog.handle(502, "/лу")
|
||||||
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
||||||
dialog.handle(502, answer)
|
dialog.handle(502, answer)
|
||||||
self.assertIn("несамостоятельно", dialog.handle(502, "несам").lower())
|
self.assertIn("скриншот", dialog.handle(502, "несам").lower())
|
||||||
|
|
||||||
def test_keyboard_changes_with_dialog_state(self):
|
def test_keyboard_changes_with_dialog_state(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
@@ -188,6 +205,9 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(503, answer)
|
dialog.handle(503, answer)
|
||||||
labels = [button["action"]["label"] for row in dialog.keyboard_for(503)["buttons"] for button in row]
|
labels = [button["action"]["label"] for row in dialog.keyboard_for(503)["buttons"] for button in row]
|
||||||
self.assertEqual(labels[:2], ["Сам", "Несам"])
|
self.assertEqual(labels[:2], ["Сам", "Несам"])
|
||||||
|
dialog.handle(503, "сам")
|
||||||
|
labels = [button["action"]["label"] for row in dialog.keyboard_for(503)["buttons"] for button in row]
|
||||||
|
self.assertIn("Готово", labels)
|
||||||
|
|
||||||
def test_quick_buttons_cover_safe_choices(self):
|
def test_quick_buttons_cover_safe_choices(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
|
|||||||
Reference in new issue
Block a user