Пример #1
0
    def handle(self, handler_input):
        d = ask_utils.get_slot_value(handler_input, "days_day")
        n = ask_utils.get_slot_value(handler_input, "days_name")
        z = s.get_date_type(d)
        print(f" Day - days_day:{d},days_name:{n}, day: {z} ")
        if z == "A":
            day = "It is a A day."
        elif z == "B":
            day = "It is a B day."
        elif z == "W":
            day = "It is a weekend!"
        else:
            day = "Yay! it is a holiday."

        if n == None:
            speak_text = day
        else:
            if n.upper() == z:
                speak_text = f"Yes. {day}."
            else:
                speak_text = f"No. {day}."

        return handler_input\
            .response_builder \
            .speak(speak_text)\
            .set_should_end_session(True)\
            .response
Пример #2
0
def add_show_intent_handler(handler_input):
    """ handler for Add Show Intent"""

    h = handler_input.request_envelope.context.system.user.access_token
    showtype = 'show'
    # If we are not auth, let the user know
    if h is None:
        reprompt = language.AUTH_ERROR
        handler_input.response_builder.speak(reprompt).ask(reprompt)
        return handler_input.response_builder.response
    headers = utils.build_headers(h, clientid)

    # get our persistent_attributes
    _perattr = handler_input.attributes_manager.persistent_attributes
    movie = get_slot_value(handler_input=handler_input, slot_name="showName")
    user_list = get_slot_value(handler_input=handler_input, slot_name="list_name")
    _list, _usecustomlist = utils.get_list(user_list, _perattr)
    # search for move and get the object
    b = trakt_api.search(movie, headers, showtype, False)
    if b['error']:
        # handle this
        handler_input.response_builder.speak(language.SHOW_404)
        return handler_input.response_builder.response

    y = b['show']
    # dig through our search and add the movie/show to our list or our Watchlist
    trakt_api.parse_search(b['type'], headers, y, _list, _usecustomlist, True)
    utils.notify(movie, b['type'], _list)
    handler_input.response_builder.speak(movie + " show has been added to your list " + str(_list))
    # .ask(reprompt)
    return handler_input.response_builder.response
 def can_handle(self, handler_input):
     return is_intent_name(SET_DEFAULT_INTENT)(handler_input) and \
            get_dialog_state(handler_input) == dialog_state.DialogState.IN_PROGRESS \
            and get_slot_value(slot_name=SLOT_ROUTE_NUMBER, handler_input=handler_input) and \
            get_slot_value(slot_name=SLOT_STOP_NAME, handler_input=handler_input) \
            and get_slot(handler_input, SLOT_STOP_NAME).confirmation_status == SlotConfirmationStatus.CONFIRMED \
            and handler_input.request_envelope.request.intent.confirmation_status == IntentConfirmationStatus.NONE
Пример #4
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        number = get_slot_value(
            handler_input = handler_input,
            slot_name = "number"
        )
        method = get_slot_value(
            handler_input = handler_input,
            slot_name = "method"
        )

        slots = handler_input.request_envelope.request.intent.slots
        if "method" in slots:
            method_slot_resolution = slots["method"].resolutions.resolutions_per_authority[0]
            if method_slot_resolution.status.code == StatusCode.ER_SUCCESS_MATCH:
                method = method_slot_resolution.values[0].value.name
 
        request = {
            "function": "appendRecords",
            "parameters": [{
                "query_result": {
                "number": number,
                "method": method
                }
            }],
            "devMode": True
        }

        gsheet.write_data(gsheet.get_auth(), request)
        
        speech_text = str(number) + "回、" + method + "の記録をしました"
        handler_input.response_builder.speak(speech_text).set_should_end_session(True)
        return handler_input.response_builder.response
Пример #5
0
    def send_sms(self, handler_input):
        # Try to send the SMS.
        try:
            logger.info("In send_sms")

            RECIPIENT = get_slot_value(handler_input=handler_input,
                                       slot_name="toPhone")
            BODY_TEXT = get_slot_value(handler_input=handler_input,
                                       slot_name="body")
            FRON_NAME = [YOUR_CODE_IS_HERE]
            TO_NAME = [YOUR_CODE_IS_HERE]

            translate_slot = get_slot(handler_input=handler_input,
                                      slot_name="translate")

            #Provide the contents of the SMS.
            sms_setup = sns.set_sms_attributes(
                attributes={'DefaultSenderID': FRON_NAME})

            #Publish the SMS
            [YOUR_CODE_IS_HERE]

        # Display an error if something goes wrong.
        except ClientError as e:
            logger.info("SMS wasn't sent correctly!")
            logger.error(e.response['Error']['Message'])
            return False
        else:
            logger.info("SMS sent! Message ID:"),
            logger.info(response['MessageId'])
            return True
Пример #6
0
    def handle(self, handler_input):
        school_name = ask_utils.get_slot_value(handler_input, "lunch_school")
        lunch_day = ask_utils.get_slot_value(handler_input, "lunch_day")
        menu_type = ask_utils.get_slot_value(handler_input, "lunch_type")
        end = True
        print(lunch_day)
        print(school_name)
        if lunch_day == None:
            x = datetime.today()
        else:
            x = datetime.strptime(lunch_day, '%Y-%m-%d')
        if school_name == None:
            end = False
            speak_text = "I am unable to help you. You must mention a school name in Loudoun County. For example, ask like this, What is the lunch menu at lunsford today? "
        else:
            print(school_name)
            print(x)
            menus = s.menu(school_name, x, menu_type)
            print(
                f"school_name:{school_name}, lunch_day:{lunch_day}, x:{x} , MENUS -({menus})"
            )
            if menus == None:
                end = False
                speak_text = f"I am unable to help you. Looks like {school_name} is not a school in Loudoun County. For example, ask like this, What is the lunch menu at lunsford today? "
            elif menus == "":
                speak_text = f"The cafetria is closed. Looks like {lunch_day} is not a school day!"
            else:
                speak_text = f"They are serving {menus}."

        return handler_input\
            .response_builder \
            .speak(speak_text)\
            .set_should_end_session(end)\
            .response
Пример #7
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        country_value = ask_utils.get_slot_value(handler_input=handler_input,
                                                 slot_name="country")
        case_value = ask_utils.get_slot_value(handler_input=handler_input,
                                              slot_name="cases")
        speak_output = "Sorry, I had trouble doing what you asked. Please try again."

        if (country_value and case_value):
            country_value = {
                'usa': 'us',
                'united states': 'us',
                'united states of america': 'us',
                'united kingdom': 'uk',
                'uae': 'united-arab-emirates',
                'ivory coast': 'cote-d-ivoire',
                'palestine': 'state-of-palestine',
                'congo': 'democratic-republic-of-the-congo',
                'vietnam': 'viet-nam',
            }.get(country_value.lower(), country_value)

            if case_value in [
                    'deaths', 'death', 'recovered', 'recovering', 'recover',
                    'confirmed', 'confirming', 'confirm'
            ]:
                try:
                    if country_value == 'worldwide':
                        response = requests.get(
                            "https://www.worldometers.info/coronavirus")
                    else:
                        response = requests.get(
                            "https://www.worldometers.info/coronavirus/country/{}"
                            .format(inflection.dasherize(
                                country_value.lower())))

                    soup = BeautifulSoup(response.text, 'html.parser')
                    figures = soup.find_all('div', id='maincounter-wrap')

                    if case_value in ['confirmed', 'confirming', 'confirm']:
                        confirmed = figures[0].find('span').text
                        speak_output = "{} confirmed cases".format(confirmed)

                    if case_value in ['deaths', 'death']:
                        deaths = figures[1].find('span').text
                        speak_output = "{} deaths".format(deaths)

                    if case_value in ['recovered', 'recovering', 'recover']:
                        recovered = figures[2].find('span').text
                        speak_output = "{} recovered cases".format(recovered)

                except:
                    speak_output = "Sorry, I had trouble doing what you asked. Please try again."

        return (
            handler_input.response_builder.speak(speak_output).ask(
                speak_output)
            # .ask("add a reprompt if you want to keep the session open for the user to respond")
            .response)
Пример #8
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In PlayMetronomeHandler")

        tempo = int(get_slot_value(handler_input, "tempo"))
        if tempo < 20 or tempo > 240:
            handler_input.response_builder.speak(strings.TEMPO_NOT_IN_RANGE)
            return handler_input.response_builder.response

        duration = (get_slot_value(handler_input, "duration")
                    or strings.DEFAULT_DURATION)
        seconds = iso_8601_duration_to_seconds(duration)
        if seconds < 10 or seconds > 600:
            handler_input.response_builder.speak(strings.DURATION_NOT_IN_RANGE)
            return handler_input.response_builder.response

        logger.info("tempo={} duration={} seconds={}".format(
            tempo, duration, seconds))

        speak = strings.PLAYING.format(
            tempo, "{}'{}\"".format(int(seconds / 60), seconds % 60))

        data = {
            "card": {
                "title": strings.SKILL_NAME,
                "text": strings.CARD_TEXT.format(tempo),
                "small_image_url": strings.ICON_URL,
                "large_image_url": strings.ICON_URL
            },
            "url": get_metronome_url(tempo, seconds),
        }

        card = StandardCard(
            title=data["card"]["title"],
            text=data["card"]["text"],
            image=Image(small_image_url=data["card"]["small_image_url"],
                        large_image_url=data["card"]["large_image_url"]))

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(expected_previous_token=None,
                              token=data["url"],
                              url=data["url"],
                              offset_in_milliseconds=0),
                metadata=AudioItemMetadata(
                    title=data["card"]["title"],
                    subtitle=data["card"]["text"],
                    art=display.Image(
                        content_description=data["card"]["title"],
                        sources=[display.ImageInstance(url=strings.ICON_URL)]),
                    background_image=display.Image(
                        content_description=data["card"]["title"],
                        sources=[display.ImageInstance(url=strings.ICON_URL)
                                 ]))))
        (handler_input.response_builder.speak(speak).set_card(
            card).add_directive(directive).set_should_end_session(True))
        return handler_input.response_builder.response
Пример #9
0
def extract_event_params(handler_input) -> DeviceInfo:
    device_name = get_slot_value(handler_input, 'name')
    state = get_slot_value(handler_input, 'state')
    print("device info: ", device_name, state)

    if device_name is not None and state is not None:
        return DeviceInfo(device_name.lower(), state.upper())
    else:
        raise SlotValueNotPresentException
    def test_get_slot_value_throws_exception_for_non_existent_slot(self):
        test_input = self._create_handler_input(
            request=self.test_intent_request)

        with self.assertRaises(
                ValueError,
                msg="get_slot_value method didn't throw ValueError when an "
                    "invalid slot name is passed"):
            get_slot_value(handler_input=test_input, slot_name="some_slot")
Пример #11
0
def add_movie_intent_handler(handler_input):
    """Handler for Add Movie Intent."""

    # get our persistent_attributes
    # if the user has launched the app greet them
    # set out session attributes
    _perattr = handler_input.attributes_manager.persistent_attributes
    attr = handler_input.attributes_manager.session_attributes
    if is_request_type("LaunchRequest")(handler_input):
        # _usecustomlist = _perattr['usecustomlist']
        attr["movie"] = {}
        attr["show"] = {}
        attr['readBoxOffice'] = False
        attr['readMovies'] = False
        attr['readShows'] = False
        attr['readBoth'] = False
        attr['active_request'] = ''
        attr['repeat'] = ''
        handler_input.response_builder.speak("Welcome To Radar the Trakt.tv tracker").ask("")
        return handler_input.response_builder.response

    # Get the value of the users auth token
    h = handler_input.request_envelope.context.system.user.access_token
    # _list = 'watchlist'
    _usecustomlist = False
    # If we are not auth, let the user know
    if h is None:
        handler_input.response_builder.speak(language.AUTH_ERROR)
        return handler_input.response_builder.response
    # Set all our headers for the trakt-api
    headers = utils.build_headers(h, clientid)
    print("Header= " + str(headers))
    # Get the movie name and throw it onto the movie var
    movie = get_slot_value(handler_input=handler_input, slot_name="movieName")
    use_list = get_slot_value(handler_input=handler_input, slot_name="list_name")
    # reprompt = "Are you sure you want to add "+movie+' to your list ?'
    # user gave us nothing lets do some checks to make sure we have saved attributes
    _list, _usecustomlist = utils.get_list(use_list, _perattr)
    # search for move and get the object
    b = trakt_api.search(movie, headers, "movie", True)
    if b['error']:
        # handle this
        handler_input.response_builder.speak("I couldn't find the show you requested")
        return handler_input.response_builder.response
    # force our movie/show object into a small var to make things easier
    y = b["movie"]
    # dig through our search and add the movie/show to our list or our Watchlist
    if trakt_api.parse_search(b['type'], headers, y, _list, _usecustomlist, True):
        # media_name, media_type, a_list
        utils.notify(movie, b['type'], _list)
        handler_input.response_builder.speak(movie + " has been added to your " + _list + " list")  # .ask(reprompt)
    else:
        # TODO Fix the notify to allow errors
        # utils.notify(movie, b['type'], _list)
        handler_input.response_builder.speak("There was a problem adding " + movie + " to your list " + _list)
    return handler_input.response_builder.response
Пример #12
0
def stats_intent_handler(handler_input):
    """ Handle the stats intent
        TODO: Handle possives countries (eg. "Who is Germany's top scorer")
        TODO: Handle stats other than scorer
    """
    sayings = default_sayings["STATS_INTENT"]
    country_value = get_slot_value(handler_input=handler_input,
                                   slot_name="country")
    stat_value = get_slot_value(handler_input=handler_input, slot_name="stat")
    # This is an 'id' that should represent the season id
    try:
        event_id = (get_slot(handler_input=handler_input,
                             slot_name="event").resolutions.
                    resolutions_per_authority[0].values[0].value.id)
    except:
        event_id = "default"

    event = EVENTS[event_id]
    if not fifa.util.has_season_started(event.season):
        # Short circuit if the season hasn't started
        speech_text = "Sorry, the {} hasn't started yet".format(
            SEASON_NAMES[event.season])
        handler_input.response_builder.speak(
            speech_text).set_should_end_session(False)
        return handler_input.response_builder.response

    if country_value:
        id_team = fifa.util.team_lookup_by_keyword(
            API,
            country_value,
            gender=event.gender,
            football_type=event.football_type,
            age=event.age,
        )[0].id_team
    else:
        id_team = None

    print("event: {} team: {}".format(event.season, id_team))
    results = fifa.util.top_scorer(API, event.season, id_team=id_team, count=1)
    for r in results:
        goal_plural = "goals" if r.goals_scored > 1 else "goal"
        if id_team:
            s = sayings["TEAM_LEADER"]
        else:
            s = sayings["OVERALL_LEADER"]

        speech_text = s.format(r.player_name, r.team_name, r.goals_scored,
                               goal_plural)
    if not results:
        speech_text = "Sorry, I don't have that statistic"

    LOGGER.info("Sending: {}".format(speech_text))

    handler_input.response_builder.speak(speech_text).set_should_end_session(
        False)
    return handler_input.response_builder.response
    def test_get_slot_value_throws_exception_for_non_intent_request(self):
        test_input = self._create_handler_input(
            request=self.test_launch_request)

        with self.assertRaises(
                TypeError,
                msg="get_slot_value method didn't throw TypeError when an "
                    "invalid request type is passed"):
            get_slot_value(
                handler_input=test_input, slot_name=self.test_slot_name)
Пример #14
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     logger.info("In GetINOUTHandler")
     user = get_slot_value(handler_input, 'user')
     time = get_slot_value(handler_input, 'time')
     speak_output = "Inout status of %s is set to %s" % (user, time)
     return (
         handler_input.response_builder
             .speak(speak_output)
             # .ask("add a reprompt if you want to keep the session open for the user to respond")
             .response
     )
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        numero = int(get_slot_value(handler_input=handler_input, slot_name="numero"))
        razao = int(get_slot_value(handler_input=handler_input, slot_name="razao"))
        inicio = int(get_slot_value(handler_input=handler_input, slot_name="inicio"))
        resultado = ProgAritmeticaIntentHandler.calculo_pa(numero, razao, inicio)
        speak_output = "O termo {} da progressão aritmética com razão {} é igual a {}".format(numero, razao, resultado)

        return (
            handler_input.response_builder
                .speak(speak_output)
                .response
        )
Пример #16
0
def make_transfer_intent_handler(handler_input):
    """Handler for Make Transfer Intent."""
    # type: (HandlerInput) -> Response

    name = get_slot_value(handler_input=handler_input, slot_name="name")
    value = float(get_slot_value(handler_input=handler_input, slot_name="value"))
    description = get_slot_value(handler_input=handler_input, slot_name="description")
    assistant = SafraAssistant.deserialize(handler_input.attributes_manager.session_attributes.get("assistant"))
    speech_text = assistant.make_transfer(name, value, description)

    return handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Easy Safra", speech_text)).set_should_end_session(
        False).response
Пример #17
0
 def handle(self, handler_input):
     place = get_slot_value(
         handler_input=handler_input, slot_name="place")
     
     date = get_slot_value(
         handler_input=handler_input, slot_name="date")
         
         
     
     params = {
         'key': key
         'q': place,
         'days': 1, #the number of days to forecast
     }
Пример #18
0
    def handle(self, handler_input):
        home_assistant_object = HomeAssistant(handler_input)

        dates = ask_utils.get_slot_value(handler_input, "Dates")
        times = ask_utils.get_slot_value(handler_input, "Times")

        if not dates and not times:
            raise

        data = handler_input.attributes_manager.request_attributes["_"]
        speak_output = data[prompts.ERROR_SPECIFIC_DATE]

        return (handler_input.response_builder.speak(speak_output).ask(
            '').response)
Пример #19
0
    def handle(self, handler_input):
        place = get_slot_value(handler_input=handler_input, slot_name="place")

        date = get_slot_value(handler_input=handler_input, slot_name="date")

        params = {'key': key, 'q': place, 'dt': date}
        api_result = requests.get('http://api.weatherapi.com/v1/history.json',
                                  params)
        api_response = api_result.json()
        speak_output = "The high in " + str(
            api_response['location']['name']) + " on " + str(
                date) + " was " + str(
                    api_response['forecast']['forecastday'][0]['day']
                    ['maxtemp_f']) + " degrees Fahrenheit"
        return (handler_input.response_builder.speak(speak_output).response)
    def handle(self, handler_input):
        topic = get_slot_value(handler_input=handler_input,
                               slot_name="topic").lower()
        topics_with_id = req.get(BASE_URL + "/api/topics").json()
        topics = [topic["name"].lower() for topic in topics_with_id]

        if topic in topics:
            speak_output = "Let's start! "
            topic_id = topics_with_id[topics.index(topic)]["_id"]
            questions = req.get(BASE_URL + "/api/questions/" + topic_id).json()

            user_id = handler_input.request_envelope.session.user.user_id

            if user_id not in SESSIONS.keys():
                SESSIONS[user_id] = SessionState(topic, questions)
            else:
                if topic not in SESSIONS[user_id].categories.keys():
                    SESSIONS[user_id].load_new_category(topic, questions)
                else:
                    speak_output += "You've answered all questions on this topic. Going back to last topic... "

            speak_output += SESSIONS[user_id].stringify_question()
            if not speak_output:
                speak_output = "There are no more questions available. Please choose another topic."

            return (handler_input.response_builder.speak(speak_output).ask(
                speak_output).response)

        speak_output = topic + " was not found. Ask for different topic or for help."
        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).response)
Пример #21
0
def set_command_intent_handler(handler_input: HandlerInput):
    # Construct and send a custom directive to the connected gadget with data from
    # the SetCommandIntent.
    logger.info("SetCommandIntent received.")

    command = get_slot(handler_input, "Command")

    if (command is None):
        # no slot in request
        return (handler_input.response_builder.speak(
            "Can you repeat that?").ask("What was that again?").response)

    command_id = get_id_from_slot(command)
    spoken_command = get_slot_value(handler_input, "Command")

    session_attr = handler_input.attributes_manager.session_attributes

    endpoint_id = session_attr.get("endpoint_id", [])
    speed = session_attr.get("speed", "50")

    # Construct the directive with the payload containing the move parameters
    payload = {"type": "command", "command": command_id, "speed": speed}
    directive = build_send_directive(NAMESPACE, NAME_CONTROL, endpoint_id,
                                     payload)

    speak_output = "command {} activated".format(spoken_command)
    return (handler_input.response_builder.speak(
        speak_output + BG_MUSIC).add_directive(directive).response)
Пример #22
0
    def handle(self, handler_input):
        print("calling PrioryEventsIntentHandler")
        print("handler input is " + str(handler_input.request_envelope.request.intent))
        key = get_slot_value(handler_input=handler_input, slot_name="day")
        print(f"key is {key}")
        outputs = CommonStaticMethods.lookup_dynamoDB(key)
        len_outputs = len(outputs)
        outputs = [item["Name"] for item in outputs]
        if len_outputs  == 1:
            speak_output = f"The only event on this day is {outputs[0]}"
        if len_outputs > 1:
            speak_output = f"There are {str(len_outputs)} events on this day. They are {CommonStaticMethods.join_list(outputs)}"
        if len_outputs == 0:
            #TODO: say something different if today is this date
            speak_output = "There are no events on this day"
            
        card_title = "Events on this day"
        card_text = speak_output

        print("##################################################")
        print("Voice output from PrioryEventsIntentHandler is "  + str(speak_output))
        print("##################################################")
       # speak_output = "Working."

        return CommonStaticMethods.get_text_and_speach_output(speak_output, handler_input)
Пример #23
0
    def handle(self, handler_input):
        print("calling DayOfEventIntentHandler")
        print("handler input is " + str(handler_input))
        priory_event = get_slot_value(handler_input=handler_input, slot_name="prioryEvent")
        print("PrioryDayOfEventIntentHandler input: " + priory_event)
        items = CommonStaticMethods.get_all_items_from_dynamoDB('Events')
        
        matches = self.get_matches(items, priory_event)

        today = CommonStaticMethods.get_current_date()
        
        output = []
        for item in matches:
            if item["DayTypeEvent"]:
                if item["BeginDay"] and datetime.strptime(item["EndTime"],'%Y-%m-%d').date() >= today:
                    output.append(item)
            else:
                output.append(item)
        outputs = [CommonStaticMethods.item_to_string(item) for item in output]
        
        if (len(outputs) == 0):
            speak_output = "I could not find any events matching " + priory_event
        else:
            speak_output = CommonStaticMethods.join_list(outputs)

        return CommonStaticMethods.get_text_and_speach_output(speak_output, handler_input)
    def handle(self, handler_input):
        # type: (HandlerInput) -> response
        x = ask_utils.get_slot_value(handler_input, "x")
        y = ask_utils.get_slot_value(handler_input, "y")

        req_url = "{}/add/{}/{}".format(API_URL, x, y)
        res = requests.get(req_url)
        res_json = res.json()        

        speak_output = "The answer is: {}".format(res_json.prediction)
        
        return (
            handler_input.response_builder
                .speak(speak_output)
                .response
        )
Пример #25
0
def find_movie_handler(handler_input):
    """Handler for Find Movie Intent"""

    # Get the value of the users auth token
    h = handler_input.request_envelope.context.system.user.access_token
    # If we are not auth, let the user know
    if h is None:
        handler_input.response_builder.speak(language.AUTH_ERROR).ask(language.AUTH_ERROR)
        return handler_input.response_builder.response
    # Set all our headers for the trakt-api
    headers = utils.build_headers(h, clientid)
    movie = get_slot_value(handler_input=handler_input, slot_name="movieName")
    # TODO search the movie var and strip  "on my list" from the end incase Alexa f***s up
    #
    b = trakt_api.search(movie, headers, "movie", True)
    if b['error']:
        # handle this
        reprompt = '_'
        handler_input.response_builder.speak("I couldnt find the movie you requested").ask(reprompt)
        return handler_input.response_builder.response
    # check if its a show or a movie
    # force our movie/show object into a small var to make things easier
    y = b["movie"]

    t = trakt_api.search_lists(y, b, headers, "movie")
    if t['found']:
        # print(movie+" found on the list "+t['list'])
        reprompt = movie + " is already on the list " + t['list']
        handler_input.response_builder.speak(reprompt).ask(reprompt)
        return handler_input.response_builder.response
    else:
        reprompt = movie + " isn't on any of your lists."
        handler_input.response_builder.speak(reprompt).ask(reprompt)
        return handler_input.response_builder.response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "You've answered a question! "
        answer = int(
            get_slot_value(handler_input=handler_input, slot_name="answer"))
        user_id = handler_input.request_envelope.session.user.user_id

        num_of_answers = len(SESSIONS[user_id].current_question["answers"])
        correct = SESSIONS[user_id].current_question["correct"]

        if answer < 1 or answer > num_of_answers:
            speak_output = f"You only had {num_of_answers} possible answers"
        else:
            if answer == correct + 1:
                SESSIONS[user_id].inc_score(True)
                speak_output = "Correct! ..."
            else:
                SESSIONS[user_id].inc_score(False)
                speak_output = f"Sorry, the correct answer should have been: {correct}: "
                speak_output += SESSIONS[user_id].current_question["answers"][
                    correct]
                speak_output += "... "

            SESSIONS[user_id].set_next_question()
            new_question = SESSIONS[user_id].stringify_question()

            if not new_question:
                speak_output += "You've answered all questions in this topic, please pick a new one or quit."
            else:
                speak_output += new_question

        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).response)
Пример #27
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In SensorReadingHandler")

        data = get_readings_from_dynamo()[0]['Items']
        logger.info(data)
        response_alexa = ''
        sensor_slot_value = get_slot_value(handler_input=handler_input, slot_name="AWS.Slot.Sensor")

        if sensor_slot_value:
            slot_value = handler_input.request_envelope.request.intent.slots["AWS.Slot.Sensor"].resolutions.resolutions_per_authority[0].values[0].value.name
            response_alexa += phrase_enum.SENSOR_READING.format(slot_value, str(data[slot_value]))
            if 'temperature' in slot_value:
                response_alexa += '°C.'
            if 'moisture' in slot_value or 'humidity' in slot_value:
                response_alexa += '%.'

        else:
            for key, value in data.items():
                response_alexa += phrase_enum.SENSOR_READING.format(key, str(value))
                if 'temperature' in key:
                    response_alexa += '°C.'
                if 'moisture' in key or 'humidity' in key:
                    response_alexa += '%.'
                response_alexa += ' <break time="300ms"/> '

        handler_input.response_builder.speak(response_alexa)
        return handler_input.response_builder.response
Пример #28
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     logger.info("In getConferenceRoom")
     floor_no = get_slot_value(handler_input, 'FLOOR_NO')
     
     session_attr = handler_input.attributes_manager.session_attributes
     session_attr["floor_no"] = floor_no
     
     if floor_no in rooms.keys():
         rooms_list = rooms[floor_no].keys()
         if len(rooms_list) > 1:
             speak_output = "There are %s room available on %s floor" % (len(rooms_list), floor_no)
             count = 0
             for room in rooms_list:
                 count += 1
                 if count > 1:
                     speak_output += " and %s" % room    
                 else:
                     speak_output += ", %s" % room
             speak_output += ". Would you like to book any room?"  
     else:
         speak_output = "There is no room available on %s floor" % floor_no
     return (
         handler_input.response_builder
             .speak(speak_output)
             .ask(speak_output)
             .response
     )
Пример #29
0
    def handle(self, handler_input):

        diaper_weight = get_slot_value(handler_input=handler_input,
                                       slot_name="diaper")

        persistence_attr = handler_input.attributes_manager.persistent_attributes
        persistence_attr['diaper'] = diaper_weight

        handler_input.attributes_manager.save_persistent_attributes()

        session_attr = handler_input.attributes_manager.session_attributes

        if not session_attr:
            speak_output = "おむつの重さを" + diaper_weight + "グラムで登録します。"

        else:
            pee_poo_session = session_attr["pee_poo"]
            totalweight_session = session_attr["totalweight"]

            delta = int(totalweight_session) - int(diaper_weight)
            speak_output = ("おむつの重さを{0}グラムで計算します。{1}を{2}グラムでメモします。".format(
                diaper_weight, pee_poo_session, delta))

        return (
            handler_input.response_builder.speak(speak_output)
            # .ask("add a reprompt if you want to keep the session open for the user to respond")
            .response)
Пример #30
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        permissions = handler_input.request_envelope.context.system.user.permissions
        if not (permissions and permissions.consent_token):
            return (handler_input.response_builder.speak(
                "Please give permissions to set timers using the alexa app.").
                    set_card(
                        AskForPermissionsConsentCard(
                            permissions=REQUIRED_PERMISSIONS)).response)

        duration_slot_value = ask_utils.get_slot_value(handler_input,
                                                       'duration')
        timer_request = get_custom_task_launch_timer(duration_slot_value)

        timer_service = handler_input.service_client_factory.get_timer_management_service(
        )
        timer_response = timer_service.create_timer(timer_request)

        if str(timer_response.status) == "Status.ON":
            session_attr = handler_input.attributes_manager.session_attributes
            if not session_attr:
                session_attr['lastTimerId'] = timer_response.id
                speech_text = 'Your timer is now running!.'
        else:
            speech_text = 'Timer did not start'

        return (handler_input.response_builder.speak(speech_text).response)