def run_command(user_state, command_code, chat_message, router):

        card_number = ""
        card_month = ""
        card_year = ""
        card_cvv = ""
        error = ""

        command_value = {"card_number": card_number, "card_month": card_month, "card_year": card_year, "card_cvv": card_cvv}

        UserState.set_command_value(chat_message.chat_id, user_state, command_code, json.dumps(command_value)) #empty card settings
        UserState.set_state(chat_message.chat_id, user_state, command_code)

        user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)
        
        card_number = " ".join("{:-<16s}".format(card_number))
        card_number = string.join([card_number[i: i+7]+"  " for i in range(0, 32, 8)])
        
        view_params['text'] = view_params['text'].format(card_number = card_number,
                                                         card_year = " ".join("{:-<2s}".format(card_year)),
                                                         card_month = " ".join("{:-<2s}".format(card_month)),
                                                         card_cvv = " ".join("{:-<3s}".format(card_cvv)),
                                                         error = error
                                                         )


        user_view.render(**view_params)
Ejemplo n.º 2
0
 def start_scenario(self, user_id, scenario_name, text):
     """Начало сценария и выполнения первого шага"""
     scenario = settings.SCENARIOS[scenario_name]
     first_step = scenario["first_step"]
     step = scenario["steps"][first_step]
     info_user = self.api.users.get(user_ids=user_id)[0]
     first_name = info_user["first_name"]
     last_name = info_user["last_name"]
     UserState(
         user_id=user_id,
         first_name=first_name,
         last_name=last_name,
         scenario_name=scenario_name,
         step_name=first_step,
         context={}
     )
     state = UserState.get(user_id=user_id)
     state.context["departure_cities_for_write"] = self.departure_cities_for_write
     state.context["departure_cities"] = self.departure_cities
     state.context["flight_schedule"] = convert_data_to_str(self.flight_schedule)
     self.sent_step(
         step=step,
         user_id=user_id,
         text=text,
         state=state
     )
    def run_command(user_state, command_code, chat_message, router):

        UserState.set_command_value(chat_message.chat_id, user_state, command_code, "")
        UserState.set_state(chat_message.chat_id, user_state, command_code)

        user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)
        
        render_context = AbstractView.show_toast(chat_message.chat_id, MessageText.STATE_AUTH_LOADING)
        view_render_extras = {'message_id': render_context['result']['message_id'], 'is_update': True}
        try:
            user_cards = []
            cards_json = AlfaApi.get_cards(user = User(chat_message.chat_id))
            for card_obj in cards_json:
                user_cards.append(UserCard(**card_obj))

            inline_buttons = []
            for card in user_cards:
                inline_buttons.append([{'text': MessageText.CARD_NAME % card.number, 'callback_data': card.pack()}])
                logging.info(card.pack())
            view_params.update({'inline_buttons': inline_buttons})            
            
            view_params.update(view_render_extras)
            user_view.render(**view_params)

        except AlfaApiError:
            AbstractView.show_toast(chat_message.chat_id, ErrorText.ERROR_BANK_ERROR_TOAST, view_render_extras)
    def process_update(update):
    
        try:
            chat_message = ChatMessage(update)
        except ChatMessageNotPrivate: #message must be private
            logging.info("Wrong group type")
            return

        user_state = UserState.get_state(chat_message.chat_id)

        if chat_message.is_command:
            if RouteConfig.command_fits_state(chat_message.command_code, user_state['state']):
                command_name = chat_message.command_code
                method_results = RouteConfig.get_route(user_state['state'], command_name)['controller'].run_command(user_state['state'], command_name, chat_message, RouteConfig)
            else:
                return #just disregard the message
        else:
            command_name = user_state['command_code']
            method_results = RouteConfig.get_route(user_state['state'], command_name)['controller'].complete_command(user_state['state'], command_name, chat_message, RouteConfig)
        

        if method_results:
            try:
                if method_results['run_next']:
                    user_state = UserState.get_state(chat_message.chat_id)
                    RouteConfig.get_route(user_state['state'], user_state['command_code'])['controller'].run_command(user_state['state'], user_state['command_code'], chat_message, RouteConfig)
            except KeyError:
                pass
    def run_command(user_state, command_code, chat_message, router):
        UserState.set_command_value(chat_message.chat_id, user_state, command_code, "") #empty phone number/confirmation number
        UserState.set_state(chat_message.chat_id, user_state, command_code)

        user_view = router.get_route(user_state, command_code)['view']
        view_params = user_view.get()
        view_params.update({'chat_id': chat_message.chat_id})
        user_view.render(**view_params)
    def run_command(user_state, command_code, chat_message, router):
        UserState.set_command_value(chat_message.chat_id, user_state, command_code, "") 
        UserState.set_state(chat_message.chat_id, user_state, command_code)

        phone_number = UserState.get_command_value(chat_message.chat_id, user_state, UserState.STATE_UNAUTH_C_GET_PHONE)
        phone_number = phone_number[0] + "-" + phone_number[1:4] + "-" + phone_number[4:7] + "-" + phone_number[7:]
        sms_code = ""
        sms_code = " ".join("{:-<6s}".format(sms_code))
        error = ""

        user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)

        view_params['text'] = view_params['text'].format(phone_number=phone_number, sms_code=sms_code, error=error)             
        user_view.render(**view_params)
Ejemplo n.º 7
0
 def check_intents(self, user_id: int, text: str):
     """
     Проверка возможных запросов
     :param user_id: id пользователя
     :param text: текст сообщения
     """
     msg_data = handlers.intents_handler(text, user_id)
     if msg_data:
         text_to_send = msg_data[0]
         keyboard = msg_data[1]
         self.send_text(text_to_send, user_id, keyboard)
     else:
         keyboard = json.dumps(handlers.get_keyboard('root'))
         UserState.set_current_section(user_id, 'root')
         self.send_text(settings.DEFAULT_ANSWER, user_id, keyboard)
Ejemplo n.º 8
0
    def on_event(self, event):
        """
        Отправляет сообщение назад, если это текст.

        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            if event.type == VkBotEventType.MESSAGE_TYPING_STATE:
                log.info("Пользователь набирает сообщение")
            elif event.type == VkBotEventType.MESSAGE_REPLY:
                log.info("Пользователь отправил сообщение")
            return

        user_id = str(event.message.peer_id)
        text = event.message.text
        state = UserState.get(user_id=user_id)

        for intent in settings.INTENTS:
            log.debug(f'User gets {intent}')
            if any(token in text.lower() for token in intent['tokens']):
                if state is not None:
                    state.delete()

                if intent['answer']:
                    self.send_text(intent['answer'], user_id)
                else:
                    self.start_scenario(user_id, intent['scenario'], text)
                break
        else:
            if state is not None:
                self.continue_scenario(text, state, user_id)
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 9
0
    def on_event(self, event):
        """ Отправляет сообщение назад, если это текст.
        :param event: VkBotMessageEvent object
        :return None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info("Мы не умеем обрабатывать событие такого типа %s",
                     event.type)
            return

        user_id = event.message.peer_id
        text = event.message.text
        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 10
0
    def on_event(self, event):
        """
        Отправляет сообщение назад если это текст.
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('Пришло событие, которое не обрабатано, типа - %s', event.type)
            return

        text = event.object.text
        user_id = event.object.peer_id

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    # run intent
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                        break
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                        break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 11
0
    def on_event(self, event):
        """
        Receive message back if the message is text
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info("This part isn't work %s", event.type)
            return

        user_id = event.object.message['peer_id']
        text = event.object.message['text']

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text=text, state=state, user_id=user_id)

        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    # run intent
                    if intent['answer']:
                        self.send_text(text_to_send=intent['answer'], user_id=user_id)
                    else:
                        self.start_scenario(scenario_name=intent['scenario'], user_id=user_id, text=text)
                    break
            else:
                self.send_text(text_to_send=settings.DEFAULT_ANSWER, user_id=user_id)
Ejemplo n.º 12
0
    def on_event(self, event):
        """
        Отправляем сообщение назад, если оно текствое
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            # log.info(f' неизвестное событие {event.type}')
            return

        user_id = event.object.peer_id
        text = event.object.text
        log.debug(f'пользователь {user_id} пишет: {text}')

        state = UserState.get(user_id=str(user_id))

        for intent in INTENTS:
            log.debug(f'User {user_id} get {intent}')
            if any(token in text.lower() for token in intent['tokens']):
                if intent['answer']:
                    self.clear_context(state)
                    text_to_send = intent['answer']
                    self.send_text(text_to_send, user_id)
                else:
                    self.clear_context(str(user_id))
                    self.start_scenario(scenario_name=intent['scenario'], user_id=user_id, text=text)

                break
        else:
            if state is not None:
                self.continue_scenario(text=text, state=state, user_id=user_id)
            else:
                text_to_send = DEFAULT_ANSWER
                self.send_text(text_to_send, user_id)
Ejemplo n.º 13
0
    def on_event(self, event):
        """
        Ответ на полученные сообщения, если это текст
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info(f'{event.type} - НЕОБРАБАТЫВАЕМЫЙ ТИП СОБЫТИЯ')
            return

        user_id = event.object.message['peer_id']
        text = event.object.message["text"]
        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(state=state, user_id=user_id, text=text)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(text_to_send=intent['answer'], user_id=user_id)
                    else:
                        self.start_scenario(user_id=user_id, scenario_name=intent['scenario'], text=text)
                    break
            else:
                self.send_text(text_to_send=settings.DEFAULT_ANSWER, user_id=user_id)
Ejemplo n.º 14
0
 def on_event(self, event: VkBotEventType):
     """
     Обработка входящего события и отправка встречного сообщения
     """
     user_id = str(event.message.peer_id)
     text = event.message.text
     state = UserState.get(user_id=user_id)
     self.user_time = event.message.date
     user = self.vk.method("users.get", {"user_ids": user_id})
     self.name = user[0]['first_name'] + ' ' + user[0]['last_name']
     if state is not None:
         # продолжать сценарий
         self.continue_scenario(text=text, state=state, user_id=user_id)
     else:
         for intent in settings.INTENTS:
             if any(token in text.lower() for token in intent['tokens']):
                 # run intent
                 log.debug(f'Пользователь получил {intent}')
                 if intent['answer']:
                     self.send_text(intent['answer'], user_id)
                 else:
                     self.start_scenario(intent['scenario'], user_id, text)
                 break
         else:
             self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 15
0
    def on_event(self, event):
        """
        Send the message back

        :param event: VkBotMessageEvent object
        :return None
        """
        if event.type != vk_api.bot_longpoll.VkBotEventType.MESSAGE_NEW:
            log.info('Мы пока не умеем обрабатывать такие сообщения')
            return

        user_id = event.object.message['peer_id']
        text = event.object.message['text']

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:

                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 16
0
    def on_event(self, event):
        """
        :param event: VkBotMessageEvent object
        :return: NONE
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.debug('Cannot handle this even %s', event.type)
            return

        user_id = event.object.peer_id
        text = event.object.text
        state = UserState.get(user_id=str(user_id))
        if state is not None:
            self.continue_scenario(text=text, state=state, user_id=user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User get {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 17
0
    def on_event(self, event):
        """
        Обработка текстового сообщения.
        :param event: событие VkBotLongPoll
        :return: None, если событие неизвестно
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            if event.type == VkBotEventType.MESSAGE_EVENT:
                print(event)
            else:
                log.info('мы пока не можем обрабатывать этот тип %s', event.type)
                return

        user_id = event.object.peer_id
        text = event.object.text
        state = UserState.get(user_id=str(user_id))

        if event.object.get('geo'):  # TODO
            text = event.object.get('geo')['place']['title']

        if state is not None and state.scenario_name != 'welcome':
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            if self.check_token(text, user_id) is False:
                spelling_text = SpellingCorrect(settings.TEXT_TEST)
                ans = spelling_text.correct_text(text.lower())
                if ans:
                    self.check_token(ans, user_id)
                else:
                    self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 18
0
    def on_event(self, event):
        """
        Отправляет сообщение назад, если сообщение текст
        :param event: VKBotMessageEvent event
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('мы еще не умеем обрабатывать такой тип событий %s',
                     event.type)
            return

        user_id = event.object.message['peer_id']
        text = event.object.message['text']
        state = UserState.get(user_id=str(user_id))

        if state is not None:
            # continue scenario
            self.continue_scenario(text, state, event)
        else:
            # search intent
            for intent in settings.INTENTS_TICKET:
                if any(token in text.lower() for token in intent['tokens']):
                    log.debug(f'User gets {intent}')
                    # run intent
                    if intent['answer']:
                        self.send_text(event, intent['answer'])
                    else:
                        self.start_scenario(user_id, intent['scenario'], event,
                                            text)
                    break
            else:
                self.send_text(event, settings.DEFAULT_ANSWER)
Ejemplo n.º 19
0
    def on_event(self, event):
        """
        Отправляет сообщение назад пользователю
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info(f'Не умеем пока обрабатывать это событие {event.type}')
            return
        text = event.message.text
        user_id = event.message.peer_id

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    # run intent
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(intent['scenario'], user_id, text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 20
0
    def on_event(self, event):
        """ Отправляет сообщение-ответ на запрос пользователя.

        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('Пришло сообщение типа %s', event.type)
            return

        # определяем id пользователя и текст сообщения
        user_id = event.object.peer_id
        text = event.object.text
        state = UserState.get(user_id=str(user_id))

        # находится ли пользователь в некотором сценарии
        if state is not None:
            # продолжаем сценарий
            self.continue_scenario(text, state, user_id)
        else:
            # определяем потребность пользователя
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')

                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 21
0
    def on_event(self, event):
        """
        Отправляет текстовое сообщение обратно
        :param event: VkBotMessageEvent object
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.debug(f"Нет возможности обаботать событие: {event.type}")
            return

        user_id = str(event.object['message']['peer_id'])
        text = event.object['message']['text']
        state = UserState.get(user_id=user_id)

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 22
0
    def on_event(self, event):
        """
        Sending back text message

        :param event: VkBotMessageEvent object
        :return None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info("Can't handle this type of message %s", event.type)
            return

        user_id = event.obj.peer_id
        text = event.obj.text

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            # continue scenario
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent["tokens"]):
                    # run intent
                    if intent["answer"]:
                        self.send_text(intent["answer"], user_id)
                    else:
                        self.start_scenario(user_id, intent["scenario"], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 23
0
    def on_event(self, event):
        """Отправляет сообщение назад, если это текст
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('Пока не умеем обрабатывать %s', event.type)
            return

        user_id = event.object.message['peer_id']
        text = event.object.message['text']
        state = UserState.get(user_id=str(user_id))

        if state is not None:
            # continue scenario
            text_to_send = self.continue_scenario(text, state)
        else:
            # search intent
            for intent in settings.TICKETS_INTENTS:
                log.debug(f'User got {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        text_to_send = intent['answer']
                    else:
                        text_to_send = self.start_scenario(
                            user_id, intent['scenario'])
                    break
            else:
                text_to_send = settings.DEFAULT_ANSWER

        self.api.messages.send(
            message=text_to_send,
            random_id=random.randint(0, 2**20),
            peer_id=user_id,
        )
Ejemplo n.º 24
0
    def event_receiver(self, event):
        log.debug("Вызов метода _event_receiver")
        events = VkBotEventType
        if event.type != events.MESSAGE_NEW:
            log.info(f"Мы пока не умеем обрабатывать сообщения данного типа. {event.type}")
            return

        user_id = event.object.message['from_id']  # получаем уникальный id пользователя
        text = event.object.message['text']  # текст сообщения отправленного пользователем

        state = UserState.get(user_id=str(user_id))

        if text == '/ticket':
            log.debug("Запуск сценария.")
            text_to_send = self.start_scenario('registration', user_id, state)
        elif text == '/help':
            text_to_send = DEFAULT_ANSWER
        else:
            if state is not None:  # проверяем находится ли пользователь на каком-то шаге сценария
                log.debug("Продолжение сценария.")
                text_to_send = self.continue_scenario(text, state)  # продолжение сценария
            else:
                text_to_send = DEFAULT_ANSWER
        log.debug("Отправка сообщения.")
        self.api.messages.send(message=text_to_send,
                               random_id=get_random_id(),
                               user_id=user_id)  # отправляем пользователю сообщение
Ejemplo n.º 25
0
    def on_event(self, event):
        """
        Обработка события:
        :param event: VkBotMessageEvent
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('Сообщения такого типа не обрабатываются %s', event.type)
            return
        user_id = event.object.peer_id
        text = event.object.text
        state = UserState.get(user_id=str(user_id))

        if self.first_event:
            self.send_text(HELLO_MESSAGE, user_id)
            self.first_event = False
            return
        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            for intent in INTENTS:
                log.debug(f'user get {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 26
0
    def on_event(self, event):
        """
        Handles vk bot events

        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != bot_longpoll.VkBotEventType.MESSAGE_NEW:
            log.info('мы пока не умеем обрабатывать событие такого типа %s',
                     event.type)
            return

        user_id = event.object.peer_id
        text = event.object.text

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            # continue scenario
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        # text_to_send = intent['answer']
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 27
0
    def on_event(self, event):
        """send message back, if it is message
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.info('Мы пока не умеем обрабатывать событие такого типа %s', event.type)
            return

        user_id = event.object.message['peer_id']
        text = event.object.message['text']

        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text, state, user_id)
        else:
            # search intent
            for intent in settings.INTENTS:
                log.debug(f'User gets {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    # run intent
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 28
0
    def event_handling(self, event):
        """
        Отправляет сообщение назад, если оно имеет текстовый формат.
        :param event: VkBotMessageEvent object
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            self.bot_log.info(
                f'Мы пока не умеем обрабатывать событие такого типа - {event.type}'
            )
            return

        user_id = event.message.peer_id
        text = event.message.text
        state = UserState.get(user_id=str(user_id))

        if state is not None:
            self.continue_scenario(text=text, state=state, user_id=user_id)
        else:
            # search intent
            for intent in INTENTS:
                self.bot_log.debug(f'Пользователь получил {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(text_to_send=intent['answer'],
                                       user_id=user_id)
                    else:
                        self.start_scenario(user_id=user_id,
                                            scenario_name=intent['scenario'],
                                            text=text)
                    break
            else:
                self.send_text(text_to_send=DEFAULT_ANSWER, user_id=user_id)
Ejemplo n.º 29
0
    def on_event(self, event):
        """
        Resend input massage
        :event VkBotMessageEvent
        :param event: obj event
        :return: None
        """
        if event.type != VkBotEventType.MESSAGE_NEW:
            log.warning(f'Мы пока не умеем обрабатывать события {event.type}')
            return
        user_id = event.message.from_id
        text = event.message.text

        state = UserState.get(user_id=str(user_id))
        if state is not None:
            self.continue_scenario(text=text, state=state, user_id=user_id)
        else:
            for intent in settings.INTENTS:
                log.debug(f'User get {intent}')
                if any(token in text.lower() for token in intent['tokens']):
                    if intent['answer']:
                        self.send_text(intent['answer'], user_id)
                    else:
                        self.start_scenario(user_id, intent['scenario'], text)
                    break
            else:
                self.send_text(settings.DEFAULT_ANSWER, user_id)
Ejemplo n.º 30
0
def intents_handler(text: str, user_id: int) -> Tuple[str, str] or bool:
    """
    Обрабатывает общие запросы
    :param text: текст сообщения
    :param user_id: id пользователя
    :return: текст отправляемого сообщения и JSON-строка, представляющая клавиатуру,
    или False в случае некорректного запроса
    """
    for intent in settings.INTENTS:
        if any(token in text.lower() for token in intent['tokens']):
            keyboard = json.dumps(get_keyboard(intent['section']))
            text_to_send = intent['answer']
            UserState.set_current_section(user_id, intent['section'])
            log.debug(f'Ответ: {text_to_send}; user_id: {user_id}')
            return text_to_send, keyboard
    else:
        return False
Ejemplo n.º 31
0
def root_choice_handler(text: str, user_id: int) -> Tuple[str, str] or bool:
    """
    Обрабатывает запросы в корневом разделе
    :param text: текст сообщения
    :param user_id: id пользователя
    :return: текст отправляемого сообщения и JSON-строка, представляющая клавиатуру,
    или False в случае некорректного запроса
    """
    sections = select(s.name for s in Section)[:]
    for section in sections:
        if section.lower() in text.lower():
            keyboard = json.dumps(get_keyboard(section))
            text_to_send = f'Вы перешли в раздел "{section}". Выберите интересующий вас товар.'
            UserState.set_current_section(user_id, section)
            log.debug(f'Ответ: {text_to_send}; user_id: {user_id}')
            return text_to_send, keyboard
    else:
        return False
Ejemplo n.º 32
0
 def start_scenario(self, scenario_name, user_id, text):
     scenario = settings.SCENARIOS[scenario_name]  # 'registration'
     first_step = scenario['first_step']
     step = scenario['steps'][first_step]  # 'step1'
     self.sent_step(step, user_id, text, context={})
     UserState(user_id=str(user_id),
               scenario_name=scenario_name,
               step_name=first_step,
               context={})  # создаем состояние пользователя записываем в бд
Ejemplo n.º 33
0
 def start_scenario(self, user_id, scenario_name, text):
     scenario = settings.SCENARIOS[scenario_name]
     first_step = scenario["first_step"]
     step = scenario["steps"][first_step]
     self.send_step(step, user_id, text, context={})
     UserState(user_id=str(user_id),
               scenario_name=scenario_name,
               step_name=first_step,
               context={})
Ejemplo n.º 34
0
 def start_scenario(self, scenario_name, user_id, text):
     scenario = settings.SCENARIOS[scenario_name]
     first_step = scenario['first_step']
     step = scenario['steps'][first_step]
     self.send_step(step, user_id, text, context={})
     UserState(scenario_name=scenario_name,
               step_name=first_step,
               context={},
               user_id=str(user_id))
Ejemplo n.º 35
0
 def start_scenario(self, user_id, scenario_name, text):
     """Запуск сценария бота"""
     scenario = settings.SCENARIOS[scenario_name]
     first_step = scenario['first_step']
     step = scenario['steps'][first_step]
     self.send_step(step, user_id, text, context={})
     UserState(user_id=user_id,
               scenario_name=scenario_name,
               step_name=first_step,
               context={})
    def complete_command(user_state, command_code, chat_message, router):
        view_render_extras = {} #need to add this data to update a view instead of redrawing
        card_add_success = False
        error = ""

        if (chat_message.message_type == ChatMessage.UPDATE_TYPE_CALLBACK):

            view_render_extras = {"message_id": chat_message.message_id, "is_update": True}
            command_value = json.loads(UserState.get_command_value(chat_message.chat_id, user_state, command_code))
            key_code = int(chat_message.data)

            NoCardAddCardController.update_form_by_callback(chat_message, command_value)
            UserState.set_command_value(chat_message.chat_id, user_state, command_code, json.dumps(command_value))

            if key_code == ViewParams.KEYBOARD_KEY_OK:
                card_add_success, error = NoCardAddCardController.check_result(chat_message, view_render_extras, command_value)

            user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)

            card_number = ' '.join('{:-<16s}'.format(command_value['card_number']))
            card_number = string.join([card_number[i: i+7]+'  ' for i in range(0, 32, 8)])
        
            view_params['text'] = view_params['text'].format(card_number = card_number,
                                                                card_year = ' '.join('{:-<2s}'.format(command_value['card_year'])),
                                                                card_month = ' '.join('{:-<2s}'.format(command_value['card_month'])),
                                                                card_cvv = ' '.join('{:-<3s}'.format(command_value['card_cvv'])),
                                                                error = error
                                                                )
            return_value = None

            if card_add_success:
                UserState.set_state(chat_message.chat_id, UserState.STATE_AUTH, UserState.STATE_AUTH_C_INIT)
                view_params['text'] = MessageText.MESSAGE_CORRECT_CARD_ADD
                view_params.update({'force_remove_inline': True})
                return_value = {'run_next': True}
            
            view_params.update(view_render_extras)
            user_view.render(**view_params)            
            return return_value
        else:           
            AbstractView.show_toast(chat_message.chat_id, ErrorText.ERROR_INPUT_UNSUPPORTED)
    def run_command(user_state, command_code, chat_message, router):

        to_card_number = ""
        card_cvv = ""
        transfer_sum = ""
        error = ""
        command_value = {"to_card_number": to_card_number, "card_cvv": card_cvv, "transfer_sum":transfer_sum}

        UserState.set_state(chat_message.chat_id, user_state, command_code)
        UserState.set_command_value(chat_message.chat_id, user_state, command_code, json.dumps(command_value)) 

        render_context = json.loads(UserState.get_command_context(chat_message.chat_id, user_state, UserState.STATE_AUTH_C_TRANSFER_SELECT_CARD))        
        view_render_extras = {'message_id': render_context['result']['message_id'], 'is_update': True}

        user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)

        to_card_number = ' '.join('{:-<16s}'.format(to_card_number))
        to_card_number = string.join([to_card_number[i: i+7]+'  ' for i in range(0, 32, 8)])

        user_card = UserCard.unpack(UserState.get_command_value(chat_message.chat_id, user_state, UserState.STATE_AUTH_C_TRANSFER_SELECT_CARD))

        from_card_number = user_card.number
        
        view_params['text'] = view_params['text'].format(from_card_number = from_card_number, 
                                                         to_card_number = to_card_number,
                                                         card_cvv = ' '.join('{:-<3s}'.format(card_cvv)),
                                                         transfer_sum = ' '.join('{:-<5s}'.format(transfer_sum)),
                                                         error = error
                                                         )


        view_params.update(view_render_extras)
        user_view.render(**view_params)
    def complete_command(user_state, command_code, chat_message, router):
        view_render_extras = {} #need to add this data to update a view instead of redrawing

        user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)

        temp_view_params_text = view_params['text']
        key_code = 0
        sms_code = UserState.get_command_value(chat_message.chat_id, user_state, command_code)
        error = ""
        phone_number = UserState.get_command_value(chat_message.chat_id, user_state, UserState.STATE_UNAUTH_C_GET_PHONE)
        phone_number_formatted = phone_number[0] + '-' + phone_number[1:4] + '-' + phone_number[4:7] + '-' + phone_number[7:]

        if (chat_message.message_type == ChatMessage.UPDATE_TYPE_CALLBACK):
            key_code = int(chat_message.data)
            sms_code, view_render_extras = VerifyPhoneController.update_sms_code_by_callback(chat_message, view_params, sms_code)

        #processing voice message
        elif chat_message.has_voice:
            sms_code, view_render_extras = VerifyPhoneController.update_sms_code_by_audio(chat_message, view_params, sms_code)

        UserState.set_command_value(chat_message.chat_id, user_state, command_code, sms_code)
        sms_code_formatted = ' '.join('{:-<6s}'.format(sms_code))               
        view_params['text'] = view_params['text'].format(phone_number=phone_number_formatted, sms_code=sms_code_formatted, error=error)
        return_value = None        

        #Handling result
        if ((chat_message.message_type == ChatMessage.UPDATE_TYPE_CALLBACK) and (key_code == ViewParams.KEYBOARD_KEY_OK)
            or (chat_message.voice)):
            try:
                AbstractView.show_toast(chat_message.chat_id, MessageText.STATE_AUTH_LOADING, view_render_extras)
                user_obj = AlfaApi.send_sms_code(phone_number, sms_code)  
                
                User.add(chat_id, "access_token", user_obj['access_token'])
                User.add(chat_id, "refresh_token", user_obj['refresh_token'])

                UserState.set_state(chat_message.chat_id, UserState.STATE_NOCARD, UserState.STATE_NOCARD_C_INIT)
                view_params['text'] = MessageText.MESSAGE_CORRECT_CODE
                view_params.update({'force_remove_inline': True})
                return_value = {'run_next': True}

            except AlfaApiError:
                error = ErrorText.ERROR_WRONG_SMS_CODE
                sms_code = ""
                UserState.set_command_value(chat_message.chat_id, user_state, command_code, sms_code)                
                sms_code_formatted = ' '.join('{:-<6s}'.format(sms_code)) 
                view_params['text'] = temp_view_params_text.format(phone_number=phone_number_formatted, sms_code=sms_code_formatted, error=error)

        user_view.render(**view_params)
        return return_value
    def complete_command(user_state, command_code, chat_message, router):

        if chat_message.phone:
            render_context = AbstractView.show_toast(chat_message.chat_id, MessageText.STATE_AUTH_LOADING)
            view_render_extras = {'message_id': render_context['result']['message_id'], 'is_update': True}

            try:                
                user_obj = AlfaApi.send_phone_number(chat_message.phone)  
                User.add(chat_message.chat_id, "user_id", user_obj['user_id'])

                UserState.set_command_value(chat_message.chat_id, user_state, command_code, chat_message.phone) #fill phone number
                command_code = UserState.STATE_UNAUTH_C_VERIFY_PHONE            
                UserState.set_state(chat_message.chat_id, user_state, command_code)                
                AbstractView.show_toast(chat_message.chat_id, MessageText.MESSAGE_CORRECT_PHONE, view_render_extras)
                return {"run_next": True}

            except AlfaApiError:
                command_code = UserState.STATE_ERROR
                user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)
                view_params.update(view_render_extras)
                user_view.render(**view_params)
        else:            
            AbstractView.show_toast(chat_message.chat_id, ErrorText.ERROR_NO_PHONE)           
Ejemplo n.º 40
0
def get_user_state(user):
    user_state = None
    user_state_list = UserState.objects.filter(fbuser=user)
    if len(user_state_list) > 0:
        user_state = user_state_list[0]
    else:
        user_state = UserState(fbuser=user)
        user_state.current_retrieval_start = 0
        user_state.last_photo_retrieval = 0
        user_state.last_album_retrieval = 0
        user_state.save()
    return user_state
    def complete_command(user_state, command_code, chat_message, router):

        view_render_extras = {} #need to add this data to update a view instead of redrawing

        if (chat_message.message_type == ChatMessage.UPDATE_TYPE_CALLBACK):
            view_render_extras = {'message_id': chat_message.message_id, 'is_update': True}
            UserState.set_command_value(chat_message.chat_id, user_state, command_code, chat_message.data)

            render_context = AbstractView.show_toast(chat_message.chat_id, MessageText.STATE_AUTH_LOADING, view_render_extras)
            UserState.set_command_context(chat_message.chat_id, user_state, command_code, json.dumps(render_context))
            UserState.set_state(chat_message.chat_id, user_state, UserState.STATE_AUTH_C_TRANSFER_TRANSFER)
            return {'run_next': True}
        else:
            AbstractView.show_toast(chat_message.chat_id, ErrorText.ERROR_INPUT_UNSUPPORTED, view_render_extras)
    def complete_command(user_state, command_code, chat_message, router):
        view_render_extras = {} #need to add this data to update a view instead of redrawing
        error = ""
        card_add_success = False #TODO: design the correct handling of the alfa API

        if (chat_message.message_type == ChatMessage.UPDATE_TYPE_CALLBACK):
            key_code = int(chat_message.data)

            user_card = UserCard.unpack(UserState.get_command_value(chat_message.chat_id, user_state, UserState.STATE_AUTH_C_TRANSFER_SELECT_CARD))
            from_card_number = user_card.number

            view_render_extras = {'message_id': chat_message.message_id, 'is_update': True}
            command_value = json.loads(UserState.get_command_value(chat_message.chat_id, user_state, command_code))

            AuthTransferController.update_form_by_callback(chat_message, command_value)            
            UserState.set_command_value(chat_message.chat_id, user_state, command_code, json.dumps(command_value))

            if key_code == ViewParams.KEYBOARD_KEY_OK:
                card_add_success, error = AuthTransferController.check_result(chat_message, view_render_extras, command_value, user_card)

            user_view, view_params = router.get_view(user_state, command_code, chat_message.chat_id)

            to_card_number = ' '.join('{:-<16s}'.format(command_value['to_card_number']))
            to_card_number = string.join([to_card_number[i: i+7]+'  ' for i in range(0, 32, 8)])
        
            view_params['text'] = view_params['text'].format(from_card_number=from_card_number, 
                                                             to_card_number = to_card_number,
                                                             card_cvv = ' '.join('{:-<3s}'.format(command_value['card_cvv'])),
                                                             transfer_sum = command_value['transfer_sum'],
                                                             error = error
                                                                )



            if card_add_success:
                UserState.set_state(chat_message.chat_id, UserState.STATE_AUTH, UserState.STATE_AUTH_C_INIT)
                view_params['text'] = MessageText.MESSAGE_CORRECT_TRANSFER
                view_params.update({'force_remove_inline': True})
            
            view_params.update(view_render_extras)
            user_view.render(**view_params)            
        else:
            AbstractView.show_toast(chat_message.chat_id, ErrorText.ERROR_INPUT_UNSUPPORTED, view_render_extras)