def test_get_slot_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 method didn't throw TypeError when an "
                    "invalid request type is passed"):
            get_slot(handler_input=test_input, slot_name=self.test_slot_name)
 def handle(self, handler_input):
     current_intent = handler_input.request_envelope.request.intent
     stop_val = get_slot(slot_name=SLOT_STOP_NAME,
                         handler_input=handler_input)
     default_route = handler_input.attributes_manager.session_attributes.get(
         R.DEFAULT_ROUTE)
     if stop_val.resolutions:
         # Always true but just in case if later updates change
         matches = stop_val.resolutions.resolutions_per_authority
         if matches[0].status.code == StatusCode.ER_SUCCESS_MATCH:
             matched_stop = matches[0].values[0]
             route = RouteConfig.get_data_route_and_agency_tag(
                 agency_tag="umd", route_tag=default_route[R.ROUTE_TAG])
             stop_id = matched_stop.value.id
             if route.has_stop(stop_id):
                 stop = route.get_stop_by_id(stop_id)
             else:
                 current_intent.slots[SLOT_STOP_NAME].value = None
                 return handler_input.response_builder.add_directive(
                     ElicitSlotDirective(current_intent, SLOT_STOP_NAME)
                 ).speak(
                     "The stop is not a stop for this route. Please try again with a stop name or stop number "
                     "that is in this route").ask(
                         "Provide a stop name or number").response
     #             else needed TODO:
     return handler_input.response_builder.add_directive(
         ConfirmSlotDirective(current_intent, SLOT_STOP_NAME)).speak(
             "The stop you have chosen is %s. Is that okay?" %
             stop.stop_title).ask("Please confirm the stop %s" %
                                  stop.stop_title).response
Exemplo n.º 3
0
    def handle(self, handler_input):
        logger.info("In StadiumHandler")
        if "stadiums" in extra_cmd_prompts:
            del extra_cmd_prompts["stadiums"]
        slot = get_slot(handler_input, "stadiumType")
        dict = slot.resolutions.to_dict()
        success = dict['resolutions_per_authority'][0]["status"]["code"]
        if success == 'ER_SUCCESS_MATCH':
            stadium_id = dict['resolutions_per_authority'][0]["values"][0][
                "value"]["id"]
            stadium_name = dict['resolutions_per_authority'][0]["values"][0][
                "value"]["name"]
            logger.info("found stadium {} {}".format(stadium_id, stadium_name))

            s3 = boto3.client("s3")
            bucket = "bpltables"
            key = "stadiums/" + stadium_name
            logger.info('try to open file ' + bucket + ":" + key)
            resp = s3.get_object(Bucket=bucket, Key=key)
            body_str = resp['Body'].read().decode("utf-8")
            logger.info("converted streaming_body to string")

            speech = body_str
        else:
            logger.info("could not find stadium")
            speech = "Sorry, we could not find that stadium"
        #speech = "in development"
        card_text = "in development"

        handler_input.response_builder.speak(speech).ask(speech).set_card(
            SimpleCard("Stadium", card_text))
        return handler_input.response_builder.response
Exemplo n.º 4
0
def __GetCourseOnlyHandler(handler_input):
    session = get_session(handler_input)
    course = get_resolved_value(get_slot(handler_input, "Course"))
    response = requests.post("https://backend.showcasr.yadunut.com/live",
                             json=GeneratePayload("all", course),
                             headers=FormHeader(session['idToken']))
    message = ""
    if response.status_code == 401:
        message = "Request Error! Unauthorized"
    else:
        session['course'] = None
        json = response.json()
        project_count = json['projectCount']
        if course == "A3DA":
            course = "a. 3. d. a."
        if project_count == 0:
            message = f"Projects from the {course} course was not found"
        else:
            if "all" in course:
                message = f'Here are all projects from all of the courses. There is a total of {project_count} project'
            else:
                message = f'Here are all projects from the {course} course. There is a total of {project_count} project'
            if project_count > 1:
                message += "s"
    message += "."
    message += " Would you like to retrieve other kinds of projects?"
    session['expecting']['projectSearch'] = True
    return handler_input.response_builder.speak(
        message).set_should_end_session(False).response
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def handle(self, handler_input):
        val = get_slot_value(handler_input, "stages")
        stage = str(val)
        slot_dict = get_slot(handler_input, 'stages').to_dict()
        stage_name = slot_dict['resolutions']['resolutions_per_authority'][0][
            'values'][0]['value']['name']

        stages = getStageAppearance(stage_name)

        if len(stages) == 0:
            speak_output = stage_name + ' will not be available in the next 24 hours. Please check back later.'
        else:
            speak_output = 'You can play ' + stage_name + ' next '
            if len(stages) == 1:
                speak_output += stages[0] + '.'
            else:
                for i in range(len(stages)):
                    if i == len(
                            stages
                    ) - 1:  # If we are on the last stage of the list
                        speak_output += ' and ' + stages[i] + '.'
                    else:
                        speak_output += stages[i] + ', '

        return (handler_input.response_builder.speak(speak_output).response)
Exemplo n.º 7
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
 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
    def test_get_slot_returns_none_for_non_existent_slot(self):
        test_input = self._create_handler_input(
            request=self.test_intent_request)

        self.assertEqual(
            get_slot(handler_input=test_input, slot_name="some_slot"), None,
            "get_slot method didn't return None from input request "
            "when a non-existent slot name is passed")
    def test_get_slot(self):
        test_input = self._create_handler_input(
            request=self.test_intent_request)

        self.assertEqual(
            get_slot(handler_input=test_input, slot_name=self.test_slot_name),
            self.test_slot,
            "get_slot method returned incorrect slot from input request "
            "when a valid slot name is passed")
    def test_get_slot_returns_none_for_no_slots(self):
        self.test_intent_request.intent.slots = None
        test_input = self._create_handler_input(
            request=self.test_intent_request)

        self.assertEqual(
            get_slot(handler_input=test_input, slot_name="some_slot"), None,
            "get_slot method didn't return None from input request "
            "when intent request has no slots")
Exemplo n.º 12
0
 def handle(self, handler_input):
     val = get_slot_value(handler_input, "weapon")
     weapon = str(val)
     slot_dict = get_slot(handler_input, 'weapon').to_dict(
     )  # change happened here ==================================================
     weapon_name = slot_dict['resolutions']['resolutions_per_authority'][0][
         'values'][0]['value']['name']
     speak_output = getWeaponInfoIntent(weapon_name)  #previously 'weapon'
     return (handler_input.response_builder.speak(speak_output).response)
Exemplo n.º 13
0
 def get_value_for_slot(self, handler_input, slot_name):
     """"Get value from slot, also know as the (why does amazon make you do this code)"""
     slot = ask_utils.get_slot(handler_input, slot_name=slot_name)
     if slot and slot.resolutions and slot.resolutions.resolutions_per_authority:
         for resolution in slot.resolutions.resolutions_per_authority:
             if resolution.status.code == StatusCode.ER_SUCCESS_MATCH:
                 for value in resolution.values:
                     if value.value and value.value.name:
                         return value.value.name
Exemplo n.º 14
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
Exemplo n.º 15
0
def matches_intent_handler(handler_input):
    sayings = default_sayings["MATCHES_INTENT"]

    # 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 fifa.util.has_season_ended(event.season):
        # Short circuit if the season already ended
        speech_text = "Sorry, the {} has already ended".format(
            SEASON_NAMES[event.season])
        handler_input.response_builder.speak(
            speech_text).set_should_end_session(False)
        return handler_input.response_builder.response

    timeframe_dt = fifa.util.date_parse(
        get_slot_value(handler_input=handler_input, slot_name="timeframe"))
    delta = fifa.util.day_delta(timeframe_dt)
    if delta.friendly_name == "today" or delta.friendly_name == "tomorrow":
        s = sayings["MATCHES_RELATIVE"]
    else:
        s = sayings["MATCHES_DATE"]

    speech_text = ""
    results = fifa.util.matches_by_date(API,
                                        event.season,
                                        event.competition,
                                        on_date=timeframe_dt)
    for i, v in enumerate(results, 1):
        if i == len(results) and i > 1:
            s = sayings["MATCHES_CONTINUED"]
            speech_text += " and " + s.format(v.home_team_name,
                                              v.away_team_name)
        elif i > 1:
            s = sayings["MATCHES_CONTINUED"]
            speech_text += ", " + s.format(v.home_team_name, v.away_team_name)
            continue
        else:
            speech_text += s.format(delta.friendly_name, v.home_team_name,
                                    v.away_team_name)

    if not results:
        s = sayings["NO_MATCHES"]
        speech_text = s.format(timeframe_dt.strftime("%m%d"))

    LOGGER.info("Sending: {}".format(speech_text))
    handler_input.response_builder.speak(speech_text).set_should_end_session(
        False)

    return handler_input.response_builder.response
Exemplo n.º 16
0
def live_matches_intent_handler(handler_input):
    sayings = default_sayings["LIVE_MATCH_INTENT"]
    # 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

    speech_text = ""
    live_matches = fifa.util.live_scores(API, event.season)

    for i, v in enumerate(live_matches, 1):
        if i > 1:
            s = sayings["MATCH_STATUS_CONTINUED"]
            speech_text += " " + s.format(
                v.home_team_name,
                v.away_team_name,
                v.match_time,
                v.home_team_name,
                v.home_team_score,
                v.away_team_name,
                v.away_team_score,
            )
        else:
            s = sayings["MATCH_STATUS"]
            speech_text += s.format(
                v.home_team_name,
                v.away_team_name,
                v.match_time,
                v.home_team_name,
                v.home_team_score,
                v.away_team_name,
                v.away_team_score,
            )

    if not live_matches:
        speech_text = sayings["NO_MATCHES"]

    LOGGER.info("Sending: {}".format(speech_text))
    handler_input.response_builder.speak(speech_text).set_should_end_session(
        False)

    return handler_input.response_builder.response
Exemplo n.º 17
0
def GetCourseHandler(handler_input):
    """ Handler for getting Course """
    course_slot = get_slot(handler_input, "Course")
    session = get_session(handler_input)
    if course_slot.value is None or get_resolved_value(course_slot) is None:
        return handler_input.response_builder.speak(
            "Sorry, I did not get that. What course do you want?"
        ).add_directive(ElicitSlotDirective(slot_to_elicit="Course")).response
    else:
        value = get_resolved_value(course_slot)
        session['course'] = value
        return ProjectHandler(handler_input, "")
Exemplo n.º 18
0
def GetTypeHandler(handler_input):
    """ Handler for getting Project Type """
    tag = get_slot(handler_input, "ProjectType")
    session = get_session(handler_input)
    logger.info("ProjectType slot: {}".format(tag))

    if tag.value is None:
        return handler_input.response_builder.speak(
            "Sorry I did not get that. What type of projects do you want?"
        ).add_directive(
            ElicitSlotDirective(slot_to_elicit="ProjectType")).response
    else:
        session['tag'] = tag.value
        return ProjectHandler(handler_input, "")
Exemplo n.º 19
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        logger.debug("In CompletedFavoriteStopHandler")

        # Boilerplate
        _ = handler_input.attributes_manager.request_attributes["_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes
        session_attributes = handler_input.attributes_manager.session_attributes

        # Retrieve slot values
        logger.debug("Slots %s",
                     handler_input.request_envelope.request.intent.slots)
        # Todo: retrieve this properly via entity resolution results
        destination_name = get_slot_value(handler_input, "destination_name")
        logger.debug("Destination: %s", destination_name)
        stop_name_slot = get_slot(handler_input, "stop_name")
        success_slot_er_results = self._parse_successful_entity_resolution_results_for_slot(
            stop_name_slot)
        session_line_details = session_attributes["session_line_details"]
        correct_slot_value = self._filter_correct_slot_value(
            success_slot_er_results, session_line_details, destination_name)
        logger.debug("Correct stop name slot value: %s", correct_slot_value)
        stop_id = correct_slot_value["id"]
        stop_name_fr = correct_slot_value["stopNameFr"]
        line_id = session_attributes["favorite_line_id"]
        stib_transportation_type = session_attributes[
            "favorite_transportation_type"]

        # Update persistent attributes
        persistent_attributes[
            "favorite_transportation_type"] = stib_transportation_type
        persistent_attributes["favorite_line_id"] = line_id
        persistent_attributes["favorite_line_destination"] = destination_name
        persistent_attributes["favorite_stop_id"] = stop_id
        persistent_attributes["favorite_stop_name"] = stop_name_fr
        handler_input.attributes_manager.save_persistent_attributes()

        # Prepare skill response
        speech = _(data.PREFERENCES_SAVED).format(stib_transportation_type,
                                                  line_id, stop_name_fr,
                                                  destination_name)
        reprompt_speech = _(data.SKILL_DESCRIPTION_WITH_PREFERENCES)
        speech += " " + reprompt_speech

        # Update repeat prompt
        session_attributes["repeat_prompt"] = reprompt_speech

        return (handler_input.response_builder.speak(speech).ask(
            reprompt_speech).response)
Exemplo n.º 20
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        print('handling weight')
        intent_name = ask_utils.get_intent_name(handler_input)
        print(f'triggered intent {intent_name}')

        weight_value_slot = ask_utils.get_slot(handler_input,
                                               "USER_WEIGHT_VALUE")
        print(
            f'got weight value slot: {weight_value_slot.name} {weight_value_slot.value} {weight_value_slot.confirmation_status}'
        )
        weight_units_slot = ask_utils.get_slot(handler_input,
                                               "USER_WEIGHT_UNITS")
        print(
            f'got weight units slot: {weight_units_slot.name} {weight_units_slot.value} {weight_units_slot.confirmation_status}'
        )

        speak_output = f"I'm adding the weight {weight_value_slot.value} {weight_units_slot.value}"
        print(speak_output)

        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)
Exemplo n.º 21
0
    def handle(self, handler_input):
        logger.info("In TeamHandler")
        reload_main_table_as_needed()
        slot = get_slot(handler_input, "plteam")
        dict = slot.resolutions.to_dict()
        success = dict['resolutions_per_authority'][0]["status"]["code"]
        if success == 'ER_SUCCESS_MATCH':
            team_id = dict['resolutions_per_authority'][0]["values"][0][
                "value"]["id"]
            team_name = dict['resolutions_per_authority'][0]["values"][0][
                "value"]["name"]
            logger.info("found team {} {}".format(team_id, team_name))
            this_team_index = find_team_index(team_id)
            if this_team_index == -1:
                logger.info("could not find team")
            else:
                speech = "You asked about " + team_name + ", their form is "
                form = say_place(this_team_index + 1) + " with " + pluralize(
                    table_data[this_team_index][WINS_INDEX], "win", 's') + ", "
                form = form + pluralize(
                    table_data[this_team_index][DRAWS_INDEX], " draw",
                    's') + ", "
                form = form + pluralize(
                    table_data[this_team_index][LOSSES_INDEX], " loss",
                    'es') + ", "
                form = form + pluralize(
                    table_data[this_team_index][GOALS_FOR_INDEX], " goal",
                    's') + " scored, "
                form = form + pluralize(
                    table_data[this_team_index][GOALS_AGAINST_INDEX], " goal",
                    's') + " allowed, "
                form = form + " for a goal difference of " + table_data[
                    this_team_index][GOAL_DIFF_INDEX] + ", and "
                form = form + pluralize(
                    table_data[this_team_index][POINTS_INDEX], " point",
                    's') + ", "
                form = get_excitement_prefix(
                    this_team_index) + form + get_excitement_suffix()
                speech = speech + form + random_prompt()
        else:
            err_msg = "could not find team with that name, please try again or ask us for a list of team names"
            logger.info(err_msg)
            speech = err_msg

        handler_input.response_builder.speak(speech).ask(speech).set_card(
            SimpleCard("Hello PremierLeague", speech))
        return handler_input.response_builder.response
Exemplo n.º 22
0
    def handle(self, handler_input, query_food_id=None):
        # type: (HandlerInput) -> Response

        slot = ask_utils.get_slot(handler_input, "food")

        if slot:
            # スロット値がマッチしてないとき
            if slot.resolutions.resolutions_per_authority[
                    0].status.code != StatusCode.ER_SUCCESS_MATCH:
                print("マッチしませんでした")
                return FallbackIntentHandler.handle(self, handler_input)

            query_food_id = slot.resolutions.resolutions_per_authority[
                0].values[0].value.id
            query_food_name = slot.resolutions.resolutions_per_authority[
                0].values[0].value.name

        if not query_food_id:
            # エラーハンドリング
            print("カテゴリが見つかりませんでした")
            return CatchAllExceptionHandler.handle(self, handler_input)

        # セッション変数に答えをいれておく
        handler_input.attributes_manager.session_attributes[
            'query_food_id'] = query_food_id

        print("クエリの食べ物は%sです" % query_food_id)

        ranking = RANKING[str(query_food_id)]

        vitamin = sorted(ranking.items(), key=lambda x: x[1])[-1][0]
        handler_input.attributes_manager.session_attributes[
            'answer_vitamin'] = vitamin
        print("足りないビタミンは%s" % vitamin)

        food = random.choice(ANSWER[vitamin])
        # 回答済みの答えもいれておく
        handler_input.attributes_manager.session_attributes[
            'answered_foods'] = [food]
        print("おすすめの食材は%s" % food)

        speak_output = vitamin + "を追加で摂取するとよいかもしれません。オススメの食材は" + food + "です。ほかの候補が知りたいときは、ほかには、と聞いてください"

        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).response)
Exemplo n.º 23
0
def CourseHelpHandler(handler_input):
    course_slot = get_slot(handler_input, "Course")
    if course_slot.value is None:
        return ProjectHandler(handler_input,
                              "There is IMGD, IT, FI, ISF, and A3DA.")
    course = get_resolved_value(course_slot)
    message = ""
    if course == "ISF":
        message = "i. s. f. is about cybersecurity. "
    elif course == "FI":
        message = "f. i. is about finance. "
    elif course == "IT":
        message = "i. t. is about programming. "
    elif course == "A3DA":
        message = "a. three. d. a. is about animation. "
    elif course == "IMGD":
        message = "i. m. g. d. is about game design. "
    return ProjectHandler(handler_input, message)
    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 = get_slot_value(handler_input=handler_input, slot_name="myName")
            TO_NAME = get_slot_value(handler_input=handler_input, slot_name="toName")

            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
                }
            )
Exemplo n.º 25
0
    def handle(self, handler_input):
        #What hall?
        hallSlot = ask_utils.get_slot(handler_input=handler_input,
                                      slot_name="hall")
        try:
            hallID = hallSlot.resolutions.resolutions_per_authority[0].values[
                0].value.id
        except:
            hallID = "ALL"

        #What day?
        dateValue = ask_utils.get_slot_value(handler_input=handler_input,
                                             slot_name="menuDate")
        if not dateValue:
            dateValue = ""

        #What meal?
        menuName = ask_utils.get_intent_name(handler_input)
        if menuName == "BreakfastMenu":
            meal = 0
        elif menuName == "LunchMenu":
            meal = 1
        elif menuName == "DinnerMenu":
            meal = 2

        if hallID == "ALL":
            page = self.pullA(dateValue, meal)
            output = [
                self.scrape(hall) for hall in page.findAll(class_="meal row")
            ]
            print("initial output complete")
            output = [
                "In Taylor Dining:", output[2], "In Thomas Dining:", output[3],
                "At Stevenson Deli: ", output[1], "At Stevenson Grill: ",
                output[0], "At the Union: ", output[4]
            ]
            print("output sorting complete")
            output = ";".join(output)
            print("output complete")
        else:
            page = self.pullH(hallID, dateValue, meal)
            output = self.scrape(page)

        return (handler_input.response_builder.speak(output).response)
 def handle(self, handler_input):
     current_intent = handler_input.request_envelope.request.intent
     obj_serializer = DefaultSerializer()
     stop_val = get_slot(slot_name=SLOT_STOP_NAME,
                         handler_input=handler_input)
     default_route = handler_input.attributes_manager.session_attributes.get(
         R.DEFAULT_ROUTE)
     current_intent.confirmation_status = IntentConfirmationStatus.NONE
     matches = stop_val.resolutions.resolutions_per_authority
     # If the stop was matched with a valid name
     if matches[0].status.code == StatusCode.ER_SUCCESS_MATCH:
         matched_stop = matches[0].values[0]
         route = RouteConfig.get_data_route_and_agency_tag(
             agency_tag="umd", route_tag=default_route[R.ROUTE_TAG])
         stop_id = matched_stop.value.id
         if route.has_stop(stop_id):
             stop = route.get_stop_by_id(stop_id)
             handler_input.attributes_manager.session_attributes[
                 R.DEFAULT_STOP] = obj_serializer.serialize({
                     R.STOP_ID:
                     stop.stop_id,
                     R.DIRECTION:
                     stop.direction,
                     R.STOP_TITLE:
                     stop.stop_title
                 })
         else:
             current_intent.slots[SLOT_STOP_NAME].value = None
             current_intent.slots[
                 SLOT_STOP_NAME].confirmation_status = SlotConfirmationStatus.NONE
             return handler_input.response_builder.add_directive(
                 ElicitSlotDirective(current_intent, SLOT_STOP_NAME)
             ).speak(
                 "The stop while confirming is not a stop for this route. Please try again with a stop name or stop number "
                 "that is in this route").ask(
                     "Provide a stop name or stop number").response
     return handler_input.response_builder.add_directive(
         ConfirmIntentDirective(current_intent)).speak(
             "I am setting these defaults. Is that okay?").response
Exemplo n.º 27
0
def move_intent_handler(handler_input: HandlerInput):
    # Construct and send a custom directive to the connected gadget with
    # data from the MoveIntent request.
    logger.info("MoveIntent received.")

    direction = get_slot(handler_input, "Direction")
    direction_id = get_id_from_slot(direction)
    spoken_direction = get_slot_value(handler_input, "Direction")

    # Duration is optional, use default if not available
    duration = get_slot_value(handler_input, "Duration")
    if duration is None:
        duration = 2

    # Get data from session attribute
    session_attr = handler_input.attributes_manager.session_attributes

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

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

    speak_output = "Applying brake" if (direction_id == "stop") else (
        "{} {} seconds at {} percent speed".format(spoken_direction, duration,
                                                   speed))

    return (handler_input.response_builder.speak(speak_output).add_directive(
        directive).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.DENIED
Exemplo n.º 29
0
def results_intent_handler(handler_input):
    sayings = default_sayings["RESULTS_INTENT"]
    # 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

    timeframe_dt = fifa.util.date_parse(
        get_slot_value(handler_input=handler_input, slot_name="timeframe"))
    delta = fifa.util.day_delta(timeframe_dt)

    speech_text = ""
    results = fifa.util.matches_by_date(API,
                                        event.season,
                                        event.competition,
                                        on_date=timeframe_dt)
    for i, v in enumerate(results, 1):
        # Find out who the winner was
        draw_key_suffix = ""
        if v.home_team_score > v.away_team_score:
            winner_name, winner_score = v.home_team_name, v.home_team_score
            loser_name, loser_score = v.away_team_name, v.away_team_score
        elif v.away_team_score > v.home_team_score:
            winner_name, winner_score = v.away_team_name, v.away_team_score
            loser_name, loser_score = v.home_team_name, v.home_team_score
        elif v.away_team_score == v.home_team_score:
            draw_key_suffix = "_DRAW"

        # Send the results to be spoken
        if i == len(results) and i > 1:
            # This is the last element case
            s = sayings["RESULTS_CONTINUED" + draw_key_suffix]
            speech_text += " and " + s.format(delta.friendly_name, winner_name,
                                              loser_name, winner_score,
                                              loser_score)
        elif i > 1:
            s = sayings["RESULTS_CONTINUED" + draw_key_suffix]
            speech_text += ", " + s.format(delta.friendly_name, winner_name,
                                           loser_name, winner_score,
                                           loser_score)
            continue
        else:
            # This is the first element case
            # Find out if we should respond with a "friendly relative time (eg. yesterday)"
            date_key_suffix = ""
            if delta.friendly_name == "today" or delta.friendly_name == "tomorrow":
                date_key_suffix = "_RELATIVE"

            s = sayings["RESULTS" + date_key_suffix + draw_key_suffix]
            speech_text += s.format(delta.friendly_name, winner_name,
                                    loser_name, winner_score, loser_score)

    if not results:
        s = sayings["NO_RESULTS"]
        speech_text = s.format(timeframe_dt.strftime("%m%d"))

    LOGGER.info("Sending: {}".format(speech_text))
    handler_input.response_builder.speak(speech_text).set_should_end_session(
        False)

    return handler_input.response_builder.response
Exemplo n.º 30
0
def where_to_watch_intent_handler(handler_input):
    """ Get Broadcast information
    """
    sayings = default_sayings["WHERE_TO_WATCH_INTENT"]
    country = get_slot_value(handler_input=handler_input, slot_name="country")
    country_code = fifa.util.country_iso(country).alpha2
    team_name = get_slot_value(handler_input=handler_input, slot_name="team")
    speech_text = "I am unable to find viewing info for {}".format(country)

    # 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 fifa.util.has_season_ended(event.season):
        # Short circuit if the season already ended
        speech_text = "Sorry, the {} has already ended".format(
            SEASON_NAMES[event.season])
        handler_input.response_builder.speak(
            speech_text).set_should_end_session(False)
        return handler_input.response_builder.response

    def concat_tv_sources(sources):
        """ Take a list and output a string of TV sources
        """
        tv_sources = ""
        for i, v in enumerate(sources, 1):
            if i == 1:
                # First element
                tv_sources += "{} ".format(v)
            elif i == len(sources):
                # Last element
                tv_sources += "or {}".format(v)
            else:
                tv_sources += ", {} ".format(v)
        return tv_sources

    if not team_name:
        # We should have a country at least. The interaction model validates this
        s = sayings["WHERE_BY_CC"]
        where_to_watch = fifa.util.where_to_watch(API, event.season,
                                                  country_code)
        tv_sources = concat_tv_sources(where_to_watch.sources)
        speech_text = s.format(country, tv_sources)

    elif team_name:
        s = sayings["WHERE_BY_CC_AND_MATCH"]
        team_info = fifa.util.team_lookup_by_keyword(
            API,
            country,
            gender=event.gender,
            football_type=event.football_type,
            age=event.age,
        )[0]
        # Get the next match for this team
        match = fifa.util.matches_next(API,
                                       event.season,
                                       event.competition,
                                       id_team=team_info.id_team)[0]
        id_match = match.id_match
        where_to_watch = fifa.util.where_to_watch(API,
                                                  event.season,
                                                  country_code,
                                                  id_match=id_match)
        tv_sources = concat_tv_sources(where_to_watch.sources)

        # We want to say the requested team first
        team1 = team_info.team_name
        if team_info.team_name == match.home_team_name:
            team2 = match.away_team_name
        else:
            team2 = match.home_team_name

        speech_text = s.format(country, team1, team2, tv_sources)

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

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