Пример #1
0
def reply_handler(request):
    message = "Sorry, I couldn't tell which tweet you want to reply to. "
    slots = request.get_slot_map()
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if not slots["Tweet"]:
        return reply_focus_handler(request)
    else:
        can_reply = False
        if slots['Tweet'] and not (slots['Ordinal'] or slots['Index']):
            user_state = twitter_cache.get_user_state(request.access_token())
            if 'focus_tweet' in user_state: # User is focused on a tweet
                can_reply = True
        else:
            index = focused_on_tweet(request)
            if index: can_reply = True

        if can_reply: # Successfully focused on a tweet
            index, focus_tweet = user_state['focus_tweet']
            tweet_message = "@{0} {1}".format(focus_tweet.get_screen_name(),
                                          slots['Tweet'])
            params = {"in_reply_to_status_id": focus_tweet.get_id()}
            
            def action():
                print ("Performing action! lambda functions are awesome!")
                message = post_tweet(request.access_token(), tweet_message, params)
                del user_state['focus_tweet']
                return message

            should_end_session = False
            message = "I am ready to post the tweet, {}. Please say yes to confirm or stop to cancel.".format(slots['Tweet'])
            user_state['pending_action'] = {"action" : action,
                                            "description" : message }

    return alexa.create_response(message=message, end_session=should_end_session)
Пример #2
0
def find_trends_handler(request):

    uid = request.access_token()
    user_cache = twitter_cache.get_user_state(uid)
    resolved_location = False
    message = ""
    location = request.get_slot_value("Location")
    should_end_session = True

    if not location:
        # Get trends for user's current location
        user_details = get_user_twitter_details(uid)        
        location = user_details[0]['location'] 
        if location:
            message += "Finding trends near you . "
        else:
            message += "I could not figure out where you are, please set it up on your twitter account . "

    if location:

        response = geo_search(request.access_token(), location) # convert natural language text to location
        top_result = response['result']['places'][0]
        lon, lat = top_result['centroid'] 
        trend_params = {"lat" : lat, "long" : lon}
        trend_location = closest_trend_search(request.access_token(), trend_params) # find closest woeid which has trends
        woeid = trend_location[0]['woeid']
        trends = list_trends(request.access_token(), trend_location[0]['woeid']) # List top trends
        trend_lst = [trend['name'] for trend in trends[0]['trends']]
        message += "The top trending topics near {0} are, ".format(trend_location[0]['name'])
        message += "\n".join(["{0}, {1}, ".format(index+1, trend) for index, trend in enumerate(trend_lst)])

    return alexa.create_response(message=message, end_session=should_end_session)
Пример #3
0
def focused_on_tweet(request):
    """
    Return index if focused on tweet False if couldn't
    """
    slots = request.get_slot_map()
    if "Index" in slots and slots["Index"]:
        index = int(slots['Index'])

    elif "Ordinal" in slots and slots["Index"]:
        parse_ordinal = lambda inp: int("".join(
            [l for l in inp if l in string.digits]))
        index = parse_ordinal(slots['Ordinal'])
    else:
        return False

    index = index - 1  # Going from regular notation to CS notation
    user_state = twitter_cache.get_user_state(request.access_token())
    queue = user_state['user_queue'].queue()
    if index < len(queue):
        # Analyze tweet in queue
        tweet_to_analyze = queue[index]
        user_state['focus_tweet'] = tweet_to_analyze
        return index + 1  # Returning to regular notation
        twitter_cache.serialize()
    return False
Пример #4
0
def post_tweet_intent_handler(request):
    """
    Use the 'intent' field in the VoiceHandler to map to the respective intent.
    """
    tweet = request.get_slot_value("Tweet")
    tweet = tweet if tweet else ""
    if tweet:
        user_state = twitter_cache.get_user_state(request.access_token())

        def action():
            return post_tweet(request.access_token(), tweet)

        message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(
            tweet)
        user_state['pending_action'] = {
            "action": action,
            "description": message
        }
        return r.create_response(message=message, end_session=False)
    else:
        # No tweet could be disambiguated
        message = " ".join([
            "I'm sorry, I couldn't understand what you wanted to tweet .",
            "Please prepend the message with either post or tweet ."
        ])
        return alexa.create_response(message=message, end_session=False)
Пример #5
0
def launch_request_handler(request):
    """ Annotate functions with @VoiceHandler so that they can be automatically mapped 
    to request types. Use the 'request_type' field to map them to non-intent requests """

    user_id = request.access_token()
    if user_id in twitter_cache.users():

        user_cache = twitter_cache.get_user_state(user_id)
        user_cache["amzn_id"] = request.user_id()
        base_message = "Welcome to Twitter, {} . How may I help you today ?".format(
            user_cache["screen_name"])
        print(user_cache)
        if 'pending_action' in user_cache:
            base_message += " You have one pending action . "
            print("Found pending action")
            if 'description' in user_cache['pending_action']:
                print("Found description")
                base_message += user_cache['pending_action']['description']
        return r.create_response(base_message)

    card = r.create_card(title="Please log into twitter",
                         card_type="LinkAccount")
    return r.create_response(
        message="Welcome to twitter, looks like you haven't logged in!"
        " Log in via the alexa app.",
        card_obj=card,
        end_session=True)
Пример #6
0
def more_info_handler(request):
    index = focused_on_tweet(request)
    if index:
        user_state = twitter_cache.get_user_state(request.access_token())
        index, tweet = user_state['focus_tweet']
        message = " ".join(["details about tweet number {}.".format(index+1), tweet.detailed_description(), 
                            "To reply, say 'reply' followed by your message"])
        return alexa.create_response(message=message, end_session=False)
    return reply_focus_handler(request)
Пример #7
0
def cancel_action_handler(request):
    message = "okay."
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if 'pending_action' in user_state:
        del user_state['pending_action'] # Clearing out the user's pending action
        print ("cleared user_state")
        message += " i won't do it. would you like me to do something else ? "
        should_end_session = False
    return r.create_response(message, end_session=should_end_session)
Пример #8
0
def cancel_action_handler(request):
    message = "okay."
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if 'pending_action' in user_state:
        del user_state[
            'pending_action']  # Clearing out the user's pending action
        print("cleared user_state")
        message += " i won't do it. would you like me to do something else ? "
        should_end_session = False
    return r.create_response(message, end_session=should_end_session)
Пример #9
0
def more_info_handler(request):
    index = focused_on_tweet(request)
    if index:
        user_state = twitter_cache.get_user_state(request.access_token())
        index, tweet = user_state['focus_tweet']
        message = " ".join([
            "details about tweet number {}.".format(index + 1),
            tweet.detailed_description(),
            "To reply, say 'reply' followed by your message"
        ])
        return alexa.create_response(message=message, end_session=False)
    return reply_focus_handler(request)
Пример #10
0
def reply_handler(request):
    message = "Sorry, I couldn't tell which tweet you want to reply to. "
    slots = request.get_slot_map()
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if not slots["Tweet"]:
        return reply_focus_handler(request)
    else:
        can_reply = False
        if slots['Tweet'] and not (slots['Ordinal'] or slots['Index']):
            user_state = twitter_cache.get_user_state(request.access_token())
            if 'focus_tweet' in user_state:  # User is focused on a tweet
                can_reply = True
        else:
            index = focused_on_tweet(request)
            if index: can_reply = True

        if can_reply:  # Successfully focused on a tweet
            index, focus_tweet = user_state['focus_tweet']
            tweet_message = "@{0} {1}".format(focus_tweet.get_screen_name(),
                                              slots['Tweet'])
            params = {"in_reply_to_status_id": focus_tweet.get_id()}

            def action():
                print("Performing action! lambda functions are awesome!")
                message = post_tweet(request.access_token(), tweet_message,
                                     params)
                del user_state['focus_tweet']
                return message

            should_end_session = False
            message = "I am ready to post the tweet, {}. Please say yes to confirm or stop to cancel.".format(
                slots['Tweet'])
            user_state['pending_action'] = {
                "action": action,
                "description": message
            }

    return alexa.create_response(message=message,
                                 end_session=should_end_session)
Пример #11
0
def confirm_action_handler(request):
    message = "okay."
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if 'pending_action' in user_state:
        params = user_state['pending_action']
        # Perform action
        message = params['action']()
        if 'message' in params:
            message = params['message']
        if 'callback' in params:
            params['callback']()
        del user_state['pending_action']
        print ("successfully executed command")
        message = message + " would you like me to do anything else ? "
        should_end_session = False
    return alexa.create_response(message, end_session=should_end_session)
Пример #12
0
def confirm_action_handler(request):
    message = "okay."
    user_state = twitter_cache.get_user_state(request.access_token())
    should_end_session = True
    if 'pending_action' in user_state:
        params = user_state['pending_action']
        # Perform action
        message = params['action']()
        if 'message' in params:
            message = params['message']
        if 'callback' in params:
            params['callback']()
        del user_state['pending_action']
        print("successfully executed command")
        message = message + " would you like me to do anything else ? "
        should_end_session = False
    return alexa.create_response(message, end_session=should_end_session)
Пример #13
0
def find_trends_handler(request):

    uid = request.access_token()
    user_cache = twitter_cache.get_user_state(uid)
    resolved_location = False
    message = ""
    location = request.get_slot_value("Location")
    should_end_session = True

    if not location:
        # Get trends for user's current location
        user_details = get_user_twitter_details(uid)
        location = user_details[0]['location']
        if location:
            message += "Finding trends near you . "
        else:
            message += "I could not figure out where you are, please set it up on your twitter account . "

    if location:

        response = geo_search(
            request.access_token(),
            location)  # convert natural language text to location
        top_result = response['result']['places'][0]
        lon, lat = top_result['centroid']
        trend_params = {"lat": lat, "long": lon}
        trend_location = closest_trend_search(
            request.access_token(),
            trend_params)  # find closest woeid which has trends
        woeid = trend_location[0]['woeid']
        trends = list_trends(request.access_token(),
                             trend_location[0]['woeid'])  # List top trends
        trend_lst = [trend['name'] for trend in trends[0]['trends']]
        message += "The top trending topics near {0} are, ".format(
            trend_location[0]['name'])
        message += "\n".join([
            "{0}, {1}, ".format(index + 1, trend)
            for index, trend in enumerate(trend_lst)
        ])

    return alexa.create_response(message=message,
                                 end_session=should_end_session)
Пример #14
0
def launch_request_handler(request):
    """ Annotate functions with @VoiceHandler so that they can be automatically mapped 
    to request types. Use the 'request_type' field to map them to non-intent requests """

    user_id = request.access_token()
    if user_id in twitter_cache.users():

        user_cache = twitter_cache.get_user_state(user_id)        
        user_cache["amzn_id"]= request.user_id()
        base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"])
        print (user_cache)        
        if 'pending_action' in user_cache:
            base_message += " You have one pending action . "
            print ("Found pending action")
            if 'description' in user_cache['pending_action']:
                print ("Found description")
                base_message += user_cache['pending_action']['description']
        return r.create_response(base_message)

    card = r.create_card(title="Please log into twitter", card_type="LinkAccount")
    return r.create_response(message="Welcome to twitter, looks like you haven't logged in!"
                             " Log in via the alexa app.", card_obj=card,
                             end_session=True)
Пример #15
0
def post_tweet_intent_handler(request):
    """
    Use the 'intent' field in the VoiceHandler to map to the respective intent.
    """
    tweet = request.get_slot_value("Tweet")
    tweet = tweet if tweet else ""    
    if tweet:
        user_state = twitter_cache.get_user_state(request.access_token())
        def action():
            return post_tweet(request.access_token(), tweet)

        message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(tweet)
        user_state['pending_action'] = {"action" : action,
                                        "description" : message} 
        return r.create_response(message=message, end_session=False)
    else:
        # No tweet could be disambiguated
        message = " ".join(
            [
                "I'm sorry, I couldn't understand what you wanted to tweet .",
                "Please prepend the message with either post or tweet ."
            ]
        )
        return alexa.create_response(message=message, end_session=False)
Пример #16
0
def focused_on_tweet(request):
    """
    Return index if focused on tweet False if couldn't
    """
    slots = request.get_slot_map()
    if "Index" in slots and slots["Index"]:
        index = int(slots['Index'])

    elif "Ordinal" in slots and slots["Index"]:
        parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits]))
        index = parse_ordinal(slots['Ordinal'])
    else:
        return False
        
    index = index - 1 # Going from regular notation to CS notation
    user_state = twitter_cache.get_user_state(request.access_token())
    queue = user_state['user_queue'].queue()
    if index < len(queue):
        # Analyze tweet in queue
        tweet_to_analyze = queue[index]
        user_state['focus_tweet'] = tweet_to_analyze
        return index + 1 # Returning to regular notation
        twitter_cache.serialize()
    return False