Ejemplo n.º 1
0
def main():
    """ Функция получает тело запроса и возвращает ответ

    :return: ответ
    """
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))
    alice_response = AliceResponse(alice_request)
    user_id = alice_request.user_id
    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id))
    logging.info('Response: {}'.format(alice_response))
    return alice_response.dumps()
Ejemplo n.º 2
0
def main():
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id

    alice_response, SESSION_STORAGE[user_id] = handle_dialog(
        alice_request, alice_response, SESSION_STORAGE.get(user_id)
    )

    logging.info('Response: {}'.format(alice_response))

    return alice_response.dumps()
def main():
    database = init_database(host='localhost', user='******', password='******', dbname='new_game')
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))
    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id
    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id), database
    )

    logging.info('Response: {}'.format(alice_response))
    print()

    return alice_response.dumps()
Ejemplo n.º 4
0
def main():
    # Функция получает тело запроса и возвращает ответ.
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))
    database = database_module.DatabaseManager()
    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id
    print(user_id)
    print(session_storage.get(user_id))
    print(len(session_storage))
    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id), database)

    logging.info('Response: {}'.format(alice_response))
    print()

    return alice_response.dumps()
def main():
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id

    alice_response, storage = handle_dialog(
        alice_request, alice_response,
        mc.get("session_storage").get(user_id))

    sessions = mc.get("session_storage")
    sessions[user_id] = storage
    mc.set("session_storage", sessions)

    logging.info('Response: {}'.format(alice_response))

    return alice_response.dumps()
Ejemplo n.º 6
0
def main():
    with open("sessions.json", encoding="utf8") as file:
        session_storage = json.loads(file.read())

    alice_request = AliceRequest(request.json)
    # logging.info("Request: {}".format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id

    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id))

    with open("sessions.json", "w", encoding="utf8") as file:
        json.dump(session_storage, fp=file)

    logging.info("Response: {}".format(alice_response))

    return alice_response.dumps()
Ejemplo n.º 7
0
    def handle_dialog(
        self, request: AliceRequest
    ) -> AliceResponse:  # alice_request, alice_response, session_storage
        self.request = request
        logger.info(request)
        self.response = AliceResponse(self.request)  # Создаем тело ответа

        if self.request.is_new_session:
            self.user_storage["conversation"] = None
            self.user_storage["state"] = 0
            self.user_storage["content"] = []
            self.user_storage["buttons_mode"] = False
            self.response.set_text(
                'Этот навык позволит вам оперативно опубликовывать '
                'экологические проблемы города, а также получать информацию по ним. '
                'Чтобы опубликовать проблему, скажите или введите "Новое", '
                'чтобы получить объявления - "Проблемы".')
            return self.response

        if self.user_storage["conversation"] is None:
            message = self.request.command.lower().strip()  # .replace()
            # Предобработка message
            meaning = self.parse_message(message)
            self.execute(meaning)
        elif not self.user_storage["buttons_mode"]:
            if self.request.command.lower().strip() == "отмена":
                self.reset_conversation()
                self.response.set_text("Действие отменено")
            else:
                input_functions = self.user_storage["conversation"]
                state = self.user_storage["state"]
                self.conversations[input_functions][state](
                )  # Запускаем функцию из очереди
        else:
            input_functions = self.user_storage["conversation"]
            state = self.user_storage["state"]
            self.conversations[input_functions][state](
            )  # Запускаем функцию из очереди

        return self.response
Ejemplo n.º 8
0
def main():
    database = init_database(host='localhost', user='******', password='******',
                             dbname='programmer_simulator')

    # Функция получает тело запроса и возвращает ответ.
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id
    print(user_id)
    print(session_storage.get(user_id))
    print(len(session_storage))
    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id), database
    )

    logging.info('Response: {}'.format(alice_response))
    print()

    return alice_response.dumps()
def mainnn():
    from other import main_function
    from other import alice_app
    import pymorphy2
    database = alice_app.init_database(host='localhost', user='******', password='******', dbname='word_coach')
    alice_request = AliceRequest(request.json)
    morph = pymorphy2.MorphAnalyzer()
    logging.info('Request: {}'.format(alice_request))
    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id
    print(user_id)
    print(session_storage.get(user_id))
    print(len(session_storage))
    alice_response, session_storage[user_id] = main_function.handle_dialog(
        alice_request, alice_response, session_storage.get(user_id), database, morph
    )

    logging.info('Response: {}'.format(alice_response))
    print()

    return alice_response.dumps()
def main():
    # Функция получает тело запроса и возвращает ответ.
    with open("sessions.json", encoding="utf8") as file:
        session_storage = json.loads(file.read())

    alice_request = AliceRequest(request.json)
    # logging.info("Request: {}".format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id

    alice_response, session_storage[user_id] = handle_dialog(
        alice_request, alice_response, session_storage.get(user_id))

    # Потому что оперативка плохо работает
    with open("sessions.json", "w", encoding="utf8") as file:
        json.dump(session_storage, fp=file)

    logging.info("Response: {}".format(alice_response))

    return alice_response.dumps()
Ejemplo n.º 11
0
def zavalinka():
    from other2 import database_module
    from other2 import zavalinka
    import pymorphy2
    from other2.alice_sdk import AliceRequest, AliceResponse
    morph = pymorphy2.MorphAnalyzer()
    database = database_module.DatabaseManager()
    # Функция получает тело запроса и возвращает ответ.
    alice_request = AliceRequest(request.json)
    logging.info('Request: {}'.format(alice_request))

    alice_response = AliceResponse(alice_request)

    user_id = alice_request.user_id
    print(user_id)
    print(session_storage.get(user_id))
    print(len(session_storage))
    alice_response, session_storage[user_id] = zavalinka.handle_dialog(
        alice_request, alice_response, session_storage.get(user_id), database, morph.parse('очко')[0]
    )

    logging.info('Response: {}'.format(alice_response))

    return alice_response.dumps()
Ejemplo n.º 12
0
class AliceDialog:
    def __init__(self):
        self.user_storage = {}
        self.api = UserApi('http://urbanalerts.ml', 'alice')
        self.request = None
        self.response = None
        self.tags = {
            "Урбанистика": "Urban",
            "Общество": "Social",
            "Экология": "Eco"
        }
        self.meanings = {"новое": "new_problem", "проблемы": "get_problems"}

        self.conversations = {
            "new_problem": {
                0: self.get_title,
                1: self.get_description,
                2: self.get_address,
                3: self.get_tag
            },
            "new_": {}
        }

    # Анализ сообщений для соотнесения с ключевыми словами
    def parse_message(self, message: str):
        message = message.split()[0].lower()  # TODO обработку сообщений
        if message in list(self.meanings.keys()):
            meaning = self.meanings[message]
        else:
            meaning = "unclassed"
        return meaning

    # Выполнение на основании ключевых слов
    def execute(self, meaning: str):
        message = ""
        # if meaning == "profile":
        # response = self.api.user_profile(self.request.user_id, "alice")
        # pass
        # if response.status:
        #     self.response.set_text(f"{response.text}")
        if meaning == "new_problem":
            message = 'Если хотите прервать действие скажите/введите "Отмена". "Дайте название проблеме.'
            self.user_storage["conversation"] = "new_problem"

        elif meaning == "get_problems":
            self.get_problems()

        # elif meaning == "stats":
        #     pass
        # elif meaning == "comments/add":
        #     pass
        # elif meaning == "problems/solved":
        #     pass
        # elif meaning == "problems/all":
        #     pass
        # elif meaning == "problems/active":
        #     pass
        if meaning == "unclassed":
            self.response.set_text(
                f"Введите/скажите что-нибудь из списка: {', '.join(self.meanings)}"
            )
        else:
            self.response.set_text(message)

    # Сброс диалоговых переменных
    def reset_conversation(self):
        self.user_storage["conversation"] = None
        self.user_storage["state"] = 0
        self.user_storage["content"] = []
        self.user_storage["buttons_mode"] = False

    # Функции для ConvHandler new
    # ==================================================================================================================
    def get_title(self):
        self.user_storage["state"] += 1
        self.user_storage["content"].append(self.request.command)
        self.response.set_text("Дайте описание проблемы.")

    def get_description(self):
        self.user_storage["state"] += 1
        self.user_storage["content"].append(self.request.command)
        self.response.set_text("Назовите адрес места с этой проблемой.")

    def get_address(self):
        self.user_storage["state"] += 1
        self.user_storage["content"].append(self.request.command)
        self.response.set_text(
            f"Выберите один тег, подходящий для вашей проблемы, нажав на кнопку."
        )
        buttons = []
        for button in self.tags.keys():
            buttons.append({
                "title": button,
                "payload": {
                    "pressed": True,
                    "button": self.tags[button]
                },
                "hide": True
            })
        self.user_storage["buttons_mode"] = True
        self.response.set_buttons(buttons)

    def get_tag(self):
        tag = self.request.payload["button"]
        title, description, address = self.user_storage[
            "content"]  # tag уже присутствует как локальная переменная
        response = self.api.problem_new(title, description, tag, address)

        logger.info(response)
        self.response.set_text("Успешно отмечено.")
        self.reset_conversation()

    # Функции для ConvHandler get problems
    # ==================================================================================================================
    def get_problems(self):
        response = json.loads(self.api.get_problems().text)
        result = ""
        lenght = len(response)
        if len(response) > 5:
            lenght = 5
        for i in range(lenght):
            result += f"{i+1} {response[i]['title']} {response[i]['description']} {response[i]['coors']}| "
        self.response.set_text(
            f"На данный момент актуальны следующие проблемы: {result}")

    # ==================================================================================================================

    # Основной обработчик
    def handle_dialog(
        self, request: AliceRequest
    ) -> AliceResponse:  # alice_request, alice_response, session_storage
        self.request = request
        logger.info(request)
        self.response = AliceResponse(self.request)  # Создаем тело ответа

        if self.request.is_new_session:
            self.user_storage["conversation"] = None
            self.user_storage["state"] = 0
            self.user_storage["content"] = []
            self.user_storage["buttons_mode"] = False
            self.response.set_text(
                'Этот навык позволит вам оперативно опубликовывать '
                'экологические проблемы города, а также получать информацию по ним. '
                'Чтобы опубликовать проблему, скажите или введите "Новое", '
                'чтобы получить объявления - "Проблемы".')
            return self.response

        if self.user_storage["conversation"] is None:
            message = self.request.command.lower().strip()  # .replace()
            # Предобработка message
            meaning = self.parse_message(message)
            self.execute(meaning)
        elif not self.user_storage["buttons_mode"]:
            if self.request.command.lower().strip() == "отмена":
                self.reset_conversation()
                self.response.set_text("Действие отменено")
            else:
                input_functions = self.user_storage["conversation"]
                state = self.user_storage["state"]
                self.conversations[input_functions][state](
                )  # Запускаем функцию из очереди
        else:
            input_functions = self.user_storage["conversation"]
            state = self.user_storage["state"]
            self.conversations[input_functions][state](
            )  # Запускаем функцию из очереди

        return self.response
Ejemplo n.º 13
0
def book(request: AliceRequest, response: AliceResponse, user_storage):
    if not user_storage.get("buy-status"):
        user_storage["buy-status"] = BuyStatus.Choosing
        user_storage["composers"] = composers.copy()
        return send_response(response, user_storage, "select-concert")

    if user_storage.get("buy-status") == BuyStatus.Selected:
        user_storage.pop("buy-status")
        return send_response(response,
                             user_storage,
                             "concert-selected",
                             add_variants=False)

    last_names = request.get_last_names()

    if len(last_names):
        user_storage["composers"] &= last_names

    logging.debug(
        f"Composers for request {' '.join(user_storage['composers'])}")

    if len(user_storage["composers"]) == 0:
        user_storage["composers"] = composers.copy()
        return send_response(response, user_storage,
                             "select-concert-composer-unknown")

    # I'm really feel sorry for this code
    # but working with time sucks
    # working with time ranges sucks twice

    start_date = datetime.date.today()
    end_date = None
    if request.has_date():
        logging.debug("has dates")
        dates = request.get_date()
        start = dates[0]
        if "month_is_relative" in start:
            month = None
            if start["month_is_relative"] == True:
                month_add = start["month"]
                if month_add < 0:
                    return send_response(response, user_storage,
                                         "select-concert-empty")
                month = max(1, (datetime.date.today().month + month_add) % 13)
                logging.debug("relative time")
            else:
                month = start["month"]
                logging.debug("non relative time")
            if month in [11, 12]:
                start_date = datetime.date(2018, month, 1)
            elif month < 5:
                start_date = datetime.date(2019, month, 1)
            else:
                return send_response(response, user_storage,
                                     "select-concert-empty")
            end_date = last_day_in_month(start_date)

    start_date = max(start_date, datetime.date.today())
    logging.debug(f"start date: {humanize.naturalday(start_date)}")
    if end_date:
        logging.debug(f"end date: {humanize.naturalday(end_date)}")

    concerts = find_concerts(user_storage["composers"], start_date, end_date)

    if concerts.empty:
        return send_response(response, user_storage, "select-concert-empty")
    logging.debug(f"found: {concerts.shape[0]} concerts")

    text = f"{'Нашлось' if len(concerts) > 1 else 'Нашёлся'} {len(concerts)} {right_form_from_number('концерт', len(concerts))}. Скажи номер понравившегося!\n"
    buttons = []

    for i, (_, concert) in enumerate(concerts.iterrows()):
        i += 1
        day = concert["дата, гггг-мм-дд"]
        buttons.append({
            "title": str(i),
            "url": concert["купить билет"],
            "hide": True
        })
        text += f"\n{i}. {concert['title']}, {day.day}.{day.month}.{day.year}"

    response.set_text(text)
    response.set_buttons(buttons)
    user_storage["buy-status"] = BuyStatus.Selected
    return response, user_storage