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)
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 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 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)
示例#5
0
def lambda_handler(request_obj, context=None):

    myUsageMonths = {}

    jsonStr = getUsage()

    if jsonStr == None:
        card = alexa.create_card(title="GetInternetUsage activated",
                                 subtitle=None,
                                 content="asked alexa to get internet usage")
        return alexa.create_response(
            "Sorry unable to retrieve comcast account information",
            end_session=True,
            card_obj=card)

    jsonObj = json.loads(jsonStr)

    usageMonths = jsonObj['usageMonths']

    for usageMonth in usageMonths:
        monthName = calendar.month_name[int(usageMonth['startDate'][:2])]
        myUsageMonths[monthName] = MyUsage(monthName,
                                           usageMonth['unitOfMeasure'],
                                           usageMonth['homeUsage'],
                                           usageMonth['allowableUsage'])

    metadata = {'usageMonths': myUsageMonths}

    return alexa.route_request(request_obj, metadata)
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_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)
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
示例#9
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 launch_ShowPizzaTypes_handler(request):
    r = "pizza types are "
    global PIZZAS
    for x in PIZZAS:
        r = r + '{},'.format(x)
    card = alexa.create_card(title="Pizza Menu", subtitle=None, content=r)
    return alexa.create_response(message=r, end_session=False, card_obj=card)
    '''
示例#11
0
def get_internet_usage_intent_handler(request):

    myUsageMonths = request.metadata['usageMonths']

    requestMonth = request.slots["Date"]

    if requestMonth == None:
        currentDT = datetime.datetime.now(
        )  # If users request does not have a date lets default to the current date
        requestUserMonthByName = currentDT.strftime(
            "%B")  # Get Month by name e.g.
    else:
        requestUserMonthByName = calendar.month_name[int(requestMonth[5] +
                                                         requestMonth[6])]

    if requestUserMonthByName not in myUsageMonths:
        card = alexa.create_card(
            title="GetInternetUsage activated",
            subtitle=None,
            content="asked alexa to get internet usage using {}".format(
                requestMonth))
        return alexa.create_response(
            "Sorry no usage data exist for the requested month {}".format(
                requestMonth),
            end_session=False,
            card_obj=card)
    else:
        card = alexa.create_card(
            title="GetInternetUsage activated",
            subtitle=None,
            content="You have used %s%s out of %s%s for the month of %s!" %
            (myUsageMonths[requestUserMonthByName].homeUsage,
             myUsageMonths[requestUserMonthByName].unitOfMeasure,
             myUsageMonths[requestUserMonthByName].allowableUsage,
             myUsageMonths[requestUserMonthByName].unitOfMeasure,
             myUsageMonths[requestUserMonthByName].monthLongName))

        return alexa.create_response(
            "You have used %s%s out of %s%s for the month of %s!" %
            (myUsageMonths[requestUserMonthByName].homeUsage,
             myUsageMonths[requestUserMonthByName].unitOfMeasure,
             myUsageMonths[requestUserMonthByName].allowableUsage,
             myUsageMonths[requestUserMonthByName].unitOfMeasure,
             myUsageMonths[requestUserMonthByName].monthLongName),
            end_session=False,
            card_obj=card)
def get_brohug_intent_handler(request):

    card = alexa.create_card(title="GetBroHugIntent activated", subtitle=None,
                             content="asked alexa to give BroHug advice")

    return alexa.create_response(
        message="You must remember to maintain a safe groin distance of 1 foot " +
                "when executing a proper bro hug.",
        end_session=False, card_obj=card)
def get_onprem_cost_savings_handler(request):
    """ Queries the OneSphere metrics API and returns the total private cloud cost savings.
        NOT YET IMPLEMENTED
    """

    speech_output = "The OneSphere service private cloud cost savings feature is not yet implemented"

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

    return alexa.create_response(speech_output,end_session=False, card_obj=card)
示例#14
0
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)
示例#15
0
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)
示例#16
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 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)
示例#18
0
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)
示例#19
0
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 get_service_intent_handler(request):
    """
    Query the OneSphere status API and return the service status.
    """

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

    # Get service status
    r = safe_requests(requests.get, api_base + "/status")

    if 'service' in r:
        speech_output = "The OneSphere service is currently " + r["service"]
    else:
        speech_output = "The OneSphere service is currently unavailable"

    card = alexa.create_card(title="GetServiceStatusIntent activated", subtitle=None,
                             content="asked alexa to query the OneSphere service status REST API")

    return alexa.create_response(speech_output,end_session=False, card_obj=card)
示例#21
0
def get_pool_weather_handler(request):
    pool_data = requests.get('{}/json.php'.format(webpath)).json()
    card = alexa.create_card(
        title="The pool is {}".format(
            adjective_for_temp(pool_data['probe_temp_f'])[1]),
        subtitle=None,
        content=
        "Pool water temperature is {}°F at {}.\n\nYesterday's peak water temperature was {}°F at {}."
        .format(
            pool_data['probe_temp_f'],
            datetime.strftime(
                datetime.now(pytz.UTC).astimezone(localtz), "%I:%M %p"),
            pool_data['peak_temp_f'],
            timestamp_to_local(pool_data['peak_temp_time'])),
        large_image='{}/temperature.php?start={}&lookback={}'.format(
            webpath, int(datetime.strftime(datetime.now(), "%s")),
            60 * 60 * 12))
    return alexa.create_response(message=get_pool_weather(pool_data),
                                 end_session=True,
                                 card_obj=card)
示例#22
0
def get_channel_list_intent_handler(request):
    day = request.slots["day"]
    print(request.slots["day"])
    print(day)
    if day == None:
        return alexa.create_response("Could not find an ingredient!")
    d = oi.getDayId(day)
    titles = {}
    if d == "latest":
        titles = oi.getNewTitle()
    else:
        titles = oi.getTitleOfDay(d)
    card_content = oi.getStringListOfDay(day, titles)
    speech_content = oi.getStringListOfDay(day, titles, True)
    card = alexa.create_card(title="{0}の番組一覧".format(day),
                             subtitle=None,
                             content=card_content)
    return alexa.create_response(speech_content,
                                 end_session=False,
                                 card_obj=card)
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 get_station_intent_handler(request):
    """
    You can insert arbitrary business logic code here
    """

    # Get variables like userId, slots, intent name etc from the 'Request'
    # object
    station = request.slots.get("station")

    if station is None:
        return alexa.create_response(message="Entschuldigung, du hast mir \
keine Haltestelle genannt. Kannst du bitte deine Anfrage mit Haltestelle Wiederholen?"
                                     )

    stops = dvb_monitor(station)

    speech_output = "Hier sind die nächsten 4 Abfahrten für {station}.".format(
        station=station)
    card_output = ""
    for stop in stops:
        speech_output += " Linie {line} nach {direction} in {arrival}.".format(
            line=stop["line"],
            direction=stop["direction"],
            arrival="einer Minute" if int(stop["arrival"]) == 1 else
            "{} Minuten".format(stop["arrival"]))
        card_output += "Linie {line} nach {direction}: {arrival} Minute{n}\n".format(
            line=stop["line"],
            direction=stop["direction"],
            arrival=stop["arrival"],
            n="n" if int(stop["arrival"]) != 1 else "")

    card = alexa.create_card(
        title="Die nächsten Abfahrten für {station}".format(station=station),
        subtitle=None,
        content=card_output)
    return alexa.create_response(message=speech_output,
                                 end_session=True,
                                 card_obj=card)
示例#25
0
def get_detail_info_intent_handler(request):
    day = request.get_slot_value("day")
    num = request.get_slot_value("num")
    if num == None:
        num = 1
    num = int(num) - 1
    info = oi.getTitleInfoOfDayNum(day, num)
    print(info)
    card_text = "{0}\nパーソナリティー {1}".format(info["update"], info["personality"])
    if not info["guest"] == None:
        card_text += "\nゲストは {0}".format(info["guest"])
    card_image = {
        "smallImageUrl": info["thumbnail"],
        "largeImageUrl": info["thumbnail"]
    }  #image指定はalexa_io.pyを拡張
    speech_content = "{0} {1}".format(info["data-kana"], card_text)
    card = alexa.create_card(title="{0}".format(info["title"]),
                             text=card_text,
                             card_type="Standard",
                             image=card_image)

    return alexa.create_response(speech_content,
                                 end_session=False,
                                 card_obj=card)
def checkIsReady():
    isReady, key = hasEnoughInfo()
    if isReady:
        order_no, total_price, awards, redeemCount = placeOrder()
        reply = 'Thank you! Your order number is ' + order_no + '. '
        reply += 'And the total will be $' + total_price + '. '
        reply += 'Your pizza will be ready in 15 minutes. '
        if redeemCount > 0:
            reply += 'Congratulations, you have ' + str(
                redeemCount) + ' free pizza in this order. '
        if awards is not None:
            difference_awards = 10 - int(awards)
            reply += 'Order ' + str(
                difference_awards
            ) + " more pizzas, and you will get one free. "
        # return complete info to user for the order
        global ORDER
        content = 'Order Number: ' + order_no + '\n'
        content += 'Customer Name: ' + ORDER['name'] + '\n'
        content += 'Pizza Type: ' + ORDER['type'] + '\n'
        content += 'Pizza Size: ' + ORDER['size'] + '\n'
        content += 'Pizza Crust: ' + ORDER['crust'] + '\n'
        content += 'Pizza Sauce: ' + ORDER['sauce'] + '\n'
        content += 'Pizza Bake: ' + ORDER['bake'] + '\n'
        content += 'Pizza Cut: ' + ORDER['cut'] + '\n'
        content += 'Pizza Seasoning: ' + ORDER['seasoning'] + '\n'
        content += 'Pizza Toppings: '
        count = 1
        for topping in ORDER['toppings']:
            if topping is not 'none':
                content += str(count) + '. ' + topping + ' '
                count += 1
        content += '\n'
        content += 'Number of Pizza: ' + str(ORDER['no_of_pizza']) + '\n'
        content += 'Total Price: $' + total_price + '\n'
        card = alexa.create_card(title="Pizza Order Detail",
                                 subtitle=None,
                                 content=content)
        initialzeOrder()
        return reply, card
    else:
        if key is 'member':
            return 'Are you in our membership? '
        elif key is 'name':
            return 'Please tell me your name. '
        elif key is 'type':
            return 'Please choose a type of pizza. '
        elif key is 'size':
            return 'Please choose the size for the pizza. '
        elif key is 'crust':
            return 'Please choose the crust for the pizza. '
        elif key is 'sauce':
            return 'Please choose the sauce for the pizza. '
        elif key is 'bake':
            return 'How would you like your pizza to bake, well done or normal? '
        elif key is 'cut':
            return 'Please choose the cut for the pizza. '
        elif key is 'seasoning':
            return 'Do you want garlic seasoned crust for the seasoning? '
        elif key is 'toppings':
            return 'Do you want any topping? You can choose 5 toppings if you want. '
        elif key is 'more_toppings':
            return 'Any other toppings? '
        elif key is 'no_of_pizza':
            return 'How many pizza do you want? '
        elif key is 'ask_enroll':
            return 'Do you want to join our awards program? ', None
示例#27
0
def help_intent_handler(request):
    card = alexa.create_card(title="つかいかた", text=help_msg)
    return alexa.create_response(help_msg, end_session=False, card_obj=card)