Beispiel #1
0
 def reply(self, request: Request):
     asked = request.state_session.get(state.ASKED_QUESTIONS, {})
     question_by_categories = [(t, [q["id"] for q in get_questions(t)])
                               for t in QuestionType
                               if t != QuestionType.unknown]
     non_empty_categories = [
         question_type
         for question_type, question_ids in question_by_categories
         if set(question_ids) - set(asked)
     ]
     if non_empty_categories:
         left_type_names = [t.russian() for t in non_empty_categories]
         all_categories_present = len(non_empty_categories) == 3
         buttons = [button(n) for n in left_type_names]
         state_update = {}
     else:
         all_categories_present = True
         buttons = [
             button("Простой"),
             button("Сложный"),
             button("На внимательность"),
         ]
         state_update = {state.ASKED_QUESTIONS: {}}
     new_state = {state.QUESTION_TYPE: "simple"}
     new_state.update(state_update)
     return self.make_response(
         request,
         text=texts.start_quiz(all_categories_present),
         buttons=buttons,
         state=new_state,
     )
Beispiel #2
0
 def reply(self, request: Request):
     text = self.title + "\n" + texts.welcome()
     directives = {"request_geolocation": {}}
     return self.make_response(
         request,
         text,
         buttons=[
             button("Сыграть в викторину"),
             button("Расскажи экскурсию"),
         ],
     )
Beispiel #3
0
 def reply(self, request: Request):
     text = "Все данные были сброшены" + "\n" + texts.welcome()
     return self.make_response(
         request,
         text,
         buttons=[
             button("Сыграть в викторину"),
             button("Расскажи экскурсию"),
         ],
         user_state=dict((el, None) for el in state.USER_STATE),
     )
Beispiel #4
0
 def reply(self, request: Request):
     text = texts.start_quiz()
     return self.make_response(
         request,
         text,
         buttons=[
             button("Простой"),
             button("Сложный"),
             button("На внимательность"),
         ],
         state={state.QUESTION_TYPE: "simple"},
     )
Beispiel #5
0
    def reply(self, request: Request):
        id = request.state_user[state.TOUR_ID]
        level = request.state_user[state.TOUR_LEVEL]

        data = _get_tour_data(id, level)

        return self.make_response(
            request,
            texts.continue_tour(data["return_text"]),
            buttons=[button("Напомни"),
                     button("Дальше"),
                     button("Сначала")],
        )
Beispiel #6
0
    def reply(self, request: Request):
        # как и в повторе сохранено уже следующее состояние
        id = request.state_user[state.TOUR_ID]
        level = request.state_user[state.TOUR_LEVEL]

        data = _get_tour_data(id, level)

        return self.make_response(
            request,
            texts.continue_tour(data["return_text"]),
            buttons=[button("Да"),
                     button("Нет"),
                     button("Повтори")],
        )
Beispiel #7
0
    def reply(self, request):
        self.tour_id = request.state_user.get(state.TOUR_ID, 0) + self.step_id
        if self.step_level == -1:
            self.tour_level = 0
        else:
            self.tour_level = (request.state_user.get(state.TOUR_LEVEL, 0) +
                               self.step_level)

        data = _get_tour_data(self.tour_id, self.tour_level)
        if not data:
            self.tour_id = 1
            self.tour_level = 0
            data = _get_tour_data(self.tour_id, self.tour_level)
        text = data["text"]
        tts = data["audio"]
        card = image_gallery(image_ids=data["gallery"].split(sep="|"))
        return self.make_response(
            request,
            text,
            tts=tts,
            buttons=YES_NO + [button("перерыв")],
            card=card,
            user_state={
                state.TOUR_ID: self.tour_id,
                state.TOUR_LEVEL: self.tour_level
            },
        )
Beispiel #8
0
    def get_buttons(self, asked):
        questions = get_questions(question["type"])
        not_asked = [q for q in questions if q["id"] not in asked]

        if len(not_asked) > 0:
            have_more_questions = True
            next_question_prompt = {
                "simple": "Задать еще простой вопрос?",
                "hard": "Задать еще сложный вопрос?",
                "attention": "Задать еще вопрос на внимательность?",
            }[question["type"]]
            buttons = YES_NO
        else:
            have_more_questions = False
            question_type = QuestionType[question["type"]]
            other_categories = [
                (t, [q["id"] for q in get_questions(t)]) for t in QuestionType
                if t != question_type and t != QuestionType.unknown
            ]
            non_empty_other = [
                question_type
                for question_type, question_ids in other_categories
                if set(question_ids) - set(asked)
            ]
            if non_empty_other:
                left_type_names = [t.russian() for t in non_empty_other]
                left_type_names_str = ", ".join(f'"{n}"'
                                                for n in left_type_names)
                next_question_prompt = texts.quiz_category_finished(
                    left_type_names_str, len(non_empty_other))
                buttons = [button(n) for n in left_type_names]
                buttons.append(button("Расскажи экскурсию"))
            else:
                num_true = sum(bool(v) for v in asked.values())
                num_total = len(asked)
                next_question_prompt = texts.quiz_finished(num_true, num_total)
                buttons = [
                    button("Расскажи экскурсию"),
                    button("Выйти из навыка")
                ]

            return buttons
Beispiel #9
0
 def reply(self, request: Request):
     if intents.GAME_QUESTION in request.intents:
         question_type = QuestionType.from_request(request,
                                                   intents.GAME_QUESTION)
     elif state.QUESTION_TYPE in request.state_session:
         question_type = QuestionType.from_state(request)
     else:
         question_type = QuestionType.simple
     questions = get_questions(question_type)
     asked = request.state_session.get(state.ASKED_QUESTIONS, {})
     not_asked = [q for q in questions if q["id"] not in asked]
     if not_asked:
         question = random.choice(not_asked)
         question_id = question["id"]
         question_text = question["text"]
         start_text = {
             "simple": "Задаю простой вопрос.",
             "hard": "Задаю сложный вопрос.",
             "attention": "Задаю вопрос на внимательность.",
         }[question_type.name]
         buttons = ([button(v) for v in question["suggest"].split(";")]
                    if question["suggest"] else [])
         asked.update({question_id: None})
         return self.make_response(
             request,
             f"{start_text} {question_text}",
             state={
                 "question_id": question_id,
                 state.ASKED_QUESTIONS: asked,
             },
             buttons=buttons,
         )
     else:
         return self.make_response(
             request,
             texts.run_out_of_questions(),
             buttons=[
                 button("Сыграть в викторину"),
                 button("Расскажи экскурсию"),
             ],
         )
Beispiel #10
0
            return eval(request.state_session[state.PREVIOUS_SCENE] + "()")
        elif intents.REJECT in request.intents:
            return Welcome("Тогда вернемся в самое начало.")


def _list_scenes():
    current_module = sys.modules[__name__]
    scenes = []
    for name, obj in inspect.getmembers(current_module):
        if inspect.isclass(obj) and issubclass(obj, Scene):
            scenes.append(obj)
    return scenes


def _get_tour_data(id: int, level: int):
    with open("guide/tour.csv", mode="r", encoding="utf-8") as in_file:
        reader = csv.DictReader(in_file, delimiter=",")
        data = [
            r for r in reader
            if r["id"] == str(id) and r["level"] == str(level)
        ]
        if data:
            return data[0]


SCENES = {scene.id(): scene for scene in _list_scenes()}

DEFAULT_SCENE = Welcome

YES_NO = [button("Да"), button("Нет")]
Beispiel #11
0
 def reply(self, request: Request):
     question_id = request.state_session[state.QUESTION_ID]
     question = self.get_question(question_id)
     answer_type = question["answer_type"]
     if answer_type == "int":
         correct_answer = int(question["answer"])
         nlu_entities = request.request_body["request"]["nlu"]["entities"]
         nlu_numbers = [
             e["value"] for e in nlu_entities
             if e["type"] == "YANDEX.NUMBER"
         ]
         answered_correctly = correct_answer in nlu_numbers
     elif answer_type == "str":
         tokens = request["request"]["nlu"]["tokens"]
         tokens_norm = [normal_form(t) for t in tokens]
         print(f"morph result: {tokens_norm}")
         user_words_and_forms = set(tokens + tokens_norm)
         correct_answers = set(question["answer"].lower().split(";"))
         answered_correctly = len(user_words_and_forms
                                  & correct_answers) > 0
     else:
         raise ValueError(f"Unknown answer type {answer_type}")
     text = question["reply_true"] if answered_correctly else question[
         "reply_false"]
     asked = request.state_session.get(state.ASKED_QUESTIONS, {})
     asked[question_id] = answered_correctly
     questions = get_questions(question["type"])
     not_asked = [q for q in questions if q["id"] not in asked]
     if len(not_asked) > 0:
         have_more_questions = True
         next_question_prompt = {
             "simple": "Задать еще простой вопрос?",
             "hard": "Задать еще сложный вопрос?",
             "attention": "Задать еще вопрос на внимательность?",
         }[question["type"]]
         buttons = YES_NO
     else:
         have_more_questions = False
         question_type = QuestionType[question["type"]]
         other_categories = [
             (t, [q["id"] for q in get_questions(t)]) for t in QuestionType
             if t != question_type and t != QuestionType.unknown
         ]
         non_empty_other = [
             question_type
             for question_type, question_ids in other_categories
             if set(question_ids) - set(asked)
         ]
         if non_empty_other:
             left_type_names = [t.russian() for t in non_empty_other]
             left_type_names_str = ", ".join(f'"{n}"'
                                             for n in left_type_names)
             next_question_prompt = texts.quiz_category_finished(
                 left_type_names_str, len(non_empty_other))
             buttons = [button(n) for n in left_type_names]
             buttons.append(button("Расскажи экскурсию"))
         else:
             num_true = sum(bool(v) for v in asked.values())
             num_total = len(asked)
             next_question_prompt = texts.quiz_finished(num_true, num_total)
             buttons = [
                 button("Расскажи экскурсию"),
                 button("Выйти из навыка")
             ]
             asked = {}
     return self.make_response(
         request,
         f"{text} {next_question_prompt}",
         buttons=buttons,
         state={
             state.QUESTION_TYPE: question["type"],
             state.HAVE_MORE_QUESTIONS: have_more_questions,
             state.ASKED_QUESTIONS: asked,
         },
     )