Esempio n. 1
0
def handle_attachments(event):

    recipient_id = int(event['sender']['id'])
    try:
        lat = (event['message']['attachments'][0]['payload']['coordinates']
               ['lat'])
        lng = (event['message']['attachments'][0]['payload']['coordinates']
               ['long'])
        u_info = get_by_recipient_id(recipient_id)
        u_info.cur_lat = float(lat)
        u_info.cur_lng = float(lng)
        u_info.put()
        back_payload = u_info.last_callback
        if back_payload and back_payload.startswith('seances'):
            if back_payload.find('num') != -1:
                i_n, l_n = back_payload.index('num'), len('num')
                movie_id = back_payload[len('seances'):i_n]
                starting_n = (back_payload[i_n + l_n:len(back_payload)])
            else:
                movie_id = back_payload[len('seances'):]
                starting_n = 0
            u_info = get_by_recipient_id(recipient_id)
            payload = display_cinema_seances_short(recipient_id, movie_id,
                                                   starting_n, u_info.cur_lat,
                                                   u_info.cur_lng)
            return payload
        else:
            message = 'Ваши геоданные были успешно изменены'
            payload = _construct_payload(message, recipient_id)
            return payload
    except Exception:
        message = settings.SORRY_DONT_PROCEED
        payload = _construct_payload(message, recipient_id)
        return payload
Esempio n. 2
0
def update_last_callback(recipient_id):
    u_info = get_by_recipient_id(recipient_id)
    u_info.last_callback = ''
    u_info.put()
Esempio n. 3
0
    def post(self):
        income_json = json.loads(self.request.body)
        events = income_json['entry'][0]['messaging']
        for event in events:
            recipient_id = int(event['sender']['id'])
            if event.get('message') and event['message'].get('attachments'):
                try:
                    typing = _typing_payload(recipient_id)
                    _send_payload(typing)
                    payloads = handle_attachments(event)
                    if isinstance(payloads, list):
                        for payload in payloads:
                            resp = _send_payload(payload)
                    else:
                        resp = _send_payload(payloads)
                    self.response.write(resp)
                    return
                except:
                    self.response.write('200')

            if event.get('message') and event['message'].get('quick_reply'):
                try:
                    update_last_callback(recipient_id)
                    payload = event['message']['quick_reply']['payload']
                    recipient_id = int(event['sender']['id'])
                    typing = _typing_payload(recipient_id)
                    _send_payload(typing)

                    payloads = handle_quick_reply(payload, recipient_id)
                    if isinstance(payloads, list):
                        for payload in payloads:
                            resp = _send_payload(payload)
                    else:
                        resp = _send_payload(payloads)
                    self.response.write(resp)
                    return
                except:
                    self.response.write('200')

            if event.get('postback') and event['postback'].get('payload'):
                try:
                    typing = _typing_payload(recipient_id)
                    _send_payload(typing)
                    update_last_callback(recipient_id)
                    back_payload = event['postback']['payload']
                    recipient_id = int(event['sender']['id'])
                    payloads = handle_back_payload(back_payload, recipient_id)
                    if isinstance(payloads, list):
                        for payload in payloads:
                            resp = _send_payload(payload)
                    else:
                        resp = _send_payload(payloads)
                    self.response.write(resp)
                    return
                except:
                    self.response.write('200')

            if event.get('message') and event['message'].get('text'):
                message = event['message']['text']
                typing = _typing_payload(recipient_id)
                _send_payload(typing)
                try:
                    payload = handle_special_words(recipient_id, message)
                    if payload:
                        self.response.write(_send_payload(payload))
                        return

                    if settings.uncd(message).find(u'В прокате') != -1:
                        update_last_callback(recipient_id)

                        payload = display_running_movies(
                            recipient_id, settings.FB_FILMS_TO_DISPLAY)
                        self.response.write(_send_payload(payload))
                        return

                    u_info = get_by_recipient_id(recipient_id)
                    if u_info and u_info.last_callback:
                        payload = u_info.last_callback

                        payloads = handle_text_with_payload(
                            u_info, recipient_id, payload, message)
                        if isinstance(payloads, list):
                            for payload in payloads:
                                resp = _send_payload(payload)
                        else:
                            resp = _send_payload(payloads)
                        self.response.write(resp)
                        return
                    else:
                        typing = _typing_payload(recipient_id)
                        _send_payload(typing)
                        payload = handle_text_message(recipient_id, message)
                        self.response.write(_send_payload(payload))
                        return
                except:
                    self.response.write('200')
Esempio n. 4
0
def handle_back_payload(back_payload, recipient_id):
    if back_payload.startswith('seances'):
        payload = _construct_get_geo_payload(recipient_id)

        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = back_payload
        u_info.put()

        return payload

    elif back_payload.startswith('/c'):
        index_of_m, index_of_d = (back_payload.index('m'),
                                  back_payload.index('d'))
        cinema_id = back_payload[2:index_of_m]
        movie_id, d = (back_payload[index_of_m + 1:index_of_d],
                       back_payload[-1])

        payloads = display_cinema_seances(recipient_id, cinema_id, movie_id, d)
        u_info = get_by_recipient_id(recipient_id)

        u_info.cur_movie_id = int(movie_id)
        u_info.cur_cinema_id = int(cinema_id)
        u_info.last_callback = 'nearest'
        u_info.put()
        text = _construct_payload(settings.DISCOUNT, recipient_id)
        return [text] + payloads

    elif (back_payload.startswith('info')
          and back_payload.find('cinema') != -1):
        movie_id = int(back_payload[len('info'):back_payload.find('cinema')])
        cinema_id = int(back_payload[back_payload.find('cinema') +
                                     len('cinema'):])
        (payload, first_message, full_info,
         trailer_url) = construct_full_movie_info(movie_id, recipient_id)
        if trailer_url:
            buttons = [
                {
                    'type': 'web_url',
                    'url': trailer_url,
                    'title': 'Трейлер'
                },
                {
                    "type":
                    "postback",
                    "title":
                    "Сеансы",
                    "payload":
                    "/c{}m{}d{}".format(cinema_id, movie_id, settings.TODAY)
                },
            ]
        else:
            buttons = [{
                "type":
                "postback",
                "title":
                "Сеансы",
                "payload":
                "/c{}m{}d{}".format(cinema_id, movie_id, settings.TODAY)
            }]
        buttons = _construct_button_payload(recipient_id, full_info, buttons)

        return [payload] + [first_message] + [buttons]

    elif back_payload.startswith('info'):
        movie_id = int(back_payload[len('info'):])
        (payload, first_message, full_info,
         trailer_url) = construct_full_movie_info(movie_id, recipient_id)

        if trailer_url:
            buttons = [
                {
                    'type': 'web_url',
                    'url': trailer_url,
                    'title': 'Трейлер'
                },
                {
                    "type": "postback",
                    "title": "Сеансы",
                    "payload": "seances{}num{}".format(movie_id, 0)
                },
            ]
        else:
            buttons = [{
                "type": "postback",
                "title": "Сеансы",
                "payload": "seances{}num{}".format(movie_id, 0)
            }]
        buttons = _construct_button_payload(recipient_id, full_info, buttons)
        return [payload] + [first_message] + [buttons]

    elif back_payload == 'start':
        u_info = get_by_recipient_id(recipient_id)
        u_info.put()
        payload = display_welcome_buttons(recipient_id)
        return payload

    elif back_payload.startswith('/running'):
        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = back_payload

        u_info.cur_movie_id = None
        u_info.last_searched_movie = None
        u_info.put()
        n_movies = int(back_payload[len('/running'):])
        payload = display_running_movies(recipient_id, n_movies)
        return payload

    elif back_payload.startswith('cinema'):
        cinema_id = back_payload[len('cinema'):len(back_payload)]
        payload = display_cinema_schedule(recipient_id, cinema_id,
                                          settings.FB_FILMS_TO_DISPLAY,
                                          settings.TODAY)
        return payload

    elif back_payload.startswith('nearest'):
        number = int(back_payload[len('nearest'):len(back_payload)])
        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = back_payload
        u_info.cur_movie_id = None
        if not u_info or not u_info.cur_lat or not u_info.cur_lng:
            payload = display_nearest_cinemas(recipient_id, number)
        elif u_info.cur_lat and u_info.cur_lng:
            payload = display_nearest_cinemas(recipient_id,
                                              number,
                                              lat=u_info.cur_lat,
                                              lng=u_info.cur_lng)
        text = _construct_payload(settings.WE_OFFER_LIST, recipient_id)

        u_info.put()
        return [text] + [payload]

    elif back_payload == 'bug':
        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = back_payload
        u_info.put()

        return _construct_payload(settings.DESCRIBE_YOUR_PROBLEM, recipient_id)

    else:
        payload = support_message_generator(int(recipient_id), back_payload,
                                            support_dict)
        if not payload:
            return
        else:
            return payload
Esempio n. 5
0
def handle_quick_reply(payload, recipient_id):
    if payload.startswith('/running'):
        n_movies = int(payload[len('/running'):len(payload)])
        return display_running_movies(recipient_id, n_movies)

    elif payload.startswith('/premiere'):
        n_movies = int(payload[len('/premiere'):len(payload)])
        return display_premieres(recipient_id, n_movies)

    elif payload.startswith('/c'):
        index_of_m, index_of_d = (payload.index('m'), payload.index('d'))
        cinema_id = payload[2:index_of_m]
        movie_id, d = (payload[index_of_m + 1:index_of_d], payload[-1])
        if not d.isdigit():
            return

        if int(d) == settings.ANOTHER_FB_DAY:
            u_info = get_by_recipient_id(recipient_id)
            u_info.last_callback = payload
            u_info.put()

            message = settings.TELL_DATE
            return _construct_payload(message, recipient_id)
        else:
            payloads = display_cinema_seances(recipient_id, cinema_id,
                                              movie_id, d)
            text = _construct_payload(settings.DISCOUNT, recipient_id)
            return [text] + payloads

    elif payload.startswith('seances'):
        i_d = payload.index('d')
        i_n, l_n = payload.index('num'), len('num')
        movie_id = payload[len('seances'):i_n]
        starting_n = payload[i_n + l_n:i_d]
        date = datetime.strptime(payload[i_d + 1:len(payload)][0:10],
                                 '%Y-%m-%d')

        u_info = get_by_recipient_id(recipient_id)

        if not u_info or not u_info.cur_lat or not u_info.cur_lng:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   starting_n,
                                                   date=date)
        elif u_info.cur_lat and u_info.cur_lat:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   starting_n,
                                                   u_info.cur_lat,
                                                   u_info.cur_lng,
                                                   date=date)
        return payload

    elif payload == 'refuse_geo':
        update_last_callback(recipient_id)
        u_info = get_by_recipient_id(recipient_id)
        movie_id = u_info.cur_movie_id

        payload = display_cinema_seances_short(recipient_id, movie_id, 0)
        return payload

    elif payload.startswith('nearest'):
        number = int(payload[len('nearest'):len(payload)])
        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = payload
        # movie_id = u_info.cur_movie_id dg
        if not u_info or not u_info.cur_lat or not u_info.cur_lng:
            payload = display_nearest_cinemas(recipient_id, number)
        elif u_info.cur_lat and u_info.cur_lng:
            payload = display_nearest_cinemas(recipient_id,
                                              number,
                                              lat=u_info.cur_lat,
                                              lng=u_info.cur_lng)
        text = _construct_payload(settings.CINEMA_LIST, recipient_id)
        u_info.put()
        return [text] + [payload]

    elif payload.startswith('cinema'):
        i_d = payload.index('d')
        i_n, l_n = payload.index('num'), len('num')
        cinema_id = payload[len('cinema'):i_n]
        starting_n = payload[i_n + l_n:i_d]
        day = payload[i_d + 1:len(payload)]
        payload = display_cinema_schedule(recipient_id, cinema_id,
                                          int(starting_n), day)

        return payload

    elif payload.startswith('s_short'):
        i_d = payload.index('d')
        u_info = get_by_recipient_id(recipient_id)
        u_info.last_callback = payload
        u_info.put()

        message = settings.TELL_DATE
        return _construct_payload(message, recipient_id)
Esempio n. 6
0
def handle_text_with_payload(u_info, recipient_id, payload, message):
    if payload.startswith('/c'):
        seance_date = Parser.detect_time(message.encode('utf-8'))
        index_of_m, index_of_d = (payload.index('m'), payload.index('d'))
        cinema_id = payload[2:index_of_m]
        movie_id = (payload[index_of_m + 1:index_of_d])
        payloads = display_cinema_seances(recipient_id, cinema_id, movie_id,
                                          seance_date)

        text = _construct_payload(settings.DISCOUNT, recipient_id)
        update_last_callback(recipient_id)
        return [text] + payloads

    elif payload.startswith('seances'):
        if 'num' in payload:
            i_n = payload.index('num')
        else:
            return
        movie_id = payload[len('seances'):i_n]
        city_id = 1
        u_f = get_by_recipient_id(recipient_id)
        if u_f and u_f.cur_lat and u_f.cur_lng:
            l = {'latitude': u_f.cur_lat, 'longitude': u_f.cur_lng}
            city_id = detect_city_id_by_location(l)

        parser = Parser(message.encode('utf-8'), 'cinema', city_id=city_id)

        parser.parse()
        data = parser.data.place
        cinemas = []
        if not data:
            res = _construct_payload('К сожалению, мы ничего не нашли',
                                     recipient_id)
            return res
        for c in data:
            if not isinstance(c, dict):
                c = c.to_dict()

            c_info = _construct_cinema_movie_generic(c, movie_id)
            cinemas.append(c_info)
        payload = contruct_cinemas(recipient_id, cinemas, 10)
        payload = json.dumps(payload)
        update_last_callback(recipient_id)
        return payload

    elif payload.startswith('s_short'):
        seance_date = Parser.detect_time(message.encode('utf-8'))
        i_d = payload.index('d')
        movie_id = payload[len('s_short'):i_d]

        if u_info and u_info.cur_lat and u_info.cur_lng:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   lat=u_info.cur_lat,
                                                   lng=u_info.cur_lng,
                                                   date=seance_date.date())
        else:
            payload = display_cinema_seances_short(recipient_id,
                                                   movie_id,
                                                   date=seance_date.date())
        return payload

    elif payload == 'bug':
        if len(message) > 2:
            u_info.bug_description = message
            u_info.last_callback = 'bug_email'
            u_info.put()

            resp = _construct_payload('Введите ваш email', recipient_id)
            return resp

        else:
            resp = _construct_payload('Опишите проблему', recipient_id)
            return resp

    elif validate_email(settings.uncd(message)):
        email = settings.uncd(message)
        u_info = get_by_recipient_id(recipient_id)

        if (u_info.last_callback == NO_AGAIN_CALLBACK
                or u_info.last_callback == NO_MAIL_SENDED_CALLBACK
                or u_info.last_callback == ANOTHER_PAY_ER_CALLBACK):
            last_callback = u_info.last_callback
            deferred.deffer(send_email, email, last_callback)
            our_spec = 'Наш специалист скоро свяжется с Вами'
            payload = _construct_payload(our_spec, recipient_id)

            return payload

        elif u_info.last_callback == 'bug_email':
            deferred.defer(send_email, email, u_info.bug_description)
            our_spec = 'Спасибо :)'
            payload = _construct_payload(our_spec, recipient_id)
            return payload

        else:
            payload = _construct_payload(settings.SORRY_I_DONT_UNDERSTAND,
                                         recipient_id)
            return payload

    else:
        payload = handle_text_message(recipient_id, message)
        return payload
Esempio n. 7
0
def handle_text_message(recipient_id, message):
    city_id = 1
    u_f = get_by_recipient_id(recipient_id)
    if u_f and u_f.cur_lat and u_f.cur_lng:
        l = {'latitude': u_f.cur_lat, 'longitude': u_f.cur_lng}
        city_id = detect_city_id_by_location(l)
    parser = Parser(message.encode('utf-8'), 'base', city_id=city_id)
    parser.parse()
    film = parser.data.what
    place = parser.data.place
    if not check_film_screens(film) or (not film and not place):
        parser.parser_special()
        film = parser.data.genre

    if film:
        movies = []

        for f in film:

            if not isinstance(f, dict):
                f = f.to_dict()
            my_id = 'kinohod_id' if 'kinohod_id' in f else 'id'

            (description, poster, trailer_url) = display_movie_info(f[my_id])

            f_info = construct_film_info(poster, description, trailer_url, f)

            movies.append(f_info)

            if len(movies) == settings.FILMS_TO_DISPLAY:
                break

        if len(movies) == 0:
            res = _construct_payload(settings.SORRY_FOUND_NOTHING,
                                     recipient_id)

            return res

        payload = json.dumps(
            construct_final_payload(recipient_id, movies,
                                    settings.FB_FILMS_TO_DISPLAY))
        return payload

    elif place:

        place = parser.data.place
        cinemas = []
        for c in place:
            c_info = construct_cinema_generic(c.to_dict(), recipient_id)
            cinemas.append(c_info)
        payload = contruct_cinemas(recipient_id, cinemas, 10)
        payload = json.dumps(payload)
        return payload

    else:
        search_dict = {'search': message.encode('utf-8')}
        url_encoded_dict = urllib.urlencode(search_dict)
        query_url = settings.QUERY_SEARCH_URL.format(settings.KINOHOD_API_KEY,
                                                     url_encoded_dict)

        film_kinohod_api = get_data(query_url)

        query_url_soon = query_url + '&filter=soon'
        film_kinohod_api_soon = get_data(query_url_soon)

        if film_kinohod_api:
            movies = construct_movies_list(film_kinohod_api)
            payload = json.dumps(
                construct_final_payload(recipient_id, movies,
                                        settings.FB_FILMS_TO_DISPLAY))

            return payload

        elif film_kinohod_api_soon:
            movies = construct_movies_list(film_kinohod_api_soon)
            payload = json.dumps(
                construct_final_payload(recipient_id, movies,
                                        settings.FB_FILMS_TO_DISPLAY))
            return payload

        else:
            payload = _construct_payload(settings.SORRY_I_DONT_UNDERSTAND,
                                         recipient_id)
            return payload