Exemple #1
0
    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('Getting information about current search')
            response = requests.get(
                'http://172.20.128.4:5001/search/{0}'.format(session.userId))
            if response.status_code == 200:
                searchingInfo = 'В данный момент происходит поиск билета из {sourceCity} в {targetCity}, дата - {date}'.format(
                    sourceCity=response.json()['sourceCity'],
                    targetCity=response.json()['targetCity'],
                    date=response.json()['date'])
                payload = {
                    'user_id': session.userId,
                    'message': searchingInfo,
                }
                logger.info('Sending data about current search')
                apiRequest('messages.send', payload)

        except requests.exceptions.RequestException as e:
            logger.error(e)
Exemple #2
0
def receiveMessage():
    """
    Api endpoint to handle new message from user.

    :return: api response with status code
    :rtype: Response
    """
    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('Got "{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")
        }
        logger.info('Sending instructions to user')
        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)
Exemple #3
0
    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:
            response = requests.get(
                'http://172.20.128.4:5001/search/{0}'.format(session.userId))
            if response.status_code == 200:
                requests.delete('http://172.20.128.4:5001/search/{0}'.format(
                    session.userId))

            data = {
                'sourceCity': session.sourceCity,
                'targetCity': session.targetCity,
                'price': session.price,
                'date': session.date,
                'userId': session.userId
            }
            requests.post('http://172.20.128.4:5001/search', json=data)
Exemple #4
0
    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)
Exemple #5
0
    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)
Exemple #6
0
    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)
Exemple #7
0
    def run(self):
        tries = 0
        price = self.price
        global searchingTasks
        filters = [filter_onlyDirect]
        trip = RequestData([{
            'origin': cities[self.sourceCity],
            'destination': cities[self.targetCity],
            'date': self.date
        }])

        for itineraries in self.scanner.scan(filters, trip=trip, useProxy=True):
            try:
                cheapestOption = itineraries[0].getCheapestPriceOptions()[0]
                for itinerarie in itineraries:
                    if itinerarie.getCheapestPriceOptions()[0] < cheapestOption:
                        cheapestOption = itinerarie.getCheapestPriceOptions()[0]
            except Exception as _:
                continue

            response = apiRequest('utils.getShortLink', {'url': cheapestOption.getLinkForBuying()})
            if int(cheapestOption) < price or (tries == 30 and int(cheapestOption) < self.price):
                price = int(cheapestOption)
                message = 'Pricing option: {option};\n\n Link: {link}'.format(
                    option=cheapestOption,
                    link=response['response']['short_url']
                )
                requests.post('http://172.20.128.3:5000/send', json={'userId': self.userId, 'message': message})
                tries = 0

            if self.stopThread:
                break

            time.sleep(10)
            tries += 1
Exemple #8
0
def sendMessage():
    """
    Api endpoint to send message from bot to user

    :return: api response with status code
    :rtype: Response
    """
    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']