예제 #1
0
def handle_messages():
    payload = request.get_data()
    webhook_type = get_type_from_payload(payload)

    # Handle messages
    if webhook_type == 'message':
        for sender_id, message in messaging_events(payload):
            # Only process message in here
            if not message:
                return 'ok'

            print(f'Received : {json.dumps(message, indent=4)}')
            # Start processing valid requests
            try:
                FacebookAPI.show_typing(sender_id)
                if message['type'] == 'text':
                    NLP.process_message(sender_id, message['data'])
                elif message['type'] == 'quick_reply':
                    NLP.process_quick_reply(sender_id, message['data'])
                else:
                    Multimedia.process_message(sender_id, message)

            except Exception as e:
                print('EXCEPTION ' + str(e))
                traceback.print_exc()

    return 'ok'
예제 #2
0
def process_message(results, cli):
    print('WEATHER REQUEST')
    (context, output, message) = results

    json_context = json.dumps(context, indent=2)
    Client.update_client_context(cli.id, json_context)

    for m in output:
        if m == '[OK] Process request':
            print(f"LOCATION = {context['location']}")
            coordinates = (context['location'] == ' or coordinates')
            if not coordinates:
                context['location'] = process_keyword(context['location']) 
                print(f"LOCATION = {context['location']}")

            if context['date'] is None and context['time'] is None:
                if context['type'] == 'weather':
                    current_weather(context, cli, coordinates)
                elif context['type'] == 'forecast':
                    next_days_forecast(context, cli, coordinates)
            elif context['time'] is not None:
                simple_forecast(context, cli, coordinates, True)
            else:
                simple_forecast(context, cli, coordinates)
        elif m == 'Can you give me a location?':
            FacebookAPI.send_quick_replies(cli.id, WeatherMB.quick_reply_location(), m)
        elif m != '':
            FacebookAPI.send_message(cli.id, m)
예제 #3
0
def current_weather(context, cli, coordinates):
    if coordinates:
        prevision = WeatherAPI.getCurrentWeatherCoordinates(context['lat'], context['long'])
    else:
        prevision = WeatherAPI.getCurrentWeatherCity(context['location'])
    icon, title, subtitle = WeatherMB.generateCurrentWeatherInfo(prevision)
    FacebookAPI.send_picture(cli.id, icon, title, subtitle)
예제 #4
0
def send_reminder(cli, word, description):
    new_context = {'word': word, 'description': description}
    json_context = json.dumps(new_context, indent=2)
    Client.update_client_context(cli, json_context)
    print(json_context)
    FacebookAPI.send_quick_replies(
        cli, ReminderMB.reminder_quick_replies(),
        ReminderMB.getDescription(word, description))
예제 #5
0
def next_days_forecast(context, cli, coordinates):
    if coordinates:
        prevision = WeatherAPI.getForecastCoordinates(context['lat'], context['long'])
    else:
        prevision = WeatherAPI.getForecastCity(context['location'])
    elements = WeatherMB.generateForecastPosts(prevision)
    FacebookAPI.send_list(cli.id, elements)
    Client.update_client_context(cli.id, None)
예제 #6
0
def register_events(context, cli, session):
    credentials = google.oauth2.credentials.Credentials(**session.credentials)
    Session.update_session(cli.id, credentials)
    calendar_service = __start_service('calendar', 'v3', credentials)   
    
    event = CalendarMB.generate_event(context)
    CalendarAPI.regist_event(calendar_service, event)   
    FacebookAPI.send_message(cli.id, 'The event is registered =D')               # register the above event example
    Client.end_context(cli.id)                 
예제 #7
0
def send_info(results, cli):
    print('INFO REQUEST')
    (context, output, _) = results

    for m in output:
        if m != '':
            FacebookAPI.send_message(cli.id, m)
            Client.update_client_context(cli.id, None)
            cli.context = None
예제 #8
0
def __invalid_request(results, cli):
    print('ANYTHING ELSE')
    (newContext, output, _) = results
    json_newContext = json.dumps(newContext, indent=2)
    Client.update_client_context(cli.id, json_newContext)

    for m in output:
        FacebookAPI.send_message(cli.id, m)

    FacebookAPI.send_quick_replies(cli.id, NLPMB.quick_reply_features(),
                                   "Here's all the features, enjoy!")
예제 #9
0
def list_events(context, cli, session):
    credentials = google.oauth2.credentials.Credentials(**session.credentials)
    Session.update_session(cli.id, credentials)
    calendar_service = __start_service('calendar', 'v3', credentials)        
    
    if context['number'] is not None:
        events = CalendarAPI.list_events(calendar_service, int(context['number'])) 
    else:
        events = CalendarAPI.list_events(calendar_service, 3)         
    elements = CalendarMB.list_events(events)
    FacebookAPI.send_carousel(cli.id, elements)  
    Client.end_context(cli.id)                 
예제 #10
0
def process_message(user_id, message):
    # Location message type
    if message['type'] == 'location':
        coordinates = message['data']
        #__select_action(user_id, coordinates['lat'], coordinates['long'])
        NLP.process_message(
            user_id, f"coord({coordinates['lat']},{coordinates['long']})")

    # Image message type TODO
    elif message['type'] == 'image':
        image_url = message['data']
        FacebookAPI.send_picture(user_id, image_url)

    # Audio message type
    elif message['type'] == 'audio':
        audio_url = message['data']
        response = SpeechAPI.send_audio(audio_url)
        FacebookAPI.send_message(
            user_id, "I understood: " +
            response)  # TODO remove this (just to see the results)
        NLP.process_message(user_id, response)

    # Video message type TODO
    elif message['type'] == 'video':
        video_url = message['data']
        FacebookAPI.send_message(user_id,
                                 "I've received your video: %s" % (video_url))

    # File message type TODO
    elif message['type'] == 'file':
        file_url = message['data']
        FacebookAPI.send_message(user_id,
                                 "I've received your file: %s" % (file_url))

    # Unrecognizable incoming
    else:
        FacebookAPI.send_message(user_id, 'What?')


# select the action related to user context -> NOT USED
#def __select_action(user_id, lat, long):
#    client = Client.get_client(user_id)

# handling a weather request with the localization
#    if client.context['node'] == 'WeatherRequest':
#        response = WeatherAPI.getCurrentWeatherCoordinates(lat, long)
#        icon, title, subtitle = WeatherMB.generateCurrentWeatherInfo(response)
#        FacebookAPI.send_picture(user_id, icon, title, subtitle)

#    else:
#        FacebookAPI.send_message(user_id, 'I know where you are :)')
예제 #11
0
def process_message(results, cli):
    print('NEWS REQUEST')
    (newContext, output, message) = results

    json_newContext = json.dumps(newContext, indent=2)
    Client.update_client_context(cli.id, json_newContext)

    for m in output:
        if m == '[OK] Process request':
            print(f"ORIGINAL KEYWORD: {newContext['keyword']}")
            keyword = process_keyword(newContext['keyword'])
            print(f'RESULT KEYWORD: {keyword}')
            send_news(keyword, cli)
        elif m != '':
            FacebookAPI.send_message(cli.id, m)
예제 #12
0
def send_news(keyword, cli):
    if keyword:
        print(f"KEYWORD: {keyword}")
        news = NewsAPI.getTopHeadlines(keyword)
    else:
        print(f"KEYWORD: NULL")
        news = NewsAPI.getTopHeadlines()

    elements = NewsMB.generateNewsPosts(news)
    if len(elements) == 0:
        FacebookAPI.send_message(
            cli.id,
            f"Sorry but I couldn't find anything related to your keyword: {keyword}"
        )
    else:
        FacebookAPI.send_carousel(cli.id, elements)
    Client.update_client_context(cli.id, None)
    cli.context = None
예제 #13
0
def process_message(results, cli):
    print('EMAIL REQUEST')
    (newContext, output, message) = results

    json_newContext = json.dumps(newContext, indent=2)
    session = Session.get_session(cli.id)

    if not session:
        msg = GmailMB.generate_login(cli.id)
        FacebookAPI.send_carousel(cli.id, msg)
        Client.update_client_last_msg(cli.id, message)
    else:
        Client.update_client_context(cli.id, json_newContext)
        for m in output:
            if m == '[OK] Process request':
                send_mail(newContext, cli, session)
            elif m != '':
                FacebookAPI.send_message(cli.id, m)
예제 #14
0
def oauth2callback():
    state = session['state']
    client_id = session['client_id']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRET_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = url_for('oauth2callback', _external=True)

    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    credentials = flow.credentials
    Session.insert_session(client_id, state, credentials)

    FacebookAPI.send_message(client_id, 'You\'re logged in! 😁')
    cli = Client.get_client(client_id)
    NLP.process_message(client_id, cli.last_msg)

    return '<h1>Login succeeded.</h1><br><h3>Back to the Messenger!</h3>', 200
예제 #15
0
def send_mail(context, cli, session):
    # Load credentials from the session.
    credentials = google.oauth2.credentials.Credentials(**session.credentials)
    Session.update_session(cli.id, credentials)

    user_info_service = __start_service('oauth2', 'v2', credentials)
    user_email, user_name = GmailAPI.user_email(
        user_info_service)  # get user email

    gmail_service = __start_service('gmail', 'v1', credentials)
    (msg, subject, info) = GmailMB.generate_email(user_email, user_name,
                                                  context)
    GmailAPI.send_mail(gmail_service, 'me', msg)

    img_path = url_for('static',
                       filename=f'assets/img/mail/send.png',
                       _external=True)
    FacebookAPI.send_picture(cli.id, img_path, subject, info)
    FacebookAPI.send_message(cli.id, 'E-mail sent :)')
    Client.update_client_context(cli.id, None)
예제 #16
0
def process_message(results, cli):
    print('REMINDER REQUEST')
    (context, output, _) = results

    json_context = json.dumps(context, indent=2)
    Client.update_client_context(cli.id, json_context)

    for m in output:
        if m == '[OK] Process request':
            datetime = f"{context['date']} {context['time']}"
            word = context['word']
            description = context['description']
            print(datetime)

            SchedulerAPI.schedule_remind(datetime, cli.id, word, description)
            if context['flag'] == 'schedule':
                FacebookAPI.send_message(
                    cli.id,
                    f'I received your request to remind you {word} {description}{ReminderMB.getDatetimeDescription(datetime)}.'
                )
            elif context['flag'] == 'reschedule':
                FacebookAPI.send_message(
                    cli.id,
                    f'I\'ll remind you {word} {description}{ReminderMB.getDatetimeDescription(datetime)} then.'
                )
            Client.update_client_context(cli.id, None)
            cli.context = None

        elif m != '':
            FacebookAPI.send_message(cli.id, m)
예제 #17
0
def simple_forecast(context, cli, coordinates, hour=False):
    if coordinates:
        prevision = WeatherAPI.getForecastCoordinates(context['lat'], context['long'])
    else:
        prevision = WeatherAPI.getForecastCity(context['location'])

    if hour:
        icon, title, subtitle = WeatherMB.generateSimpleForecastDay(prevision, context['date'], context['time'])
        FacebookAPI.send_picture(cli.id, icon, title, subtitle)
    else:
        current_day = datetime.date.today().strftime('%y-%m-%d')
        current_hour = datetime.datetime.now().strftime('%H')

        if current_day in context['date']:
            if current_hour < '03:00:00':
                elements = WeatherMB.generateForecastDay(prevision, context['date'])
            else:
                elements = WeatherMB.generateForecastDay(prevision, context['date'], True)
        else:
            elements = WeatherMB.generateForecastDay(prevision, context['date'])
        FacebookAPI.send_list(cli.id, elements)
    Client.update_client_context(cli.id, None)