def _notifyUserAboutCurrentSearch(self, session): """ Notify user, if he is searching tickets now :param session: UserSession object with data :type session: UserSession :return: None """ try: logger.info('Send POST request to searchingService/is-searching') response = requests.post('http://localhost:100/is-searching', json={'userId': session.userId}) if response.json()['isSearching']: searchingInfo = 'В данный момент происходит поиск билета из {sourceCity} в {targetCity}, дата - {date}'.format( sourceCity=response.json()['searchingQuery']['sourceCity'], targetCity=response.json()['searchingQuery']['targetCity'], date=response.json()['searchingQuery']['date']) payload = { 'user_id': session.userId, 'message': searchingInfo, } apiRequest('messages.send', payload) except requests.exceptions.RequestException as e: logger.error(e)
def receiveMessage(): """ Api endpoint to handle new message from user. :return: api response with status code :rtype: Response """ logger.info('POST request to /receive endpoint') try: data = request.get_json() userSession = UserSession(data['userId']) if str(data['userId']) not in session \ else json.loads(session[str(data['userId'])], object_hook=asSession) logger.info('Execute "{0}" action'.format(data['message'])) userSession.execute(data['message']) session[str(data['userId'])] = str( json.dumps(userSession, cls=SessionEncoder)) payload = { 'user_id': data['userId'], 'message': userSession.getInstruction(), 'keyboard': json.dumps(userSession.getKeyboard(), ensure_ascii=False).encode("utf-8") } apiRequest('messages.send', payload) return Response(status=200) except requests.RequestException as e: logger.error(e) return Response(status=500) except KeyError as e: logger.error(e) return Response(status=400)
def _startSearch(self, session): """ Start search event :param session: UserSession object with data :type session: UserSession :return: None """ if not session.date or not session.price or not session.sourceCity or not session.targetCity: logger.warning('Not enough data for searching') payload = { 'user_id': session.userId, 'message': 'Введены не все данные, заполните шаблон и попробуйте снова.\n\n', } apiRequest('messages.send', payload) else: data = { 'sourceCity': session.sourceCity, 'targetCity': session.targetCity, 'price': session.price, 'date': session.date, 'userId': session.userId } logger.info('Send POST request to searchingService/start-search') requests.post('http://localhost:100/start-search', json=data)
def execute(self, action, session): """ Execute actions specific for menu object, depending on user action :param action: user input action :type action: str :param session: UserSession object with data :type session: UserSession :return: None """ if action == ButtonsEnum.BACK['action']['label']: logger.info('Execute <BACK> action') session.changeMenu(DateSelection()) elif action == ButtonsEnum.FINISH['action']['label']: logger.info('Execute <NEXT> action') session.changeMenu(MainMenu()) elif self._priceIsValid(action): logger.info('Execute <SETUP_PRICE> action') session.price = action session.changeMenu(MainMenu()) else: logger.info('Execute <INCORRECT_PRICE> action') payload = { 'user_id': session.userId, 'message': 'Некорректный формат числа.\n\n' } apiRequest('messages.send', payload)
def execute(self, action, session): """ Execute actions specific for menu object, depending on user action :param action: user input action :type action: str :param session: UserSession object with data :type session: UserSession :return: None """ if action == ButtonsEnum.BACK['action']['label']: logger.info('Execute <BACK> action') session.changeMenu(TargetCitySelection()) elif action == ButtonsEnum.NEXT['action']['label']: logger.info('Execute <NEXT> action') session.changeMenu(PriceSelection()) elif self._dateIsValid(action): logger.info('Execute <SETUP_DATE> action') session.date = action session.changeMenu(PriceSelection()) else: logger.info('Execute <INCORRECT_DATE> action') payload = { 'user_id': session.userId, 'message': 'Некорректный формат даты.', } apiRequest('messages.send', payload)
def execute(self, action, session): """ Execute actions specific for menu object, depending on user action :param action: user action :type action: str :param session: UserSession object with data :type session: UserSession :return: None """ if action == ButtonsEnum.BACK['action']['label']: logger.info('Execute <BACK> action') session.changeMenu(SourceCitySelection()) elif action == ButtonsEnum.NEXT['action']['label']: logger.info('Execute <NEXT> action') session.changeMenu(DateSelection()) elif action in cities: logger.info('Execute <SETUP_TARGET_CITY> action') session.targetCity = action session.changeMenu(DateSelection()) else: logger.info('Execute <INCORRECT_TARGET_CITY> action') payload = { 'user_id': session.userId, 'message': 'Некорректное имя города.' } apiRequest('messages.send', payload)
def sendMessage(): """ api endpoint to send message from bot to user :return: api response with status code :rtype: Response """ logger.info('POST request to /send endpoint') data = request.get_json() try: payload = { 'user_id': data['userId'], 'message': data['message'], } apiRequest('messages.send', payload) return Response(status=200) except requests.RequestException as e: logger.error(e) return Response(status=500) except KeyError as e: logger.error(e) return Response(status=400)
def _getSessionData(self, group_id, need_pts='0', lp_version='3'): """ Getting data from API to work with LongPoll :param group_id: id of vk group :param need_pts: 1 by default (to return pts field) :param lp_version: long Poll version :return: response with key, server, ts data :rtype: dict """ payload = { 'need_pts': need_pts, 'group_id': group_id, 'lp_version': lp_version, } return apiRequest('messages.getLongPollServer', payload)['response']