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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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 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)
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)
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)
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)
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)
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)
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, )
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) # отправляем пользователю сообщение
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 = str(event.message.peer_id) text = event.message.text state = UserState.get(user_id=user_id) self.search_intent(text, user_id, state)
def on_event(self, event): """Обработка полученного события""" if event.type != VkBotEventType.MESSAGE_NEW: log.debug("Мы пока не умеем обрабатывать событие такого типа %s", event.type) return user_id = event.object.peer_id text = event.object.text.lower() log.info(f'Пользователь написал {text}') state = UserState.get(user_id=user_id) if state is not None: if checking_special_commands(text): state.delete() self.sent_unswer_without_scenario(text=text, user_id=user_id) else: self.continue_scenario(text, state) else: self.sent_unswer_without_scenario(text=text, user_id=user_id)
def on_event(self, event): """ :param event: VkBotMessageEvent object :return: None """ if event.type != VkBotEventType.MESSAGE_NEW: log.debug('Мы такое пока не обрабатываем %s', event.type) return user_id = event.object['message']['peer_id'] text = event.obj['message']['text'].lower() state = UserState.get(user_id=str(user_id)) if text == '/ticket': if state: state.delete() self.send_text( self.start_scenario(scenario_name='ticket', user_id=user_id), user_id) else: self.send_text( self.start_scenario(scenario_name='ticket', user_id=user_id), user_id) elif text == '/help': self.send_text(settings.INTENTS[0]['answer'], user_id) elif text == 'нет' and state.step_name == 'step9': state.delete() self.send_text( self.start_scenario(scenario_name='ticket', user_id=user_id), user_id) else: if state is not None: self.send_text(self.continue_scenario(user_id, text, state), user_id) else: self.send_text(settings.DEFAULT_ANSWER, user_id) if state is not None: steps = settings.SCENARIO[state.scenario_name]['steps'] step = steps[state.step_name] if 'action' in step: if step['action'] == 'list_flights': self.dispatcher(user_id, state) elif step['action'] == 'correct_check': self.correct_check(user_id, state)
def on_event(self, event): """ Отправляет сообщение назад, если это текст :param event: VkBotMessageEvent object :return: None """ log.debug('получено событие') if event.type != VkBotEventType.MESSAGE_NEW: log.info( f'мы пока не умеем обрабатывать событие такого типы {event.type}' ) return user_id = event.object.message['from_id'] text = event.object.message["text"] state = UserState.get(user_id=str(user_id)) # user_id = event.object.message['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.INTENT: log.debug(f'User gets {intent}') if any(token in text.lower() for token in intent['tokens']): if intent['answer']: self.send_to_text(peer_id=user_id, text_to_send=intent['answer']) # run intent else: self.start_scenario(scenario_name=intent['scenario'], text=text, user_id=user_id) # если у # интента нет ответа - значит мы запускаем сценарий регистрации break else: self.send_to_text(peer_id=user_id, text_to_send=settings.DEFAULT_ANSWERS ) # если у интента нет
def on_event(self, event): """ Обрабатывает введенные данные :param event: VkBotMessageEvent object """ 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=user_id) if text in settings.COMMANDS: self.check_intents(user_id, text) elif state is not None: self.continue_scenario(text, state, user_id) else: self.check_intents(user_id, text)
def on_event(self, event): if event.type != VkBotEventType.MESSAGE_NEW: return user_id = event.object.message['peer_id'] text = event.object.message['text'] if int(user_id) - 2 * 10**9 < 0: state = UserState.get(user_id=str(user_id)) if state is not None: text_to_send = self.continue_scenario(text=text, state=state) else: for intent in settings.INTENTS: 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.send_message(text_to_send, user_id) else: 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_message(text_to_send, user_id) if intent['group_handler']: handler = getattr(handlers, intent['group_handler']) text_to_send = handler(text) if text_to_send: self.send_message(text_to_send, user_id) if text == '/Семен': print('ok') self.api.messages.send(random_id=random.randint(0, 2**20), peer_id=user_id, attachment='photo-197891905_457239039')