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, "")
def handle(self, handler_input): # type: (HandlerInput) -> Response logger.info("In InProgressRestaurantIntent") current_intent = handler_input.request_envelope.request.intent prompt = "" for slot_name, current_slot in six.iteritems( current_intent.slots): if slot_name not in ["article", "at_the", "I_Want"]: if (current_slot.confirmation_status != SlotConfirmationStatus.CONFIRMED and current_slot.resolutions and current_slot.resolutions.resolutions_per_authority[0]): if current_slot.resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: if len(current_slot.resolutions.resolutions_per_authority[0].values) > 1: prompt = "Which would you like " values = " or ".join( [e.value.name for e in current_slot.resolutions.resolutions_per_authority[0].values]) prompt += values + " ?" return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=current_slot.name) ).response elif current_slot.resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_NO_MATCH: if current_slot.name in required_slots: prompt = "What {} are you looking for?".format(current_slot.name) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( slot_to_elicit=current_slot.name )).response return handler_input.response_builder.add_directive( DelegateDirective( updated_intent=current_intent )).response
def in_progress_pet_match_intent(handler_input): # type: (HandlerInput) -> Response logger.info('in InProgressPetMatchIntent') current_intent = handler_input.request_envelope.request.intent prompt = '' for slot_name, current_slot in six.iteritems(current_intent.slots): if slot_name not in ['article', 'at_the', 'I want']: if current_slot.confirmation_status != SlotConfirmationStatus.CONFIRMED \ and current_slot.resolutions \ and current_slot.resolutions.resolutions_per_authority[0]: if current_slot.resolutions.resolutions_per_authority[ 0].status_code == StatusCode.ER_SUCCESS_MATCH: if len(current_slot.resolutions. resolutions_per_authority[0].values) > 1: prompt = 'Which would you like ' values = ' or '.join([ e.value.name for e in current_slot.resolutions. resolutions_per_authority[0].values ]) prompt += values + ' ?' return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( slot_to_elicit=current_slot.name)).response elif current_slot.resolutions.resolutions_per_authority[ 0].status_code == StatusCode.ER_SUCCESS_NO_MATCH: if current_slot.name in required_slots: prompt = f'What {current_slot.name} are you looking for?' return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( slot_to_elicit=current_slot.name)).response return handler_input.response_builder.add_directive( DelegateDirective(updated_intent=current_intent)).response
def handle(self, handler_input): currentIntent = handler_input.request_envelope.request.intent result = disambiguateSlot(getSlotValues(currentIntent.slots)) if result: handler_input.response_builder.speak(result["prompt"]).ask( result["prompt"]).add_directive( ElicitSlotDirective( slot_to_elicit=result["slotName"])).response else: handler_input.response_builder.add_directive( DelegateDirective(updated_intent=currentIntent)).response return handler_input.response_builder.response
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)
def handle(self, handler_input): # type: (HandlerInput) -> Response logger.info("In fever_temp_handler") current_intent = handler_input.request_envelope.request.intent test_statex(handler_input, "fever_temp") # get the swell improvement from the slot and save it in session attributes cur_slot_name = "fever_temperaturex" assert (cur_slot_name in valid_slots) cur_slot_value = get_resolved_value_from_handler( handler_input, cur_slot_name) cur_intent_name = current_intent.name # TBD make this change everywhere print(" DEBUG fever_temp_handler ", cur_slot_value) try: cur_slot_value = float(cur_slot_value) except: cur_slot_value = None # talking about swelling is improvong if cur_slot_value == None: # TBD prompt prompt = "What is your temperature? I have %s " % (cur_slot_value) reprompt = "What did your thermometer read" print("debug prompt", prompt, reprompt) print("debug", type(cur_slot_value)) return handler_input.response_builder.speak(prompt).ask( reprompt).add_directive( ElicitSlotDirective( slot_to_elicit=cur_slot_name, updated_intent=current_intent)).response # not improving else: set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move on to next slot but there is none this should take to completed if debug: test_statex(handler_input, "fever") # no further states , complete #set_statex(handler_input,"fever", "fever_completedx") #save_slots(handler_input,'fever' ) return do_fever_complete(handler_input)
def handle(self, handler_input): #if improve ice are filled simply delegate to go get next slot, if completed it will go to complete # we should have all the slots here current_intent = handler_input.request_envelope.request.intent #if ice is not filled, reprompt for ice logger.info("In jointexercises_doing_handler") cur_slot_name = "jointexercises_yesNo" assert (cur_slot_name in valid_slots) cur_slot_value = get_resolved_value_from_handler( handler_input, cur_slot_name) cur_intent_name = "jointexercises" statex = get_statex(handler_input, cur_intent_name) logger.info( "In jointexercises_doing_handler State :%s cur_slot_value %s" % (statex, cur_slot_value)) if not cur_slot_value in ('yes', 'no'): prompt = "Did you do your joint exercises?" return handler_input.response_builder.speak(prompt).ask( prompt).add_directive( ElicitSlotDirective( slot_to_elicit=cur_slot_name, updated_intent=current_intent)).response else: # we have a value save it set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) #TBD congrat APPLYING ICE IS COOLEST THING TO DO # move on to next slot but there is none this should take to completed if debug: print("expect dialog complete") test_statex(handler_input, cur_intent_name) # should pass all slots filled # this setting state to co,plete is probably wring not clear handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED #nothing more return jointexercises_do_complete(handler_input) """
def handle(self, handler_input): l = {} speech = "Please wait momentarily while we fix some technical issues." current_intent = handler_input.request_envelope.request.intent for slot_name in daily_stats_slots: valx = get_resolved_value(handler_input, slot_name) l[slot_name] = valx if valx == None: prompt = "Sorry I couldn't understand your response %s for %s " % ( valx, slot_name) save_slots(handler_input) return handler_input.response_builder.speak(prompt).ask( prompt).add_directive( ElicitSlotDirective(updated_intent=current_intent, slot_to_elicit=slot_name)) set_statex(handler_input, current_intent.name, "done_with_stats") save_slots(handler_input, current_intent.name) speech += recover_conversation(handler_input) handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED return handler_input.response_builder.speak(speech).response
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 __FallbackIntentHandler(handler_input, suffix): """Handler for Fallback Intent. AMAZON.FallbackIntent is only available in en-US locale. This handler will not be triggered except in that locale, so it is safe to deploy on any locale. """ session = get_session(handler_input) status = get_course_and_tag_status(handler_input) fallbackCount = session['fallbackCount'] session['fallbackCount'] += 1 handler_input.attributes_manager.session_attributes = session if status == HAS_TAG_NO_COURSE: return elicit_slot("Course", "GetCourseIntent", handler_input, REQUEST_COURSE_MESSAGE, suffix) else: return handler_input.response_builder.speak( f"{suffix} What kind of projects would you like?").add_directive( ElicitSlotDirective( updated_intent=Intent(name="RetrieveProjectsIntent"), slot_to_elicit="ProjectType")).response
def handle(self, handler_input): logger.info('In AskForCocktailRequestHandler') session_attr = handler_input.attributes_manager.session_attributes slot_values = get_slot_values( handler_input.request_envelope.request.intent.slots) request_type = slot_values['request']['resolved'] # checks weather a cocktail was named in the request or # a cocktail from a previous request is active drink = get_drink(session_attr, slot_values) # if both do not apply, Alexa prompts the user to name # a cocktail if drink is None: prompt = get_speech("ASK_COCKTAIL") return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit='drink')).response # new cocktail is active now session_attr['drink'] = drink api_request = build_url(api, 'search', api_category='s', api_keyword=drink ) # fugures out the kind of request, ingredient, description or both request_key = parse_request(request_type) try: response = http_get(api_request) logger.info(response) # builds a response based on the request speech = build_response(request_key, response, drink) except Exception as e: # the drink asked for is not in the database speech = get_speech('COCKTAIL_EXCEPTION').format(drink) logger.info("Intent: {}: message: {}".format( handler_input.request_envelope.request.intent.name, str(e))) # safes response so it can be repeated by request session_attr['last_speech'] = speech handler_input.response_builder.speak( speech).set_should_end_session(False) return handler_input.response_builder.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
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
def handle(self, handler_input): #if improve ice are filled simply delegate to go get next slot, if completed it will go to complete # we should have all the slots here current_intent = handler_input.request_envelope.request.intent #if ice is not filled, reprompt for ice logger.info("In bloodpressure_diastolic_handler") cur_slot_name = "bloodpressure_diastolic" assert(cur_slot_name in valid_slots) cur_slot_value = get_resolved_value_from_handler(handler_input,cur_slot_name) cur_intent_name = "bloodpressure" statex = get_statex(handler_input,cur_intent_name) logger.info("In bloodpressure_diastolic_handler State :%s cur_slot_value %s"%(statex, cur_slot_value)) if cur_slot_value == None : # TBD prompt prompt = "What is your diastolic pressure? I have %s "%(cur_slot_value) reprompt = "What did your monitor read" print("debug prompt", prompt, reprompt) print("debug", type(cur_slot_value)) return handler_input.response_builder.speak( prompt).ask(reprompt).add_directive( ElicitSlotDirective(slot_to_elicit=cur_slot_name, updated_intent=current_intent) ).response # not improving else : set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move on to next slot but there is none this should take to completed if debug: test_statex(handler_input,"bloodpressure") handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED #nothing more # no further states , complete #set_statex(handler_input,"fever", "fever_completedx") #save_slots(handler_input,'fever' ) return bloodpressure_do_complete(handler_input)
def handle(self, handler_input): logger.info('In GlassIntentHandler') session_attr = handler_input.attributes_manager.session_attributes slot_values = get_slot_values( handler_input.request_envelope.request.intent.slots) # checks if a cocktail is named by the user or is active # from a previous request drink = get_drink(session_attr, slot_values) # if both do not apply if drink is None: # Alexa prompts the user to name a cocktail prompt = get_speech("ASK_COCKTAIL") return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit='drink')).response # new drink is active session_attr['drink'] = drink api_request = build_url(api, 'search', api_category='s', api_keyword=drink ) try: response = http_get(api_request) logger.info(response) glass = response['drinks'][0]['strGlass'] speech = get_speech("GIVE_GLASS").format(drink, glass) except Exception as e: speech = get_speech('GLASS_EXCEPTION').format(drink) logger.info("Intent: {}: message: {}".format( handler_input.request_envelope.request.intent.name, str(e))) # safes response to be repeated by request session_attr['last_speech'] = speech handler_input.response_builder.speak( speech).set_should_end_session(False) return handler_input.response_builder.response
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
def handle(self, handler_input): # type: (HandlerInput) -> Response print("DEBUG in fever_handler") current_intent = handler_input.request_envelope.request.intent # get the swell improvement from the slot and save it in session attributes cur_slot_name = "fever_yesNo" try: assert (cur_slot_name in valid_slots) except: print("exception ", cur_slot_name, "not in ", valid_slots) raise ("exception in slot name ") cur_slot_value = get_resolved_value_from_handler( handler_input, cur_slot_name) cur_intent_name = "fever" assert (cur_intent_name == current_intent.name ) # TBD remove cur_intent_name = "fever" logger.info("fever_handler slotval : %s" % cur_slot_value) # we are talking about the value of swelling if cur_slot_value == None: prompt = "Do you have a fever? " save_slots(handler_input, cur_intent_name) return handler_input.response_builder.speak(prompt).ask( prompt).add_directive( ElicitSlotDirective( slot_to_elicit=cur_slot_name, updated_intent=current_intent)).response # no swelling we are done elif cur_slot_value == 'no': set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # no further states print("COMPLETED DIALOG\n") #set_statex(handler_input, cur_intent_name, "fever_completedx") #we have a bug this doesnt really work because state is not set to completed #handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED #save_slots(handler_input, cur_intent_name ) # changes state and moves on to next intent handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED return do_fever_complete(handler_input) elif cur_slot_value == 'yes': set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # TBD proper noise on swelling next_state = 'fever_collect_temp' set_statex(handler_input, cur_intent_name, next_state) next_slot = fever_state_to_slots[next_state][0] save_slots(handler_input, cur_intent_name) prompt = " Tell me in Fahrenheit What is the temperature of the fever " repromptx = "How much fever do you have " #removed the .ask(reprompt) return handler_input.response_builder.speak(prompt).ask( repromptx).add_directive( ElicitSlotDirective( slot_to_elicit='fever_temperaturex', updated_intent=current_intent)).response else: print("crashing and burning fever") if debug: raise
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
def add_elicit_slot_directive(self, handler_input): intent = handler_input.request_envelope.request.intent slot_directive = ElicitSlotDirective(slot_to_elicit='code', updated_intent=intent) handler_input.response_builder.add_directive(slot_directive)
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
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
def handle(self, handler_input): # type: (HandlerInput) -> Response logger.info("In swellsuture_swellimprove_handler") current_intent = handler_input.request_envelope.request.intent test_statex(handler_input, "swellsuture") # get the swell improvement from the slot and save it in session attributes cur_slot_name = "swellsuture_swelling_swellimproving" next_slot = "swellsuture_swellimprove_ice" assert(cur_slot_name in valid_slots) cur_slot_value = get_resolved_value_from_handler(handler_input,cur_slot_name) cur_intent_name = "swellsuture" print(" DEBUG swellsuture_swellimprove", cur_slot_value) # talking about swelling is improvong if cur_slot_value == None: # TBD prompt prompt = "Is your swelling improving? " return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=cur_slot_name, updated_intent=current_intent) ).response # not improving elif cur_slot_value == 'no': # go to icing. # TBD remove this and see if it will go to icing by default on delegate directive prompt = "Icing is good for swelling. Did you ice your swelling? " set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move to next state set_statex(handler_input,"swellsuture", "swellsuture_swellimprove_ice") save_slots(handler_input,'swellsuture' ) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=next_slot, updated_intent=current_intent) ).response # swelling is improving so we can stop elif cur_slot_value == 'yes' : set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move on to next slot but there is none this should take to completed if debug: test_statex(handler_input,"swellsuture") # no further states , complete handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED current_intent.dialog_state = DialogState.COMPLETED # ??) #completed_resp = swellsuture_do_complete(handler_input) return swellsuture_do_complete(handler_input) """ return handler_input.response_builder.add_directive( DelegateDirective( updated_intent=current_intent )).response """ else: print("swellsuture_swellimprove_handler neither yes nor no %s"%cur_slot_value) prompt = "Did you apply ice to your swelling ?" save_slots(handler_input,'swellsuture' ) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit='suture_ice', updated_intent = current_intent) ).response
def handle(self, handler_input): # type: (HandlerInput) -> Response # begin workaround why dialogState not being set to complete cur_state = get_statex(handler_input, "swellsuture" ) print("DEBUG CURRENT STATE INPROGRESSSUTURE handler ",cur_state ) if is_current_statex(handler_input, "swellsuture", 'swellsuture_completed'): print("DEBUG 292 COMPLETING") handler_input.request_envelope.request.dialog_state = DialogState.COMPLETED # try again completed_resp = swellsuture_do_complete(handler_input) return completed_resp else: print("DEBUG 297 NOT COMPLETING") if handler_input.request_envelope.request.dialog_state == DialogState.STARTED: print(" debug InProgress suture_intent RESTORE") #tbd do a better job of recovery restore_slots(handler_input, 'swellsuture') if not (get_statex(handler_input, "swellsuture")): set_statex(handler_input, "swellsuture", "swellsuture_swell") else: # this save is a bit aggressive after after every user responds print(" debug InProgress suture_intent SAVE ") save_slots(handler_input,'swellsuture' ) # dialog not completed current_intent = handler_input.request_envelope.request.intent prompt = "..." # go through each of the slots for statey in swellsuture_state_to_slots: for slot_name in swellsuture_state_to_slots[statey]: #get_statex(handler_input, "swellsuture" ) == None: # dont know why we didnt have a state, Once state is filled a different logic may arise # take the first one that hasnt been filled current_slot = current_intent.slots[slot_name] #slot object if (current_slot.confirmation_status != SlotConfirmationStatus.CONFIRMED and current_slot.resolutions and current_slot.resolutions.resolutions_per_authority[0]): print("DEBUG STATUS CODE SUCCESS ", slot_name, current_slot.resolutions.resolutions_per_authority[0].status.code, "num resolutions", len(current_slot.resolutions.resolutions_per_authority[0].values)) # deal with equivalents, ask user to fill in one particular equivalent if current_slot.resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_MATCH: if True or len(current_slot.resolutions.resolutions_per_authority[0].values) > 1: print("DEBUG Setting state", statey," TO GET SLOT: ", slot_name) set_statex(handler_input, "swellsuture", statey) prompt = "Could you clarify which of these you meant? " values = " or ".join([e.value.name for e in current_slot.resolutions.resolutions_per_authority[0].values]) prompt += values + " ?" save_slots(handler_input,'swellsuture' ) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( updated_intent = current_intent, slot_to_elicit=current_slot.name) # may have been restored ).response # otherwise ask user for the slot itself elif current_slot.resolutions.resolutions_per_authority[0].status.code == StatusCode.ER_SUCCESS_NO_MATCH: if True : # current_slot.name in required_slots: # dont understand this why we have to prompt if we are elicitung print("debug elif Setting state", statey," TO GET SLOT: ", slot_name) set_statex(handler_input, "swellsuture", statey) #prompt = "Could we talk about {} around suture?".format(current_slot.name) prompt = swellsuture_slotprompt[current_slot.name] save_slots(handler_input,'swellsuture' ) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( updated_intent = current_intent, slot_to_elicit=current_slot.name )).response else: logger.info("DEBUG", ) #In case of no synonyms were reach here save_slots(handler_input,'swellsuture' ) print("DELEGATE END OF LOOP DEBUG") return handler_input.response_builder.add_directive( DelegateDirective( updated_intent=current_intent )).response
def ask_device(self, speaker_list, message): choose_device = CHOOSE_DEVICE.format(", ".join(s.name for s in speaker_list)) return (self.response_builder.speak(f"{message} {choose_device}").ask( choose_device).add_directive( ElicitSlotDirective(slot_to_elicit="device")).response)
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
def handle(self, handler_input): logger.info('user requested a download') title = get_slot('title') if not title and session.attributes['zooqle']['selected title']: title = session.attributes['zooqle']['selected title']['title'] req_year = get_slot('year') season = get_slot('season') episode = get_slot('episode') logger.debug(f'title: {title}') logger.debug(f'year: {req_year}') logger.debug(f'season: {season}') logger.debug(f'episode: {episode}') if not title: logger.info('prompting user for the title of the movie/TV show') session.attributes['state'] = '' speech = "What would you like me to download?" reprompt = "What's the name of the movie or TV show you'd like me to download?" directives = [ElicitSlotDirective(slot_to_elicit='title')] response = generate_response(handler_input, speech=speech, reprompt=reprompt, directives=directives) return response if not session.attributes['zooqle']['selected title']: logger.info('asking user if this is the correct title') suggestion = get_suggestion(title, req_year=req_year) if not suggestion: speech = f"I couldn't find anything matching {title}." session.attributes['state'] = '' session.attributes['zooqle']['selected title'] = None session.attributes['zooqle']['selected torrent'] = None else: session.attributes['state'] = 'confirm torrent title' speech = render_template('first_suggestion', category=suggestion['category'], title=suggestion['title'], year=suggestion['year']) handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response selected_title = session.attributes['zooqle']['selected title'] for suggestion in session.attributes['zooqle']['suggestions']: if suggestion['url'] == selected_title['url']: title_url = suggestion['url'] category = suggestion['category'] if not session.attributes['zooqle']['selected torrent']: if not session.attributes['zooqle']['results']: available_torrents = list_available_torrents(title_url, season=season, episode=episode) session.attributes['zooqle']['results'] = sort_torrents( title, available_torrents, req_year=req_year)[:5] torrent = session.attributes['zooqle']['results'][0] speech = describe_torrent_result(torrent) session.attributes['state'] = 'confirm torrent download' handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response torrent = session.attributes['zooqle']['results'][0] details = get_torrent_details(torrent['url']) logger.debug(f'details: {details}') try: transmission_client.add_torrent(details['magnet_link']) speech = "I've added the torrent to the download queue." reprompt = "Is there anything else I can help you with?" except LookupError: speech = "I couldn't find the magnet link for that torrent." reprompt = "Would you like to try something else?" session.attributes['state'] = '' session.attributes['zooqle']['selected title'] = None session.attributes['zooqle']['selected torrent'] = None handler_input.response_builder.speak(' '.join([speech, reprompt ])).ask(reprompt) return handler_input.response_builder.response
def handle(self, handler_input): # type: (HandlerInput) -> Response logger.info("In jointPain_painscale_handler") current_intent = handler_input.request_envelope.request.intent test_statex(handler_input, "jointPain") # get the swell improvement from the slot and save it in session attributes cur_slot_name = "jointPainScale" next_slot = "jointPainMeds" assert(cur_slot_name in valid_slots) cur_slot_value = get_resolved_value_from_handler(handler_input,cur_slot_name) cur_intent_name = "jointPain" print(" DEBUG jointPainScale", cur_slot_value) # talking about swelling is improvong if cur_slot_value == None: # TBD prompt prompt = "On a scale from 1-10, how is your joint pain?" return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=cur_slot_name, updated_intent=current_intent) ).response # not improving elif cur_slot_value == "10" or cur_slot_value == "9" or cur_slot_value == "8" or cur_slot_value == "7" or cur_slot_value == "6": # go to icing. # TBD remove this and see if it will go to icing by default on delegate directive prompt = "Meds are good for swelling. Have you taken your meds?" set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move to next state set_statex(handler_input,cur_intent_name, "jointPain_takingmeds") save_slots(handler_input,cur_intent_name) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=next_slot, updated_intent=current_intent) ).response # swelling is improving so we can stop elif cur_slot_value == "5" or cur_slot_value == "4" or cur_slot_value == "3" or cur_slot_value == "2" or cur_slot_value == "1": set_session_attr(handler_input, cur_intent_name, cur_slot_name, cur_slot_value) # move on to next slot but there is none this should take to completed if debug: test_statex(handler_input,cur_intent_name) # no further states , complete handler_input.request_envelope.request.intent.dialog_state = DialogState.COMPLETED current_intent.dialog_state = DialogState.COMPLETED # ??) completed_resp = jointPain_do_complete(handler_input) return completed_resp """ return handler_input.response_builder.add_directive( DelegateDirective( updated_intent=current_intent )).response """ else: print("jointPain_painscale_handler not number %s"%cur_slot_value) prompt = "Sorry I am Not able to understand your response %s . Could you give a number for your pain on a scale one to ten "%cur_slot_value save_slots(handler_input,cur_intent_name) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective(slot_to_elicit=next_slot, updated_intent = current_intent) ).response
def elicit_slot(slot_name, intent_name, handler_input, message_body, suffix): return handler_input.response_builder.speak( f"{suffix} {message_body}").add_directive( ElicitSlotDirective(Intent(name=intent_name), slot_to_elicit=slot_name)).response
def handle(self, handler_input): # type: (HandlerInput) -> Response # begin workaround why dialogState not being set to complete cur_state = get_statex(handler_input, "fever") current_intent = handler_input.request_envelope.request.intent cur_intent_name = current_intent.name print("DEBUG CURRENT STATE handler ", cur_state, cur_intent_name) if is_current_statex(handler_input, "fever", 'fever_completedx'): print("DEBUG fever 165 COMPLETING") handler_input.request_envelope.request.dialog_state = DialogState.COMPLETED # try again completed_resp = do_fever_complete(handler_input) return completed_resp else: print("DEBUG2 InProgress_fever_Intent NOT COMPLETING") if handler_input.request_envelope.request.dialog_state == DialogState.STARTED: print(" DEEBUG InProgress fever RESTORE") #tbd do a better job of recovery restore_slots(handler_input, cur_intent_name) if not (get_statex(handler_input, cur_intent_name)): set_statex(handler_input, cur_intent_name, "fever_beginx") #else: # this save is a bit aggressive after after every user responds #save_slots(handler_input,cur_intent_name) # dialog not completed prompt = "" # go through each of the slots for statey in fever_state_to_slots: for slot_name in fever_state_to_slots[statey]: # dont know why we didnt have a state, Once state is filled a different logic may arise # take the first one that hasnt been filled current_slot = current_intent.slots[slot_name] #slot object if (current_slot.confirmation_status != SlotConfirmationStatus.CONFIRMED and current_slot.resolutions and current_slot.resolutions.resolutions_per_authority[0]): print( " fever+status_code ", slot_name, current_slot. resolutions.resolutions_per_authority[0].status.code) # deal with equivalents, ask user to fill in one particular equivalent if current_slot.resolutions.resolutions_per_authority[ 0].status.code == StatusCode.ER_SUCCESS_MATCH: if len(current_slot.resolutions. resolutions_per_authority[0].values) > 1: print("Setting state", statey, " TO GET SLOT: ", slot_name) set_statex(handler_input, cur_intent_name, statey) prompt = "Could you clarify which of these you meant ? " values = " or ".join([ e.value.name for e in current_slot.resolutions. resolutions_per_authority[0].values ]) prompt += values + " ?" save_slots(handler_input, cur_intent_name) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( updated_intent=current_intent, slot_to_elicit=current_slot.name ) # may have been restored ).response # otherwise ask user for the slot itself elif current_slot.resolutions.resolutions_per_authority[ 0].status.code == StatusCode.ER_SUCCESS_NO_MATCH: if current_slot.name in required_slots: # dont understand this why we have to prompt if we are elicitung print("elif Setting state", statey, " TO GET SLOT: ", slot_name) set_statex(handler_input, cur_intent_name, statey) prompt = "Could we talk about Blood Pressure ?" save_slots(handler_input, cur_intent_name) return handler_input.response_builder.speak( prompt).ask(prompt).add_directive( ElicitSlotDirective( updated_intent=current_intent, slot_to_elicit=current_slot.name) ).response #In case of no synonyms were reach here save_slots(handler_input, cur_intent_name) print("DEBUG delegate fever") return handler_input.response_builder.add_directive( DelegateDirective(updated_intent=current_intent)).response