def get_time_slept_intent(request):
    cur_date = get_cur_date() - timedelta(days=1)

    bedtime = get_value_on_date(cur_date, ATTR_MAP["bedtime"])
    waketime = get_value_on_date(cur_date, ATTR_MAP["waketime"])
    latency = get_value_on_date(cur_date, ATTR_MAP["latency"])

    if not bedtime:
        return alexa.create_response("Sorry, looks like you didn't set a bedtime yesterday.")

    if not waketime:
        return alexa.create_response("Sorry, looks like you didn't wake up yesterday.")

    if not latency:
        latency = timedelta() # In case we didn't record latency
    else:
        h, m, s = map(int, latency.split(":"))
        latency = timedelta(hours=h, minutes=m) 

    #If bedtime is before midnight, subtract an extra day
    if bedtime[-2:] == "PM":
        bedtime = create_datetime_from_time(bedtime, cur_date - timedelta(days=1))
    else:
        bedtime = create_datetime_from_time(bedtime, cur_date)
    bedtime += latency

    waketime = create_datetime_from_time(waketime, cur_date)
    duration = waketime - bedtime
    hours = int(duration.total_seconds() / 3600)
    minutes = int((duration.total_seconds() % 3600)/60)

    response_str = "You slept {} hours and {} minutes last night, Michael.".format(hours, minutes)
    return alexa.create_response(response_str, end_session=True)
def launch_ReOrder_handler(request):
    oid = int(request.slots["orderid"])
    global ORDER
    name = ORDER['name']
    orderHandler = OrderHandler()
    orders = orderHandler.getPersonOrder(name)
    if oid in orders:
        temp = oid + 1
        sheet = '!C' + str(temp) + ':Z'
        get_order = orderHandler.getOrderNumbers(sheet)[0]
        # ORDER = OrderedDict()
        ORDER['name'] = name
        ORDER['type'] = get_order[1]
        ORDER['size'] = get_order[3]
        ORDER['crust'] = get_order[5]
        ORDER['sauce'] = get_order[7]
        ORDER['bake'] = get_order[9]
        ORDER['cut'] = get_order[11]
        ORDER['seasoning'] = get_order[13]
        ORDER['toppings'] = [
            get_order[15], get_order[17], get_order[19], get_order[21],
            get_order[23]
        ]
        ORDER['no_of_pizza'] = get_order[0]
        reply, card = checkIsReady()
        return alexa.create_response(message=reply,
                                     end_session=False,
                                     card_obj=card)
    else:
        return alexa.create_response(
            message=
            'I am sorry i dont find that order in your name. Please try again.'
        )
def set_bill_reminder_intent_handler(request):
    payee = request.get_slot_value("payee")
    payee_str = str(payee)

    payment_amount = request.get_slot_value("payment_amount")
    payment_str = str(payment_amount)
    payment_double = (int(payment_str) / 1.0)

    headers = {'Content-Type': 'application/json'}
    url = 'http://api.reimaginebanking.com/accounts/5925e4eca73e4942cdafd61d/bills?key=61892e8b6b69dca102737332a828661c'
    req = urllib2.Request(
        url,
        data=
        '{"status": "recurring", "payee": "%s", "payment_date": "2017-05-25", "payment_amount": %d, "recurring_date": 1}'
        % (payee_str, payment_double),
        headers=headers)
    resp = urllib2.urlopen(req)
    code = json.load(resp)['code']

    if code == 201:
        success_str = "A bill has been created for " + payee_str + " in the amount of " + payment_str + " dollars."
        return alexa.create_response(message=success_str, end_session=True)
    return alexa.create_response(
        message="An Error Occurred. The Bill was not created. Try again.",
        end_session=True)
Beispiel #4
0
def get_temp_response(temperature_type,
                      success_response,
                      fail_response,
                      min_date=None,
                      max_date=None,
                      aggregate_type=None):
    params = {}
    if min_date:
        params['min_date'] = min_date
    if max_date:
        params['max_date'] = max_date
    if aggregate_type:
        params['aggregate_type'] = aggregate_type

    try:
        endpoint = '/temperature/%s' % temperature_type
        response = poolmon.request(endpoint, params=params)
        temp = int(
            round(response['measurements'][0]['temperature']
                  [preferred_temp_type]))
        message = success_response % {'temp': temp}

        return alexa.create_response(message=message, end_session=True)
    except IndexError:
        return alexa.create_response(message=fail_response, end_session=True)
def get_recipe_intent_handler(request):
    """
    You can insert arbitrary business logic code here    
    """

    # Get variables like userId, slots, intent name etc from the 'Request' object
    ingredient = request.slots["Ingredient"]  # Gets an Ingredient Slot from the Request object.
    
    if ingredient == None:
        return alexa.create_response("Could not find an ingredient!")

    # All manipulations to the request's session object are automatically reflected in the request returned to Amazon.
    # For e.g. This statement adds a new session attribute (automatically returned with the response) storing the
    # Last seen ingredient value in the 'last_ingredient' key. 

    request.session['last_ingredient'] = ingredient # Automatically returned as a sessionAttribute
    
    # Modifying state like this saves us from explicitly having to return Session objects after every response

    # alexa can also build cards which can be sent as part of the response
    card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None,
                             content="asked alexa to find a recipe using {}".format(ingredient))    

    return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient),
                                 end_session=False, card_obj=card)
def get_time_intent_handler(request):

    request_text = request.request['request']['intent']['slots']['value'][
        'value']

    phrases_array = [
        "what time is it", "what time it is", "what time it is in binary",
        "what time is it in binary"
    ]

    if request_text in phrases_array:

        binary_arrays = get_binary_arrays(str(datetime.utcnow().time()))

        binary_time_array = []

        for array in binary_arrays:
            binary_time_array.append(binary_to_words(array))

        return alexa.create_response(
            message="The current time in binary is " + binary_time_array[0] +
            " hours, and " + binary_time_array[1] + " minutes, and " +
            binary_time_array[2] + " seconds, Coordinated Universal Time",
            end_session=True)
    else:
        return alexa.create_response(
            message="I didn't understand that. Ask me what time it is ",
            end_session=False,
            reprompt_message="Ask me what time it is")
def get_recipe_intent_handler(request):
    """
    You can insert arbitrary business logic code here    
    """

    # Get variables like userId, slots, intent name etc from the 'Request' object
    ingredient = request.slots[
        "Ingredient"]  # Gets an Ingredient Slot from the Request object.

    if ingredient == None:
        return alexa.create_response("Could not find an ingredient!")

    # All manipulations to the request's session object are automatically reflected in the request returned to Amazon.
    # For e.g. This statement adds a new session attribute (automatically returned with the response) storing the
    # Last seen ingredient value in the 'last_ingredient' key.

    request.session[
        'last_ingredient'] = ingredient  # Automatically returned as a sessionAttribute

    # Modifying state like this saves us from explicitly having to return Session objects after every response

    # alexa can also build cards which can be sent as part of the response
    card = alexa.create_card(
        title="GetRecipeIntent activated",
        subtitle=None,
        content="asked alexa to find a recipe using {}".format(ingredient))

    return alexa.create_response(
        "Finding a recipe with the ingredient {}".format(ingredient),
        end_session=False,
        card_obj=card)
Beispiel #8
0
def reply_focus_handler(request):
    msg = "Sorry, I couldn't tell which tweet you wanted to reply to."
    index = focused_on_tweet(request)
    if index:
        return alexa.create_response(
            message=
            "Do you want to reply to tweet {} ? If so say reply, followed by your message"
            .format(index))
    return alexa.create_response(message=msg, end_session=False)
def deliver_result(station,result):
    if result.error:
        card = alexa.create_card(title = "NextTrainIntent error", subtitle=None,
                                 content = result.error)
        return alexa.create_response("Sorry. {}".format(result.error), end_session=True, card_obj=card)
    else:
        card = alexa.create_card(title="NextTrainIntent activated", subtitle=None,
                                 content="asked Alexa for trains to {}".format(station))
        speak = format_trips(station, result)
        return alexa.create_response(speak, end_session=True, card_obj=card)
Beispiel #10
0
def play_day_intent_handler(request):
    day = request.get_slot_value("day")
    info = oi.getPlayInfoOfDayNum(day, 0)
    res, title = play_day_num(day, num)
    if res == None:
        if title == None:
            return alexa.create_response("{0} {1}は無効な番組です".format(
                day, num + 1),
                                         end_session=False)
        return alexa.create_response("{0}は再生できない番組です".format(title),
                                     end_session=False)
    return res
def launch_number_handler(request):
    global ORDER
    num = int(request.slots["num"])
    if num >= 1:
        reply = "ordering {} pizzas. ".format(num)
        ORDER['no_of_pizza'] = num
        r, card = checkIsReady()
        reply += r
        return alexa.create_response(message=reply, card_obj=card)
    else:
        reply = "I could not get it, please say the number of pizza you want"
        return alexa.create_response(message=reply, end_session=False)
def get_pizza_size_handler(request):
    size = request.slots["size"].lower()
    global SIZES
    if size in SIZES:
        reply = "Ok, you pick " + size + " size. "
        # save size into order
        global ORDER
        ORDER['size'] = size
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not get it. says 'show pizza sizes' to see your options"
        return alexa.create_response(message=reply, end_session=False)
def get_cut_type_handler(request):
    cut = request.slots["cut"].lower()
    global CUTS
    if cut in CUTS:
        reply = 'OK, ' + cut + ' cut. '
        # save type into order
        global ORDER
        ORDER['cut'] = cut
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not find it. says 'show pizza cuts' to see your options"
        return alexa.create_response(message=reply, end_session=False)
def get_pizza_type_handler(request):
    pizza = request.slots["pizza"].lower()
    global PIZZAS
    if pizza in PIZZAS:
        reply = 'OK, order ' + pizza + '. '
        # save type into order
        global ORDER
        ORDER['type'] = pizza
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not find it. says 'show pizza types' to see your options"
        return alexa.create_response(message=reply, end_session=False)
def get_sauce_type_handler(request):
    sauce = request.slots["sauce"].lower()
    global SAUCES
    if sauce in SAUCES:
        reply = 'OK, ' + sauce + ' sauce. '
        # save type into order
        global ORDER
        ORDER['sauce'] = sauce
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not find it. says 'show pizza sauces' to see your options"
        return alexa.create_response(message=reply, end_session=False)
def get_pizza_crust_handler(request):
    crust = request.slots["crust"].lower()
    reply = "your crust will be " + crust + ". "
    global CRUSTS
    if crust in CRUSTS:
        reply = "Ok, pizza crust will be " + crust + ". "
        # save crust into order
        global ORDER
        ORDER['crust'] = crust
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not find it. says 'show pizza crusts' to see your options"
        return alexa.create_response(message=reply, end_session=False)
def command(cmd, ok):
    result = AVR().send(cmd)
    if result == 'OK':
        card = alexa.create_card(title="Marantz", subtitle=None, content=ok)
        response = alexa.create_response(ok, end_session=True, card_obj=card)
    else:
        card = alexa.create_card(title="Marantz",
                                 subtitle="Error",
                                 content=result)
        response = alexa.create_response(
            "Sorry, the receiver doesn't seem to be cooperating.",
            end_session=True,
            card_obj=card)
    return response
def launch_ChoosePizzaBake_handler(request):
    bake = request.slots["bake"].lower()
    reply = "you want your pizza to be baked in " + bake + ". "
    global BAKES
    if bake in BAKES:
        reply = "Ok, pizza will be baked in " + bake + ". "
        # save bake into order
        global ORDER
        ORDER['bake'] = bake
        reply += checkIsReady()
        return alexa.create_response(message=reply, end_session=False)
    else:
        reply = "I could not find it, if you want me to read menu, say 'show pizza bakes'"
        return alexa.create_response(message=reply, end_session=False)
Beispiel #19
0
def play_intent_handler(request):
    day = request.get_slot_value("day")
    num = request.get_slot_value("num")
    if num == None:
        num = 1
    num = int(num) - 1
    res, title = play_day_num(day, num)
    if res == None:
        if title == None:
            return alexa.create_response("{0} {1}は無効な番組です".format(
                day, num + 1),
                                         end_session=False)
        return alexa.create_response("{0}は再生できない番組です".format(title),
                                     end_session=False)
    return res
def next_train_intent_handler(request):
    # Get variables like userId, slots, intent name etc from the 'Request' object
    station = request.slots["Station"] 
    if station == None:
        return alexa.create_response("Please specify a station name.")
    result = get_trips(station)
    if result.error:
        card = alexa.create_card(title = "NextTrainIntent error", subtitle=None,
                                 content = result.error)
        return alexa.create_response("Sorry. {}".format(result.error), end_session=True, card_obj=card)
    else:
        card = alexa.create_card(title="NextTrainIntent activated", subtitle=None,
                                 content="asked Alexa for next trains to {}: {}".format(station, ", ".join(result.trips)))
        speak = format_trips(station, result)
        return alexa.create_response(speak, end_session=True, card_obj=card)
def launch_IsNotMember_handler(request):
    orderHandler = OrderHandler()
    global ORDER
    ORDER['member'] = {}
    reply = "it's fine! You can join later. "
    reply += checkIsReady()
    return alexa.create_response(message=reply, end_session=False)
Beispiel #22
0
def lambda_handler(request, context=None):
    metadata = {}
    app_id = 'amzn1.echo-sdk-ams.app.a563fd76-b63a-43bd-9d92-9af0bbe27e14'
    if not request.session['application']['applicationId'] == app_id:
        return alexa.create_response('yeah nice try.')

    return alexa.route_request(request, metadata)
def launch_request_handler(request):

    #use random module to select a random murder weapon
    murder_weapon = random.choice(weapon_list)

    #use random module to select a random murder location
    murder_location = random.choice(place_of_murdery)

    #create a suspected killers list
    suspected_killers = []

    #interate through the suspect dictionaries and append the 'name' values to the suspected killers list
    for suspect in suspects.keys():
        suspected_killers.append(suspects[suspect])

    #use random module to select a random killer
    killer = random.choice(suspected_killers)

    killer_name = killer['name']
    killer_hair = killer['facial hair']
    killer_scarf = killer['scarf']
    killer_hat = killer['hat']
    killer_freckles = killer['freckles']
    killer_pet = killer['pet']
    killer_glasses = killer['glasses']

    req = alexa.create_response(message="One of you killed with a {0} in the {1}. Your team is allowed two questions and one guess to figure out who the murderer is. Guess correctly and they'll be arrested and tried. Guess wrong and they go free forever. No pressure. So, what is your first question?".format(murder_weapon, murder_location))
def activity_intent_handler(request):
    act = request.slots["Activity"].lower()
    if act in ("tv", "t.v.", "netflix", "roku", "amazon video"):
        name = 'SAT/CBL'
        msg = 'OK. Turn on the TV to watch Roku, Netflix, or Amazon Video.'
    elif act == 'you tube':
        name = 'SAT/CBL'
        msg = 'OK. Use the Roku remote to select the You Tube app.'
    elif act.find('phone') > -1 or act == 'air play':
        name = 'NET'
        msg = 'OK. On your I phone, choose the Marantz receiver as the Air Play destination, and play a song.'
    elif act.find('dvd') > -1 or act.find('movie') > -1:
        name = 'BD'
        msg = 'DVD player is ready. What are we watching?'
    elif act == 'apple tv' or act == 'apple t.v.' or act.find(
            'photos') > -1 or act.find('pictures') > -1:
        name = 'MPLAY'
        msg = 'OK. Use the small white remote to control Apple TV.'
    elif act == 'pandora':
        name = 'PANDORA'
        msg = 'Pandora streaming will start in the TV room shortly.'
    else:
        return alexa.create_response(
            "Sorry, I don't know how to set up the stereo for the " + act +
            " task.",
            end_session=True,
            card_obj=alexa.create_card(title="Marantz Error", content=act))

    response = command(['Z2OFF', 'PWON', 'ZMON', 'SI' + name], msg)
    return response
def launch_request_handler(request):
    return alexa.create_response(
        message=
        "Welcome to Code Comments! If you give me the name of a programming language, I will respond with instructions for making a comment in that language! In what language would you like to comment?",
        reprompt_message=
        "Learning how to comment can be fun! What language would you like to comment out?"
    )
Beispiel #26
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)
Beispiel #27
0
def previous_intent_handler(request):
    user_queue = twitter_cache.user_queue(request.access_token())
    if user_queue and user_queue.has_prev():
        message = user_queue.read_out_prev()
    else:
        message = "I couldn't find anything to repeat"
    return alexa.create_response(message=message)
def get_onprem_cost_efficiency_handler(request):
    """ Queries the OneSphere metrics API and returns the  private cloud cost efficiency.
    """

    # Get KMS secured environment variables
    api_base = request.metadata.get('api_base', None)
    token = request.metadata.get('token', None)

    # Get service status
    # periodStart should default to the current month
    # 'periodStart': '2018-01-01T00:00:00Z',
    payload = {'category': 'providers', 'groupBy': 'providerTypeUri',
               'name': 'cost.efficiency', 'period': 'month', 'periodCount': '-1', 'view': 'full'
               }
    r = safe_requests(requests.get, api_base + "/metrics", params=payload,
                      headers={'accept': 'application/json',
                               'Authorization': token}
                      )

    # Parse metrics JSON output
    metric_data = MetricData(r)
    total_spend = metric_data.get_cost()
    speech_output = "The OneSphere service private cloud efficiency for this month is ${:,.2f}".format(total_spend)

    card = alexa.create_card(title="GetOnpremCostEfficiencyIntent activated", subtitle=None,
                             content="asked alexa to query the OneSphere metrics REST API and calculate" \
                                     " the total private cloud monthly cost efficiency")

    return alexa.create_response(speech_output,end_session=False, card_obj=card)
Beispiel #29
0
def get_recipe_intent_handler(request):
    """
    You can insert arbitrary business logic code here
    """

    # Get variables like userId, slots, intent name etc from the 'Request' object
    ingredient = request.slots["Ingredient"]

    if ingredient == None:
        return alexa.create_response("Could not find an ingredient!")

    card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None,
                             content="asked alexa to find a recipe using {}".format(ingredient))

    return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient),
                                 end_session=False, card_obj=card)
def launch_request_handler(request):
    """
    Annoatate 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
    """
    return alexa.create_response(message="Hello Welcome to My Recipes!")
Beispiel #31
0
def launch_request_handler(request):

    #use random module to select a random murder weapon
    murder_weapon = random.choice(weapon_list)

    #use random module to select a random murder location
    murder_location = random.choice(place_of_murdery)

    #create a suspected killers list
    suspected_killers = []

    #interate through the suspect dictionaries and append the 'name' values to the suspected killers list
    for suspect in suspects.keys():
        suspected_killers.append(suspects[suspect])

    #use random module to select a random killer
    killer = random.choice(suspected_killers)

    killer_name = killer['name']
    killer_hair = killer['facial hair']
    killer_scarf = killer['scarf']
    killer_hat = killer['hat']
    killer_freckles = killer['freckles']
    killer_pet = killer['pet']
    killer_glasses = killer['glasses']

    req = alexa.create_response(
        message=
        "One of you killed with a {0} in the {1}. Your team is allowed two questions and one guess to figure out who the murderer is. Guess correctly and they'll be arrested and tried. Guess wrong and they go free forever. No pressure. So, what is your first question?"
        .format(murder_weapon, murder_location))
def arrive_intent_handler(request):
    station = request.slots["Destination"]
    arrive_time = request.slots["Time"]
    if (station == None or arrive_time == None):
        return alexa.create_response("Please try again, giving the destination station and arrival time.")
    result = get_trips(station, 'arrive', arrive_time)
    return deliver_result(station,result)
Beispiel #33
0
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):
    """ This is a generic function to handle any intent that reads out a list of tweets"""
    # tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
    tweets = tweet_list_builder(request.access_token())
    print(len(tweets), 'tweets found')
    if tweets:
        twitter_cache.initialize_user_queue(user_id=request.access_token(),
                                            queue=tweets)
        text_to_read_out = twitter_cache.user_queue(
            request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)
        message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number."
        return alexa.create_response(message=message, end_session=False)
    else:
        return alexa.create_response(
            message="Sorry, no tweets found, please try something else",
            end_session=False)
Beispiel #34
0
def enqueue_next(day, num):
    res = enqueue_day_num(day, num + 1)
    if res == None:
        if num == 0:
            return alexa.create_response(end_session=True)
        return enqueue_next(day, 0)
    return res
def get_recipe_intent_handler(request):
    """
    You can insert arbitrary business logic code here    
    """

    # Get variables like userId, slots, intent name etc from the 'Request' object
    ingredient = request.slots["Ingredient"] 

    if ingredient == None:
        return alexa.create_response("Could not find an ingredient!")

    card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None,
                             content="asked alexa to find a recipe using {}".format(ingredient))
    
    return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient),
                                 end_session=False, card_obj=card)
Beispiel #36
0
def play_next(day, num, endSession=True):
    res, title = play_day_num(day, num + 1, endSession)
    if res == None:
        if title == None:
            return alexa.create_response(end_session=True)
        return enqueue_next(day, 0, endSession)
    return res
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)
Beispiel #38
0
def launch_request_handler(request):
    return alexa.create_response(
        message=
        "Welcome to Animal Translator! If you give me the name of an animal, I will respond with the human pronounciation of the sound it makes! What animal would you like me to sound out for you?",
        reprompt_message=
        'Learning how to say the sounds of animals can be fun! What animal would you like me to sound out for you?'
    )
def previous_intent_handler(request):
    user_queue = twitter_cache.user_queue(request.access_token())
    if user_queue and user_queue.has_prev():
        message = user_queue.read_out_prev()
    else:
        message = "I couldn't find anything to repeat"
    return alexa.create_response(message=message)
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)
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):

    """ This is a generic function to handle any intent that reads out a list of tweets"""
    # tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
    tweets = tweet_list_builder(request.access_token())
    print (len(tweets), 'tweets found')
    if tweets:
        twitter_cache.initialize_user_queue(user_id=request.access_token(),
                                            queue=tweets)
        text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)        
        message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number."
        return alexa.create_response(message=message,
                                     end_session=False)
    else:
        return alexa.create_response(message="Sorry, no tweets found, please try something else", 
                                 end_session=False)
Beispiel #42
0
def launch_request_handler(request):
    card = alexa.create_card(title="最新の番組一覧",
                             subtitle=None,
                             content=oi.getStringListOfDay("最新"))
    return alexa.create_response('再生したい番組を教えてください',
                                 end_session=False,
                                 card_obj=card)
def next_train_intent_handler(request):
    # Get variables like userId, slots, intent name etc from the 'Request' object
    station = request.slots["Station"] 
    if station == None:
        return alexa.create_response("Please try again, giving the destination station name.")
    result = get_trips(station, 'depart')
    return deliver_result(station,result)
def get_suspect_intent_handler(request):
    """
    Whodunnit??
    """
    # Get variables like userId, slots, intent name etc from the 'Request' object
    suspect = request.slots["Suspect"]
    suspect = suspect.lower()


    if suspect == None:
        return alexa.create_response("Could not find a suspect!")

    elif suspect == killer_name:
        return alexa.create_response("You are correct! Congratulations, you have saved the day. Well, not the murder victims day. Or the killer's day.  But someone's day was surely saved.", end_session=True)

    else:
        return alexa.create_response("You are wrong, the killer will now go free and the victim's murder will never be solved. Way to ruin everything. ", end_session=True)
def help_intent_handler(request):
    cat_list = [cat for cat in useful_science.categories]
    pre = cat_list[:-1]
    post = cat_list[-1:]
    formatted = " ".join(map(lambda x : x+",", pre) + ['and'] + post)
    message = ["You can ask for posts in the following categories - ",
               formatted]          
    return alexa.create_response(message=' '.join(message))
Beispiel #46
0
def get_temp_response(temperature_type, success_response, fail_response, min_date=None, max_date=None, aggregate_type=None):
    params={}
    if min_date:
        params['min_date'] = min_date
    if max_date:
        params['max_date'] = max_date
    if aggregate_type:
        params['aggregate_type'] = aggregate_type
    
    try:
        endpoint = '/temperature/%s' % temperature_type
        response = poolmon.request(endpoint, params=params)
        temp = int(round(response['measurements'][0]['temperature'][preferred_temp_type]))
        message = success_response % {'temp': temp}
        
        return alexa.create_response(message=message, end_session=True)
    except IndexError:
        return alexa.create_response(message=fail_response, end_session=True)
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)
Beispiel #48
0
def past_ambient_temp(request):
    min_date, max_date, date_type = poolmon.parse_date(request.slots['Date'])
    if date_type == 'day':
        aggregate_type = 'max'
    elif date_type == 'week' or date_type == 'year':
        aggregate_type = 'avg'
    else:
        return alexa.create_response(message=DATE_PARSE_FAIL, end_session=False)
    
    return get_temp_response('ambient', PAST_AMBIENT_TEMP_SUCCESS, PAST_AMBIENT_TEMP_FAIL, min_date=min_date, max_date=max_date, aggregate_type=aggregate_type)
def delays_intent_handler(request):
    delays = BartTrip(API_KEY)
    result = "DelaysIntent activated"
    if delays.error:
        speak = "Sorry. {}".format(delays.error)
        result = "DelaysIntent error"
    elif delays.delays:
        speak = delays.delays
    else:
        speak = "No delays reported."
    card = alexa.create_card(title = result, subtitle=None, content=speak)
    return alexa.create_response(speak,end_session=True,card_obj=card)
def set_waketime_intent_handler(request):
    """ Tell Alexa when you woke up. 
    """

    cur_date = get_cur_date() - timedelta(days=1)
    wake_str = cur_date.strftime(TIME_FMT)
    r = set_value_for_date(cur_date, ATTR_MAP["waketime"], wake_str)
    # TODO Unhappy path
    response_str = "Good morning Michael! I logged your wakeup time as {}. Have a great day!".format(
                    cur_date.strftime("%I %M %p"))

    return alexa.create_response(response_str, end_session=True) 
def set_latency_intent(request):
    """Tell Alexa how long it took you to fall asleep.
    Expects to be called the day after you went to bed. 
    """

    cur_date = get_cur_date() - timedelta(days=1)
    minutes = request.slots["Minutes"]
    minutes_str = "00:{}:00".format(minutes)
    r = set_value_for_date(cur_date, ATTR_MAP["latency"], minutes_str)
    # TODO: Unhappy path
    response_str = "OK, I logged your sleep latency as {} minutes.".format(
                    minutes)

    return alexa.create_response(response_str, end_session=True) 
def update_latency_intent(request):
    """Sets the sleep latency based on the current time and the previously logged bedtime. 
    """
    cur_date = get_cur_date()

    if cur_date.hour < 12:
        cur_date = cur_date - timedelta(days=1)

    prev_bedtime = get_value_on_date(cur_date, ATTR_MAP["bedtime"]) 

    if not prev_bedtime:
        response_str = "Sorry, it looks like you haven't set a bedtime yet."
        return alexa.create_response(response_str, end_session=True)

    prev_bedtime = create_datetime_from_time(prev_bedtime)

    latency = int((cur_date - prev_bedtime).total_seconds()/60)
    latency_str = "00:{}:00".format(latency)

    set_value_for_date(cur_date, ATTR_MAP["latency"], latency_str)

    response_str = "OK Michael, I updated your sleep latency to {} minutes".format(latency)
    return alexa.create_response(response_str, end_session=True)
def results_for_afd(station_name, report_component):
    report = Noaa()
    station= HOME_STATION
    component = report_component.upper()

    report.get_afd_for(station)

    if report.error:
        card_title = 'error'
        content = 'Sorry. {}'.format(report.error)
    else:
        card_title = 'activated'
        content = report.sections[component]
    
    card = alexa.create_card(title = '{}Intent {}'.format(component,card_title),  subtitle='Station: {}'.format(station), content=content)
    return alexa.create_response(content, end_session=True, card_obj = card)
def next_intent_handler(request):
    """
    Takes care of things whenver the user says 'next'
    """

    message = "Sorry, couldn't find anything in your next queue"
    end_session = True
    if True:
        user_queue = twitter_cache.user_queue(request.access_token())
        if not user_queue.is_finished():
            message = user_queue.read_out_next(MAX_RESPONSE_TWEETS)
            if not user_queue.is_finished():
                end_session = False
                message = message + ". Please, say 'next' if you want me to read out more. "
    return alexa.create_response(message=message,
                                 end_session=end_session)
def set_bedtime_intent_handler(request):
    """ Tell Alexa when you went to bed. 
    """

    # TODO: This guy should clear out the sleep latency for the day when it's set 
    cur_date = get_cur_date()

    # If bedtime is AM, set date to be previous day
    if cur_date.hour < 12:
        cur_date = cur_date - timedelta(days=1)
    bedtime = cur_date.strftime(TIME_FMT)

    r = set_value_for_date(cur_date, ATTR_MAP["bedtime"], bedtime)
    response_str = "OK, I logged your bedtime as {}. Goodnight Michael!".format(
                    cur_date.strftime("%I %M %p"))

    return alexa.create_response(response_str, end_session=True) 
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)
def get_posts_intent_handler(request):    

    def resolve_slots(text):
        if text in useful_science.categories:
            return text        
        return 'new'
    
    category_text = request.slots['Category']
    category = resolve_slots(category_text)
    post = useful_science.post_cache.get_post(category)

    card_content = "{0} Link: {1}".format(post['summary'],
                                          post['permalink'])

    card = alexa.create_card(title=post['meta_title'],
                             subtitle=post['categories'],
                             content=card_content)
    
    return alexa.create_response(message=post['summary'],
                                 end_session=True,
                                 card_obj=card)
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)
def next_recipe_intent_handler(request):
    """
    You can insert arbitrary business logic code here
    """
    return alexa.create_response(message="Getting Next Recipe ... 123")
def session_ended_request_handler(request):
    return alexa.create_response(message="Goodbye!")