def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        curr_req = handler_input.request_envelope.request

        # delegate directive for reorder intent
        reorder_intent = Intent(
            name="ReorderMedicinesIntent",
            slots={},
            confirmation_status=IntentConfirmationStatus.NONE)
        reorder_intent_directive = DelegateDirective(reorder_intent)

        # delegate intent for stop intent
        stop_intent = Intent(name="AMAZON.StopIntent",
                             slots={},
                             confirmation_status=IntentConfirmationStatus.NONE)
        stop_intent_directive = DelegateDirective(stop_intent)

        # delegate directive intent for current intent
        current_intent = Intent(
            name=curr_req.intent.name,
            slots=curr_req.intent.slots,
            confirmation_status=curr_req.intent.confirmation_status)
        confirm_intent_directive = DelegateDirective(current_intent)

        med_data = Utils.get_remaining_stock()
        speech, reorder_meds = data.get_remaining_stock_intent_response(
            med_data)

        # add reorder meds to session attributes to enable access from reorder intent handler
        handler_input.attributes_manager.session_attributes[
            'reorder_meds'] = reorder_meds

        # if user has allowed the intent to reorder medicines, then set dialog_state in the request to completed
        # to allow the dialog model to end
        if curr_req.intent.confirmation_status == IntentConfirmationStatus.CONFIRMED:
            handler_input.request_envelope.request.dialog_state = 'COMPLETED'

        # got to AMAZON.StopIntent when the user denies intent confirmation and stop the dialog model
        if curr_req.intent.confirmation_status == IntentConfirmationStatus.DENIED:
            return (handler_input.response_builder.speak("Okay").add_directive(
                stop_intent_directive).response)

        if handler_input.request_envelope.request.dialog_state != "COMPLETED":
            return (handler_input.response_builder.add_directive(
                confirm_intent_directive).speak(speech).response)
        else:
            return (handler_input.response_builder.speak(speech).add_directive(
                reorder_intent_directive).response)
    def setUp(self):
        self.test_locale = "foo_locale"
        self.test_request_type = "LaunchRequest"
        self.test_dialog_state = DialogState.COMPLETED
        self.test_intent_name = "foo_intent"
        self.test_slot_name = "foo_slot"
        self.test_slot_value = "foo_slot_value"
        self.test_slot = Slot(name=self.test_slot_name,
                              value=self.test_slot_value)
        self.test_api_access_token = "foo_api_access_token"
        self.test_access_token = "foo_account_linking_access_token"
        self.test_device_id = "foo_device_id"
        self.test_supported_interfaces = SupportedInterfaces(
            display=DisplayInterface(template_version="test_template",
                                     markup_version="test_markup"))
        self.test_new_session = False

        self.test_launch_request = LaunchRequest(locale=self.test_locale)
        self.test_intent_request = IntentRequest(
            dialog_state=self.test_dialog_state,
            intent=Intent(name=self.test_intent_name,
                          slots={
                              self.test_slot_name:
                              Slot(name=self.test_slot_name,
                                   value=self.test_slot_value)
                          }))
        self.test_request_envelope = RequestEnvelope(
            session=Session(new=self.test_new_session),
            context=Context(
                system=SystemState(user=User(
                    access_token=self.test_access_token),
                                   api_access_token=self.test_api_access_token,
                                   device=Device(device_id=self.test_device_id,
                                                 supported_interfaces=self.
                                                 test_supported_interfaces))))
    def handle(self, handler_input):
        sess_attrs = handler_input.attributes_manager.session_attributes
        intent_to_explore = sess_attrs.get("explore_intent", "")
        i18n = get_i18n(handler_input)

        if intent_to_explore == ExploreIntents.EXPLORE_SETUP_INTENT:
            slots = {"code": Slot(name="code")}
            intent = Intent(name='SetupIntent', slots=slots)
            handler_input.response_builder.add_directive(DelegateDirective(updated_intent=intent))
            return handler_input.response_builder.response

        if intent_to_explore == ExploreIntents.EXPLORE_MESSAGE_INTENT:
            intent = Intent(name='MessageIntent')
            handler_input.response_builder.add_directive(DelegateDirective(updated_intent=intent))
            return handler_input.response_builder.response

        return handler_input.response_builder.speak(i18n.SUGGEST_WHAT_TO_DO).ask(i18n.FALLBACK).response
Exemple #4
0
 def build_request(self):
     """
     Builds the request
     Returns: (IntentRequest) the build IntentRequest
     """
     return IntentRequest(request_id=self.request_id,
                          timestamp=datetime.datetime.now(),
                          locale=self.skill_settings.locale,
                          intent=Intent(self.intent_name, self.slots, IntentConfirmationStatus.NONE))
Exemple #5
0
    def handle(self, handler_input):
        i18n = Constants.i18n
        telethon_service = TelethonService()
        sess_attrs = handler_input.attributes_manager.session_attributes
        user_is_authorized = sess_attrs.get("ACCOUNT").get("AUTHORIZED")
        account = sess_attrs.get("ACCOUNT")
        slots = handler_input.request_envelope.request.intent.slots
        reprompt = None

        if user_is_authorized:
            speech_text = i18n.ALREADY_AUTHORIZED
            handler_input.response_builder.speak(speech_text) \
                .set_should_end_session(False).ask(i18n.FALLBACK)
            return handler_input.response_builder.response
        if not account.get("PHONE_NUMBER"):
            speech_text = i18n.NO_PHONE
            should_end = True
        elif not slots.get("code").value:
            try:
                phone_code_hash = telethon_service.send_code_request()
            except TelethonException as error:
                return handle_telethon_error_response(
                    error, handler_input).response_builder.response

            sess_attrs["PHONE_CODE_HASH"] = phone_code_hash

            updated_intent = Intent("AuthorizationIntent", slots)
            elicit_directive = ElicitSlotDirective(updated_intent, "code")
            handler_input.response_builder.add_directive(elicit_directive)

            speech_text = i18n.WHAT_IS_CODE
            reprompt = i18n.WHAT_IS_CODE_REPROMPT
            should_end = False
        else:
            phone_code_hash = sess_attrs.get("PHONE_CODE_HASH")
            try:
                ok = telethon_service.sign_user_in(
                    slots.get("code").value, phone_code_hash)
            except TelethonException as error:
                return handle_telethon_error_response(
                    error, handler_input).response_builder.response

            if ok:
                sess_attrs["ACCOUNT"]["AUTHORIZED"] = True
                speech_text = i18n.AUTHORIZED
                reprompt = i18n.FALLBACK
                should_end = False
            else:
                speech_text = i18n.WRONG_CODE
                should_end = True

        handler_input.response_builder.speak(speech_text) \
            .set_should_end_session(should_end)
        if reprompt:
            handler_input.response_builder.ask(reprompt)

        return handler_input.response_builder.response
Exemple #6
0
def test_is_intent_name_not_match():
    test_intent_name = "TestIntent"
    test_handler_input = HandlerInput(request_envelope=RequestEnvelope(
        request=IntentRequest(intent=Intent(name=test_intent_name))))

    intent_name_wrapper = is_intent_name("TestIntent1")
    assert not intent_name_wrapper(
        test_handler_input), "is_intent_name matcher matched with the " \
                             "incorrect intent name"
Exemple #7
0
def test_is_intent_name_match():
    test_intent_name = "TestIntent"
    test_handler_input = HandlerInput(request_envelope=RequestEnvelope(
        request=IntentRequest(intent=Intent(name=test_intent_name))))

    intent_name_wrapper = is_intent_name(test_intent_name)
    assert intent_name_wrapper(
        test_handler_input), "is_intent_name matcher didn't match with the " \
                             "correct intent name"
def test_is_intent_not_match_canfulfill_intent():
    test_intent_name = "TestIntent"
    test_handler_input = HandlerInput(
        request_envelope=RequestEnvelope(request=IntentRequest(
            intent=Intent(name=test_intent_name))))

    canfulfill_intent_name_wrapper = is_canfulfill_intent_name(test_intent_name)
    assert not canfulfill_intent_name_wrapper(
        test_handler_input), "is_canfulfill_intent_name matcher matched with the " \
                             "incorrect request type"
Exemple #9
0
def create_handler_input(slots: Dict[str, Slot],
                         attributes: Dict) -> HandlerInput:
    request_envelope = RequestEnvelope(version="v1",
                                       session=Session(attributes=attributes),
                                       request=IntentRequest(
                                           request_id=str(uuid4()),
                                           intent=Intent(name="test intent",
                                                         slots=slots)))
    attributes_manager = AttributesManager(request_envelope=request_envelope)
    handler_input = HandlerInput(request_envelope=request_envelope,
                                 attributes_manager=attributes_manager)
    return handler_input
Exemple #10
0
def bet_handler(handler_input):
    # handles that a bet has been set and remembers amount
    request_id_holder = handler_input.request_envelope.request.request_id
    directive_header = Header(request_id=request_id_holder)
    slots = handler_input.request_envelope.request.intent.slots

    bet = slots["amount"].value
    gm.player_chips.bet = int(bet)
    if not game_functions.can_bet(gm.player_chips.bet, gm.player_chips):
        output = f"""Sorry but you do not have enough for that bet.  You have a total of 
        {gm.player_chips.total}, how much would you like to bet?"""
        # speech = SpeakDirective(speech=output)
        # directive_request = SendDirectiveRequest(
        #     header=directive_header, directive=speech
        # )
        # directive_service_client = (
        #     handler_input.service_client_factory.get_directive_service()
        # )
        # directive_service_client.enqueue(directive_request)

        return (handler_input.response_builder.speak(output).add_directive(
            ElicitSlotDirective(
                slot_to_elicit="amount",
                updated_intent=Intent(
                    name="Betting",
                    confirmation_status=IntentConfirmationStatus.NONE,
                    slots={
                        "amount":
                        Slot(
                            name="amount",
                            confirmation_status=SlotConfirmationStatus.NONE,
                        )
                    },
                ),
            )).response)

    p_hand = gm.player_hand.hand_held()
    a_hand = gm.alexa_hand.holding()
    print("alexa: ", gm.alexa_hand.holding())
    print("player: ", gm.player_hand.holding())
    print("chips : ", gm.player_chips.total, "bet :", gm.player_chips.bet)
    output = f"""Okay you bet {bet}. You have {p_hand}.
    I have a {a_hand[1][1]} of {a_hand[1][0]} showing. What you like to  Hit or Stand?"""

    return (handler_input.response_builder.speak(
        output).set_should_end_session(False).response)
Exemple #11
0
def ready_game_handler(handler_input):
    # handles the start of the game setting up how many rounds
    # current_intent gets details about returned intent for checking use .name, .slots etc
    current_intent = handler_input.request_envelope.request.intent
    game_session_attr = handler_input.attributes_manager.session_attributes

    logger.info("In ReadyGameHandler")
    if (
        current_intent.slots["game_length"].name in required_slots
        and current_intent.slots["game_length"].value not in rounds_allowed
    ):

        return (
            handler_input.response_builder.speak(
                "ok how big a deck of cards should I use? "
                "Five is a short game, Fifteen is X minutes, Twenty-Five "
                "is the about XX minutes but gives the most accurate score "
            )
            .ask("five ten or fifteen")
            .add_directive(
                ElicitSlotDirective(
                    slot_to_elicit="game_length",
                    updated_intent=Intent(
                        name="ReadyGame",
                        confirmation_status=IntentConfirmationStatus.NONE,
                        slots={
                            "game_length": Slot(
                                name="game_length",
                                confirmation_status=SlotConfirmationStatus.NONE,
                            )
                        },
                    ),
                )
            )
            .response
        )
    # game_session_attr['DECK_SIZE'] = current_intent.slots["game_length"].value
    # game_session_attr['GAME_RUNNING'] = 1
    return handler_input.response_builder.add_directive(
        DelegateDirective(updated_intent=current_intent)
    ).response
def create_intent_request(round_index: int,
                          user_utterance: str) -> IntentRequest:
    """Creates an intent request."""
    intent_request = IntentRequest(
        request_id='{}.{}'.format(REQUEST_ID_BASE, round_index),
        timestamp=datetime.datetime.utcnow(),
        locale='en-US',
        dialog_state=None,
        intent=Intent(
            name='ConverseIntent',
            slots=dict(Text=Slot(
                name='Text',
                value=user_utterance,
                confirmation_status=SlotConfirmationStatus.NONE,
                resolutions=Resolutions(resolutions_per_authority=[
                    Resolution(
                        authority='{}.TEXT'.format(RESOLUTION_AUTHORITY_BASE),
                        status=Status(code=StatusCode.ER_SUCCESS_NO_MATCH))
                ]))),
            confirmation_status=IntentConfirmationStatus.NONE))
    return intent_request
Exemple #13
0
    def handle(self, handler_input):
        self.telethon_service = TelethonService()
        sess_attrs = handler_input.attributes_manager.session_attributes
        i18n = Constants.i18n
        slots = handler_input.request_envelope.request.intent.slots

        if not sess_attrs.get("ENTITY_IDS"):
            speech_text = i18n.NO_TELETHON_ID
            return handler_input.response_builder.speak(speech_text) \
            .set_should_end_session(False).ask(i18n.FALLBACK).response

        if slots.get("message").value:
            if sess_attrs.get("TELEGRAMS_COUNTER") is None:
                # User is replying on last unread dialog
                index = len(sess_attrs.get("CONTACTS")) - 1
            else:
                # User is replying to some other dialog
                index = sess_attrs.get("TELEGRAMS_COUNTER") - 1

            contact = sess_attrs.get("CONTACTS")[index]
            entity_id = sess_attrs.get("ENTITY_IDS")[index]
            self.telethon_service \
                .send_telegram(entity_id, slots.get("message").value)

            next_telegram = MessageIntentHandler().get_telegram(handler_input)
            speech_text = i18n.TELEGRAM_SENT.format(contact) + next_telegram
            reprompt = i18n.FALLBACK
        else:
            speech_text = i18n.get_random_acceptance_ack(
            ) + ", " + i18n.MESSAGE_2
            reprompt = i18n.get_random_dont_understand(
            ) + ", " + i18n.MESSAGE_2
            updated_intent = Intent("ReplyIntent", slots)
            elicit_directive = ElicitSlotDirective(updated_intent, "message")
            handler_input.response_builder.add_directive(elicit_directive)

        handler_input.response_builder.speak(speech_text) \
            .set_should_end_session(False).ask(reprompt)
        return handler_input.response_builder.response
Exemple #14
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In HelpIntentHandler")

        # Create a GravityIntent object so we can get back to the GravityIntentHandler
        gravIntent = Intent(name="GravityIntent")

        # extract our saved values from the S3 repository
        savedAttrs = handler_input.attributes_manager.persistent_attributes
        logger.info(f"In HelpIntentHandler: savedAttrs is {savedAttrs}. ")

        # Get any slot values from the user
        slots = handler_input.request_envelope.request.intent.slots
        logger.info(f"In HelpIntentHandler: slots={slots} ")

        handler_input.response_builder.speak(data.HELP_MESSAGE).ask(
            data.HELP_MESSAGE).set_card(
                SimpleCard(data.SKILL_TITLE, data.CARD_HELP))

        handler_input.response_builder.add_directive(
            DelegateDirective(updated_intent=gravIntent))

        return handler_input.response_builder.response
Exemple #15
0
    def handle(self, handler_input):
        sess_attrs = handler_input.attributes_manager.session_attributes
        slots = handler_input.request_envelope.request.intent.slots
        updated_intent = Intent("SpeedIntent", slots)
        i18n = Constants.i18n

        for slot_name in slots:
            slot = slots[slot_name]
            if slot_name == "speed_dial_number" and slots.get(
                    "message").value is None:
                if slot.value is None:
                    slot_to_elicit = "speed_dial_number"
                    speech_text = i18n.SPEED_DIAL
                    reprompt = i18n.SPEED_DIAL_REPROMPT
                else:
                    num = int(slot.value)
                    try:
                        speech_text, reprompt, slot_to_elicit = handle_speed_dial_number_input(
                            num, sess_attrs, i18n)
                    except SpeedDialException as error:
                        return handler_input.response_builder \
                            .speak(error.args[0]).set_should_end_session(True).response

                directive = ElicitSlotDirective(updated_intent, slot_to_elicit)
                handler_input.response_builder.add_directive(directive)

            if slot.name == "message" and slot.value:
                try:
                    m = slot.value
                    speech_text, reprompt = send_telegram(m, sess_attrs, i18n)
                except TelethonException as error:
                    return handle_telethon_error_response(error, handler_input)

        handler_input.response_builder.speak(speech_text) \
            .set_should_end_session(False).ask(reprompt)
        return handler_input.response_builder.response
Exemple #16
0
    def handle(self, handler_input):
        """Handle the intent; fetch and serve appropriate response.

        If a mass is taking place today, does not end the current session.
        issues a ElicitSlotDirective to continue the dialog, asking the user
        if they would like a reminder.

        If no mass, then ends the current session.

        Args:
            handler_input (ask_sdk_core.handler_input.HandlerInput):
                Input from Alexa.

        Returns:
            ask_sdk_model.response.Response: Response for this intent and
                device.

        """
        LOGGER.info("In NextMassHandler")
        userSession = session.KilianUserSession(handler_input)
        # Get response:
        envelope = handler_input.request_envelope
        speech, reprompt, cardTitle, cardText, cardImage, displayText = \
            events.MassResponse(userSession).getNextMassResponse()

        # If mass, prompt for a reminder; if not, return response.
        nextMass = events.MassResponse(userSession).getNextMass()
        if nextMass:
            msg = "Found a 'next mass' for today, constructing reminder request"
            LOGGER.debug(msg)
            speech += (". Would you like me to remind you "
                       "30 minutes prior to mass?")
            handler_input.response_builder.speak(speech).ask(
                reprompt).set_card(
                    StandardCard(
                        title=cardTitle, text=cardText,
                        image=cardImage)).set_should_end_session(False)
            #currentIntent = envelope.request.intent
            msg = "Reprompt message constructed. Now constructing nextIntent"
            LOGGER.debug(msg)
            nextIntent = Intent(
                name="NotifyNextMassIntent",
                confirmation_status=IntentConfirmationStatus.NONE,
                slots={
                    "DESIRES_REMINDER":
                    Slot(name="DESIRES_REMINDER",
                         confirmation_status=SlotConfirmationStatus.NONE)
                })
            #handler_input.response_builder.add_directive(
            #    DelegateDirective(updated_intent=nextIntent)
            #)
            msg = "nextMass constructed, now adding ElicitSlotDirective"
            LOGGER.debug(msg)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="DESIRES_REMINDER",
                                    updated_intent=nextIntent))
            msg = "Asking user if they want a reminder, and queuing follow-up intent."
            LOGGER.info(msg)
            msg = "Response looks like: \n{}".format(
                handler_input.response_builder.response)
            LOGGER.debug(msg)
            return handler_input.response_builder.response

        LOGGER.debug("No 'next mass' found for today. No reminder.")
        # No next mass, so ... no reminder needed:
        handler_input.response_builder.speak(speech).set_card(
            StandardCard(title=cardTitle, text=cardText, image=cardImage))
        # Display Directive for display devices (Echo Show, etc):
        directiveBuilder = display.Directive(
            mainUrl=
            "https://st-killian-resources.s3.amazonaws.com/displayTemplateMedia/massGifts_340.jpg",  # pylint: disable=C0301
            backgroundUrl=
            "https://st-killian-resources.s3.amazonaws.com/displayTemplateMedia/dispBG_512.jpg",  # pylint: disable=C0301
            title=cardTitle,
            text=displayText)
        displayDirective = directiveBuilder.getDirective()

        # Check for displayDirective support:
        envelope = handler_input.request_envelope
        supported = envelope.context.system.device.supported_interfaces.to_dict(
        )
        if supported.get('display'):
            LOGGER.info(
                "display interface supported, adding display directive.")
            handler_input.response_builder.add_directive(displayDirective)
        else:
            LOGGER.info(
                "display interface not supported, withholding directive.")

        handler_input.response_builder.set_should_end_session(True)
        return handler_input.response_builder.response
Exemple #17
0
    def handle(self, handler_input):
        """Handler for Processing a saved calibration value"""
        # save our current Intent so we can get back here if we have to
        calIntent = handler_input.request_envelope.request.intent
        logger.info(f"In CalibrateIntentHandler: calIntent is {calIntent}. ")

        # Create a GravityIntent object so we can get back to the GravityIntentHandler
        gravIntent = Intent(name="GravityIntent")

        # extract our saved values from the S3 repository
        savedAttrs = handler_input.attributes_manager.persistent_attributes
        logger.info(f"In CalibrateIntentHandler: savedAttrs is {savedAttrs}.")

        defaultAsked = savedAttrs.get('defaultAsked', False)

        # Get any slot values from the user
        slots = handler_input.request_envelope.request.intent.slots
        logger.info(f"In CalibrateIntentHandler: slots={slots}")

        # if we have a slot, get its value
        if slots:
            calTemp = slots["caliDefault"].value
        else:
            calTemp = None

        # if we already asked the user, then the reply is in the caliDefault slot
        # it could be a number, or something else
        if defaultAsked:
            # See if it is a number
            try:
                calTempFloat = float(calTemp)
                # Yes, we have a number. Return it to GravityIntent as the new calibration temperature
                savedAttrs[
                    'calibration'] = calTemp  # return the new calibration in GravityIntent's slot
                gravSlots = {}
                for name, value in savedAttrs.items():
                    gravSlot = Slot(name=name, value=value)
                    if name == "gravity" or name == "temperature" or name == "calibration":
                        gravSlots[gravSlot.name] = {
                            'confirmation_status':
                            gravSlot.confirmation_status,
                            'name': gravSlot.name,
                            'resolutions': gravSlot.resolutions,
                            'value': gravSlot.value
                        }
                gravIntent.slots = gravSlots
                logger.info(
                    f"In CalibrateIntentHandler: Returning new calibration to {gravIntent}. "
                )
                handler_input.response_builder.add_directive(
                    DelegateDirective(updated_intent=gravIntent))
                return handler_input.response_builder.response
            except:
                # This intent's slot was not a number. If it is some form of agreement, pass the save calibration back to GravityIntent
                calResolutions = slots["caliDefault"].resolutions
                userResponse = calResolutions.resolutions_per_authority[
                    0].status.code
                # Did the user say something we recognize as an affirmative?
                if userResponse == StatusCode.ER_SUCCESS_MATCH:
                    gravSlots = {}
                    for name, value in savedAttrs.items():
                        gravSlot = Slot(name=name, value=value)
                        if name == "gravity" or name == "temperature" or name == "calibration":
                            gravSlots[gravSlot.name] = {
                                'confirmation_status':
                                gravSlot.confirmation_status,
                                'name': gravSlot.name,
                                'resolutions': gravSlot.resolutions,
                                'value': gravSlot.value
                            }
                    gravIntent.slots = gravSlots
                    logger.info(
                        f"In CalibrateIntentHandler: Using default calibration to {gravIntent}."
                    )
                    handler_input.response_builder.add_directive(
                        DelegateDirective(updated_intent=gravIntent))
                    return handler_input.response_builder.response
                else:
                    # Otherwise, try to get something we understand
                    speech = f"Sorry, you said {calTemp}. Please reply with a new calibration temperature or reply 'yes' to use the default."
                    reprompt = "Please say 'yes' or reply with a new calibration temperature."
                    handler_input.response_builder.speak(speech).ask(
                        reprompt).set_should_end_session(False).set_card(
                            SimpleCard(data.SKILL_TITLE, reprompt))
                    handler_input.response_builder.add_directive(
                        ElicitSlotDirective(slot_to_elicit="caliDefault",
                                            updated_intent=calIntent))
                    return handler_input.response_builder.response

        # At this point, we haven't ask the user anything
        # Set the "asked" flag
        savedAttrs['defaultAsked'] = True
        handler_input.attributes_manager.persistent_attributes = savedAttrs
        handler_input.attributes_manager.save_persistent_attributes()

        # Ask the user to confirm the default or provide a new calibration temperature
        speech = f"You have a default calibration temperature of {calTemp}. Do you want to use the default?"
        reprompt = "Please say 'yes' or reply with a new calibration temperature."
        handler_input.response_builder.speak(speech).ask(
            reprompt).set_should_end_session(False).set_card(
                SimpleCard(data.SKILL_TITLE, reprompt))
        handler_input.response_builder.add_directive(
            ElicitSlotDirective(slot_to_elicit="caliDefault",
                                updated_intent=calIntent))
        return handler_input.response_builder.response
Exemple #18
0
    def handle(self, handler_input):
        """Handler for Processing the gravity correction"""
        # Create an Intent object for GravityIntent
        gravIntent = handler_input.request_envelope.request.intent
        logger.info(f"In GravityIntentHandler: gravIntent is {gravIntent}. ")

        # Obtain the request object
        request = handler_input.request_envelope.request

        # Get any slot values from the user
        slots = handler_input.request_envelope.request.intent.slots
        logger.info(f"In GravityIntentHandler: slots={slots}")

        # extract slot values
        gravity = slots["gravity"].value
        temp = slots["temperature"].value
        calTemp = slots["calibration"].value
        logger.info(
            f"In GravityIntentHandler: gravity is {gravity} and temp {temp}")

        # extract any saved values from the S3 repository
        savedAttrs = handler_input.attributes_manager.persistent_attributes
        defaultAsked = savedAttrs.get('defaultAsked', False)

        # In an effort to vary the user experience, keep track of the number of times we have asked for a slot
        # so that we can escalate our responses
        gravityAsked = savedAttrs.get('gravityAsked', 0)
        tempAsked = savedAttrs.get('tempAsked', 0)
        caliAsked = savedAttrs.get('caliAsked', 0)

        logger.info(
            f"In GravityIntentHandler: gravityAsked is {gravityAsked}, tempAsked {tempAsked}, and caliAsked {caliAsked}"
        )

        # See if we have a default calibration temperature
        savedCalibration = savedAttrs.get('calibration', 0)
        if savedCalibration == 0:
            calDefault = False
        else:
            calDefault = True

        try:
            gravityFloat = float(gravity)
        except:
            gravityAsked += 1
            speech = data.GRAVITY_MESSAGES[gravityAsked].format(gravity)
            reprompt = "What was the gravity measure again? "

            if gravityAsked >= 3:
                gravityAsked = 0

            savedAttrs['gravityAsked'] = gravityAsked
            handler_input.attributes_manager.persistent_attributes = savedAttrs
            handler_input.attributes_manager.save_persistent_attributes()

            handler_input.response_builder.speak(speech).ask(reprompt)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="gravity",
                                    updated_intent=gravIntent))
            handler_input.response_builder.set_should_end_session(False)
            return handler_input.response_builder.response

        try:
            tempFloat = float(temp)
        except:
            tempAsked += 1
            if tempAsked < 3:
                speech = data.TEMPERATURE_MESSAGES[tempAsked].format(
                    util.saySpecificGravity(gravity))
            else:
                speech = data.TEMPERATURE_MESSAGES[tempAsked].format(temp)
            reprompt = "at what temperature was your gravity measurement taken?"

            if tempAsked >= 3:
                tempAsked = 0
            savedAttrs['tempAsked'] = tempAsked
            handler_input.attributes_manager.persistent_attributes = savedAttrs
            handler_input.attributes_manager.save_persistent_attributes()

            handler_input.response_builder.speak(speech).ask(
                reprompt).set_should_end_session(False)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="temperature",
                                    updated_intent=gravIntent))
            return handler_input.response_builder.response

        # Try to use a specified calibration temperature.
        # if there is none, try to use a saved calibration temperature.
        # if that fails, ask the user for a calibration temperature
        logger.info(
            f"in GravityIntentHandler: calTemp is {calTemp} and calDefault is {calDefault}"
        )

        # If we have not yet asked about the calibration temperature, delegate control to the Calibrate Intent
        if not defaultAsked and calDefault:
            # Save the responses we have to the S3 repository, so the Calibration Intent can return them back to us
            savedAttrs['gravity'] = gravity
            savedAttrs['temperature'] = temp
            savedAttrs['defaultAsked'] = False
            handler_input.attributes_manager.persistent_attributes = savedAttrs
            handler_input.attributes_manager.save_persistent_attributes()

            # build an Intent object for CalibrateIntent
            calIntent = Intent(name="CalibrateIntent")
            calSlots = {}
            calSlot = Slot(name="caliDefault", value=savedCalibration)
            calSlots[calSlot.name] = {
                'confirmation_status': calSlot.confirmation_status,
                'name': calSlot.name,
                'resolutions': calSlot.resolutions,
                'value': calSlot.value
            }
            calIntent.slots = calSlots

            # Delegate CalibrateIntent
            logger.info(
                f"in GravityIntentHandler: about to delegate CalibrateIntent. Intent is {calIntent} "
            )
            handler_input.response_builder.add_directive(
                DelegateDirective(updated_intent=calIntent))
            return handler_input.response_builder.response
        # end of "if not defaultAsked:"

        try:
            calTempFloat = float(calTemp)
        except:
            caliAsked += 1
            speech = data.CALIBRATE_MESSAGES[caliAsked].format(
                util.saySpecificGravity(gravity), temp)
            reprompt = "You can say something like, '60'"

            if caliAsked >= 3:
                caliAsked = 0
            savedAttrs['caliAsked'] = caliAsked
            handler_input.attributes_manager.persistent_attributes = savedAttrs
            handler_input.attributes_manager.save_persistent_attributes()

            handler_input.response_builder.speak(speech).ask(
                reprompt).set_should_end_session(False)

            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="calibration",
                                    updated_intent=gravIntent))
            return handler_input.response_builder.response

        if util.validateSG(gravityFloat) == 0:
            speech = data.GRAVITY_MESSAGES[3].format(gravity)
            reprompt = "Please enter a valid specific gravity. "
            handler_input.response_builder.speak(speech).ask(
                reprompt).set_should_end_session(False)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="gravity",
                                    updated_intent=gravIntent))
            return handler_input.response_builder.response

        tempFloat = util.validateTemp(tempFloat)
        calTempFloat = util.validateTemp(calTempFloat)

        if tempFloat == 0:
            speech = data.TEMPERATURE_MESSAGES[3].format(temp)
            reprompt = "Please enter a valid temperature. "
            handler_input.response_builder.speak(speech).ask(
                reprompt).set_should_end_session(False)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="temperature",
                                    updated_intent=gravIntent))
            return handler_input.response_builder.response

        if calTempFloat == 0:
            speech = data.CALIBRATE_MESSAGES[3].format(calTemp)
            reprompt = "Please enter a valid calibration temperature. "
            handler_input.response_builder.speak(speech).ask(
                reprompt).set_should_end_session(False)
            handler_input.response_builder.add_directive(
                ElicitSlotDirective(slot_to_elicit="calibration",
                                    updated_intent=gravIntent))
            return handler_input.response_builder.response

        # We have all the validated values, save them in the S3 repository
        savedAttrs['gravity'] = gravity
        savedAttrs['temperature'] = temp
        savedAttrs['calibration'] = calTemp
        savedAttrs['defaultAsked'] = False
        savedAttrs['gravityAsked'] = 0
        savedAttrs['tempAsked'] = 0
        savedAttrs['caliAsked'] = 0
        handler_input.attributes_manager.persistent_attributes = savedAttrs
        handler_input.attributes_manager.save_persistent_attributes()
        logger.info("In GravityIntentHandler: Saved response in S3 repository")

        # Calculate the corrected gravity
        numeratorValue = 1.00130346 - (0.000134722124 * tempFloat) + (
            0.00000204052596 * tempFloat**2) - (0.00000000232820948 *
                                                tempFloat**3)
        denominatorValue = 1.00130346 - (0.000134722124 * calTempFloat) + (
            0.00000204052596 * calTempFloat**2) - (0.00000000232820948 *
                                                   calTempFloat**3)

        corrGravity = gravityFloat * (numeratorValue / denominatorValue)

        logger.info(
            f"In GravityIntentHandler: corrected gravity is {corrGravity}. ")

        speech = f"your corrected gravity is {util.saySpecificGravity(round(corrGravity))}. "
        speech += data.EXIT_SKILL_MESSAGE
        cardText = f"your corrected gravity is {int(round(corrGravity))*0.001}."

        handler_input.response_builder.speak(speech).set_should_end_session(
            True).set_card(SimpleCard(data.SKILL_TITLE, cardText))

        return handler_input.response_builder.response
Exemple #19
0
from ask_sdk_model import ui, Response, DialogState
from ask_sdk_model.ui import SimpleCard
from ask_sdk_model.dialog import ElicitSlotDirective, DelegateDirective
from ask_sdk_model import (Intent, IntentConfirmationStatus, Slot,
                           SlotConfirmationStatus)
from ask_sdk_model.slu.entityresolution.resolution import Resolution
from ask_sdk_model.slu.entityresolution import StatusCode

from alexa import data, util

sb = CustomSkillBuilder(persistence_adapter=s3_adapter)

# Set the skill id so not just anyone can invoke this function
sb.skill_id = "amzn1.ask.skill.92878a4c-6715-4eed-9b71-7805480315a0"

gravIntent = Intent()
calIntent = Intent(name="CalibrateIntent")

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


class LaunchRequestHandler(AbstractRequestHandler):
    """Determine if this is a Launch Request."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        # Indicate can handle Launch requests
        logger.info(
            f"In LaunchRequestHandler.can_handle request is {handler_input.request_envelope.request} "
        )
        return is_request_type("LaunchRequest")(handler_input)
Exemple #20
0
 def handle(self, handler_input):
     intent = Intent(name="AMAZON.StopIntent")
     handler_input.response_builder.add_directive(DelegateDirective(updated_intent=intent))
     return handler_input.response_builder.response
Exemple #21
0
    def handle(self, handler_input):
        try:
            check_for_account(handler_input)
        except AccountException as error:
            return handler_input.response_builder \
                .speak(error.args[0]).set_should_end_session(True).response

        slots = handler_input.request_envelope.request.intent.slots
        updated_intent = Intent("SendIntent", slots)
        sess_attrs = handler_input.attributes_manager.session_attributes
        locale = handler_input.request_envelope.request.locale
        i18n = Constants.i18n

        for slot_name in slots:
            slot = slots[slot_name]
            if slot_name == "first_name" and slots["message"].value is None:
                if slot.value is None:
                    slot_to_elicit = "first_name"
                    speech_text = i18n.FIRST_NAME
                    reprompt = i18n.FIRST_NAME_REPROMPT
                else:
                    if not sess_attrs.get("FIRST_NAMES"):
                        if locale == 'de-DE':
                            # On German Alexa we get "vier" if user says a speed dial number
                            # On English Alexa we get "4"... --> need that also for German
                            slot.value = parse_spoken_numbers_to_integers(slot.value)

                        is_speed_dial = slot.value.isdigit()

                        if is_speed_dial:
                            try:
                                num = int(slot.value)
                                speech_text, reprompt, slot_to_elicit = \
                                    handle_speed_dial_number_input(
                                        num, sess_attrs, i18n)
                            except SpeedDialException as error:
                                return handler_input.response_builder \
                                    .speak(error.args[0]).set_should_end_session(True).response
                        else:
                            speech_text, reprompt, slot_to_elicit = self \
                                .handle_first_name_input(slot.value, sess_attrs, i18n)
                    else:
                        one_two_or_three = slots.get("one_two_or_three")

                        if one_two_or_three.value not in ["1", "2", "3"]:
                            speech_text = i18n.MAX_NO_CONTACT
                            handler_input.response_builder\
                                .speak(speech_text).set_should_end_session(True)
                            return handler_input.response_builder.response

                        speech_text, reprompt = self \
                            .get_users_choice(one_two_or_three, i18n, sess_attrs)
                        slot_to_elicit = "message"

                directive = ElicitSlotDirective(updated_intent, slot_to_elicit)
                handler_input.response_builder.add_directive(directive)

            if slot.name == "message" and slot.value:
                try:
                    m = slot.value
                    speech_text, reprompt = send_telegram(m, sess_attrs, i18n)
                except TelethonException as error:
                    return handle_telethon_error_response(error, handler_input)

        handler_input.response_builder.speak(speech_text) \
            .set_should_end_session(False).ask(reprompt)

        return handler_input.response_builder.response