Пример #1
0
def cancel_and_stop_intent_handler(handler_input):
    """Single handler for Cancel and Stop Intent."""
    # type: (HandlerInput) -> Response
    speech_text = "See ya! Go Orange!"

    return handler_input.response_builder.speak(speech_text).set_card(
        StandardCard("Daily Orange", speech_text, DAILY_ORANGE_LOGO)).response
Пример #2
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        # go to beginning of track
        logger.info("In StartOverHandler")
        persistence_attr = handler_input.attributes_manager.persistent_attributes
        track_number = int(persistence_attr["track_number"])

        audio_key = trackInfo.track_info[track_number]["url"]
        audio_url = create_presigned_url(audio_key)
        persistence_attr["playback_settings"]["offset_in_milliseconds"] = 0
        persistence_attr["playback_settings"]["url"] = audio_url
        persistence_attr["playback_settings"]["token"] = audio_key

        persistence_attr["playback_settings"]["next_stream_enqueued"] = False

        handler_input.attributes_manager.persistent_attributes = persistence_attr

        card = StandardCard(title=trackInfo.track_info[track_number]["title"],
                            text=trackInfo.track_info[track_number]["artist"],
                            image=Image(small_image_url=small_image_url,
                                        large_image_url=large_image_url))

        directive = PlayDirective(play_behavior=PlayBehavior.REPLACE_ALL,
                                  audio_item=AudioItem(stream=Stream(
                                      token=audio_key,
                                      url=audio_url,
                                      offset_in_milliseconds=0,
                                      expected_previous_token=None),
                                                       metadata=None))

        handler_input.response_builder.set_card(card).add_directive(
            directive).set_should_end_session(True)

        return handler_input.response_builder.response
Пример #3
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        women = ['Mary Walker']
        recipient = random.choice(women)

        # fetch data into dynamodb
        logger.info('searching for the woman {}'.format(recipient))
        table = boto3.resource('dynamodb').Table('MedalOfHonorInfo')
        response = table.query(
            KeyConditionExpression=Key('name').eq(recipient), Limit=1)
        print 'response={}'.format(response)

        citation = response['Items'][0]['citation']
        year_of_honor = response['Items'][0]['year_of_honor']
        img = response['Items'][0]['img']
        name = response['Items'][0]['name']
        speech_text = citation
        handler_input.response_builder\
          .speak('{} was awarded the Medal of Honor in {}<break time="600ms"/>{}'.format(name, year_of_honor, speech_text))\
          .set_card(
            StandardCard(name, speech_text, Image(img, img)))\
          .set_should_end_session(False)

        session_attributes = handler_input.attributes_manager.session_attributes
        session_attributes['last_request'] = {
            'name': name,
            'citation': citation,
            'img': img
        }

        return handler_input.response_builder.response
Пример #4
0
def build_response(handler_input,
                   card_title,
                   card_text,
                   speech_text,
                   img_tuple=None,
                   end_session=False):
    if handler_input.attributes_manager.session_attributes["drunk_mode_state"]:
        speech_text = '<prosody rate="slow"><emphasis level="strong">' + speech_text + '</emphasis></prosody>'

    if img_tuple and supports_display(handler_input):
        card = StandardCard(card_title, card_text,
                            ui.Image(img_tuple[1], img_tuple[1]))
        img = Image('Meme', [ImageInstance(url=img_tuple[1])])
        reddit_text = TextContent(primary_text=PlainText(img_tuple[0]),
                                  secondary_text=PlainText(img_tuple[2]))
        directive = RenderTemplateDirective(
            BodyTemplate2(back_button=BackButtonBehavior.VISIBLE,
                          image=img,
                          title=card_title,
                          text_content=reddit_text))
        handler_input.response_builder.speak(speech_text).set_card(
            card).add_directive(directive).set_should_end_session(end_session)
    else:
        card = SimpleCard(card_title, card_text)
        handler_input.response_builder.speak(speech_text).set_card(
            card).set_should_end_session(end_session)
    return handler_input.response_builder.response
Пример #5
0
    def handle(self, handler_input):
        card_text = "This is a AudioMixed response with data and a standard card"
        image_url = "https://duy7y3nglgmh.cloudfront.net/tackles.png"
        card = StandardCard(title="Premier League",
                            text=card_text,
                            image=Image(small_image_url=image_url,
                                        large_image_url=image_url))

        return (handler_input.response_builder.ask(
            "this is the reprompt"
        ).set_card(card).set_should_end_session(False).add_directive(
            RenderDocumentDirective(
                token="developer-provided-string",
                document={
                    "type": "Link",
                    "src":
                    "doc://alexa/apla/documents/template_with_data_sources"
                },
                datasources={
                    "text": {
                        "speak":
                        "This is the text that will be spoken at the same time the audio \
                          clip plays, it is dynamic and set by the lambda"
                    },
                    "crowd": {
                        "noise":
                        "https://btbscratch.s3.amazonaws.com/FootballCrowdSound.mp3",
                        "start": str(randrange(0, 50 * 60))
                    }
                })).response)
Пример #6
0
    def handle(self, handler_input):
        slots = handler_input.request_envelope.request.intent.slots
        skill_locale = handler_input.request_envelope.request.locale

        name = slots["name"].value

        # check molecule on Pubchem
        cids = get_cids(name, 'name')
        if not cids:
            speech_text = "Sorry, I could not find {} on PubChem. What else can I do for you?".format(
                name)
        else:
            Natoms, atoms, geom, charge = get_parameters(cids)

            if geom is None:
                speech_text = "Sorry, I could not find the coordinates of {} on PubChem. What else can I do for you?".format(
                    name)
            else:
                speech_text = "Yes, this is the structure of {} and you can ask for calculations on it. What else can I do for you?".format(
                    name)


# type: (HandlerInput) -> Response
        small = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" + name.replace(
            " ", "") + "/PNG"
        structure = Image(small)
        handler_input.response_builder.speak(speech_text).set_card(
            StandardCard("ChemVox", speech_text,
                         structure)).set_should_end_session(False)
        return handler_input.response_builder.response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # will help with figuring out errors in cloudwatch later
        logger.info("In GetTopTeamHandler")

        rankings = APIRequest.rankings()
        teamRankings = rankings.ranks
        smittyWerbenManJensen = teamRankings[0]  #He was number one
        #Get the team name
        teamName = smittyWerbenManJensen.team.name
        #Get the number of matches won
        W = smittyWerbenManJensen.record.matchwin
        L = smittyWerbenManJensen.record.matchloss

        teamLogoSmol = smittyWerbenManJensen.team.logo
        teamLogoLarge = smittyWerbenManJensen.team.logolrg

        speechOutput = "The top team in the Overwatch League is {}".format(
            teamName)

        cardTitle = '{}: {}W - {}L'.format(teamName, W, L)
        cardContent = ''
        # TODO: With the /v2/teams endpoint the logo URL are a little more
        # formatted and varying. Need to go back and modify.
        cardImg = Image(small_image_url=teamLogoSmol.path,
                        large_image_url=teamLogoLarge.path)

        handler_input.response_builder.speak(speechOutput) \
            .set_card(StandardCard(cardTitle, cardContent, cardImg)) \
            .set_should_end_session(True)
        return handler_input.response_builder.response
Пример #8
0
    def handle(self, handler_input):
        all_pressures = self.all_pressures()
        latest_number_limit = 21
        latest_number = min(latest_number_limit, len(all_pressures))
        latest_pressures = all_pressures[-latest_number:]
        latest_pressures.sort(key=lambda p: p.timestamp, reverse=True)

        card_title = f'Your latest {latest_number} pressures'
        card_text = ''
        card_image = Image(
            'https://pressure-monitor-logo.s3-eu-west-1.amazonaws.com/pressure_monitor_medium.png',
            'https://pressure-monitor-logo.s3-eu-west-1.amazonaws.com/pressure_monitor_large.png'
        )
        speak_output = 'Your report was sent to your account. You can check it on the portal or the mobile app.'

        self._log(f'latest pressures: {latest_pressures}')

        for pressure in latest_pressures:
            date = pressure.timestamp.strftime('%d %b %Y %H:%M')
            card_text += f'❤️ {pressure.systolic_number} by {pressure.diastolic_number} as {pressure.status().description()} at {date}\n'

        card = StandardCard(card_title, card_text, card_image)

        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).set_card(card).response)
Пример #9
0
    def handle(self, handler_input):
        """Handle the launch request; fetch and serve appropriate response.

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

        Raises:
            ValueError: If something other than the sanctioned app calls this
                intent.

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

        """
        # Prevent someone bad from writing a skill that sends requests to this:
        env = handler_input.request_envelope
        appId = env.session.application.application_id
        if appId != "amzn1.ask.skill.66eb11d8-013f-4fca-b655-494dbeba291b":
            raise ValueError("Invalid Application ID")

        speech, reprompt, cardTitle, cardText, cardImage = getWelcomeResponse()
        handler_input.response_builder.speak(speech).ask(reprompt).set_card(
            StandardCard(title=cardTitle, text=cardText,
                         image=cardImage)).set_should_end_session(False)
        return handler_input.response_builder.response
Пример #10
0
    def handle(self, handler_input):

        speak_output = "Obrigado pela oportunidade de participar da batalha das startápis."
        card_text = "Obrigado pela oportunidade de participar da batalha das startups."

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Obrigado", card_text, imagem_padrao)).response)
Пример #11
0
    def handle(self, handler_input):
        """Handle the intent; fetch and serve appropriate response.

        Ends the current session with an audio directive.

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

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

        """
        userSession = session.KilianUserSession(handler_input)
        talk = audio.Talk(userSession)
        speech, title, text, directive, sessionAttrs = \
            talk.getLatestTalk()

        card = StandardCard(title=title, text=text)
        handler_input.response_builder.speak(speech)
        handler_input.response_builder.set_card(card)
        handler_input.response_builder.add_directive(directive)
        handler_input.response_builder.set_should_end_session(True)
        handler_input.attributes_manager.session_attributes = sessionAttrs
        return handler_input.response_builder.response
Пример #12
0
def read_headlines_intent_handler(handler_input):
    """Handler for Hello World Intent."""
    # type: (HandlerInput) -> Response
    speech_text = HeadLines().getHeadlines()

    return handler_input.response_builder.speak(speech_text).set_card(
        StandardCard("Daily Orange", speech_text,
                     DAILY_ORANGE_LOGO)).set_should_end_session(True).response
Пример #13
0
    def handle(self, handler_input):

        speak_output = "Você vendeu 280147 reais em setembro."
        card_text = "\nVendas em Setembro: R$280.147,00"

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Volume de vendas", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #14
0
    def handle(self, handler_input):

        speak_output = "Conta de energia paga com sucesso."
        card_text = "\nConta: Energia Elétrica R$210,35 foi paga com sucesso!"

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Pagamentos", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #15
0
    def handle(self, handler_input):

        speak_output = "Você tem uma conta de energia elétrica no valor de 210 reais e 35 centavos. e o pagamento do fornecedor de móveis no valor de 654 reais."
        card_text = "\nEnergia Elétrica: R$210,35.\n\nFornecedor de móveis: R$654,00"

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Pagamentos", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #16
0
    def handle(self, handler_input):

        speak_output = "Claro. o Dóti Benk é um banco digital que ajuda empresários a ganharem performance nas rotinas diárias além de pagamentos e recebimentos. com o meu apoio é possível fazer muitas tarefas. podemos ainda utilizar rôbôs para operações, minimizando erros humanos e aumentando a performance da empresa, além das reduções de custo."
        card_text = "Claro, o Dotbank é um banco digital que ajuda empresários a ganharem performance nas rotinas diárias além de pagamentos e recebimentos, com o meu apoio é possível fazer muitas tarefas, podemos ainda utilizar robôs para operações minimizando erros humanos e aumentando a performance da empresa além das reduções de custo."

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Obrigado", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #17
0
    def handle(self, handler_input):

        speak_output = "Olá, Marcelo, seu saldo é de 21.370 reais."
        card_text = "Saldo: R$21.370,00"

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Saldo", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #18
0
    def handle(self, handler_input):

        speak_output = "Seu melhor vendedor é o Pedro Rósa da empresa Vamos Parcelar"
        card_text = "\nVendedor: Pedro Rosa\n\n Empresa: Vamos Parcelar"

        return (handler_input.response_builder.speak(speak_output).set_card(
            StandardCard("Melhor Vendedor", card_text, imagem_padrao)).ask(
                "Posso ajudar em mais alguma coisa?").response)
Пример #19
0
def launch_request_handler(handler_input):
    """Handler for Skill Launch."""
    # type: (HandlerInput) -> Response
    speech_text = "Welcome to the Daily Orange skill, you can ask for the headlines!"

    return handler_input.response_builder.speak(speech_text).set_card(
        StandardCard("Daily Orange", speech_text,
                     DAILY_ORANGE_LOGO)).set_should_end_session(False).response
Пример #20
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In PlayMetronomeHandler")

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

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

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

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

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

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

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(expected_previous_token=None,
                              token=data["url"],
                              url=data["url"],
                              offset_in_milliseconds=0),
                metadata=AudioItemMetadata(
                    title=data["card"]["title"],
                    subtitle=data["card"]["text"],
                    art=display.Image(
                        content_description=data["card"]["title"],
                        sources=[display.ImageInstance(url=strings.ICON_URL)]),
                    background_image=display.Image(
                        content_description=data["card"]["title"],
                        sources=[display.ImageInstance(url=strings.ICON_URL)
                                 ]))))
        (handler_input.response_builder.speak(speak).set_card(
            card).add_directive(directive).set_should_end_session(True))
        return handler_input.response_builder.response
Пример #21
0
def help_intent_handler(handler_input):
    """Handler for Help Intent."""
    # type: (HandlerInput) -> Response
    speech_text = "You can ask for the headlines!"

    return handler_input.response_builder.speak(speech_text).ask(
        speech_text).set_card(
            StandardCard("Daily Orange", speech_text,
                         DAILY_ORANGE_LOGO)).response
Пример #22
0
    def handle(self, handler_input):
        speech_text = "This is a simple spoken response with a standard card"
        image_url = "https://duy7y3nglgmh.cloudfront.net/tackles.png"
        card = StandardCard(title="Premier League",
                            text=speech_text,
                            image=Image(small_image_url=image_url,
                                        large_image_url=image_url))

        return (handler_input.response_builder.ask(
            "this is the reprompt").speak(speech_text).set_card(
                card).set_should_end_session(False).response)
Пример #23
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     speech_text = "Thank you for using TeraChem! " \
                 "Have a nice day!"
     small = "https://chemvox.s3.us-east-2.amazonaws.com/" + str(
         random.randint(1, 6)) + ".png"
     pict = Image(small)
     handler_input.response_builder.speak(speech_text).set_card(
         StandardCard("ChemVox", speech_text,
                      pict)).set_should_end_session(True)
     return handler_input.response_builder.response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In GetNextMatchIntent")

        # Get user timezone
        usertz = getUserTimezone(handler_input.request_envelope)
        if usertz is None:
            handler_input = requestPermission(handler_input)
            return handler_input.response_builder.response

        # Get OWL schedule
        schedule = APIRequest.schedule()

        curWeek = getCurrentWeek(schedule)
        nextMatch = getNextMatch(curWeek)
        matchTime = nextMatch.startdate.astimezone(usertz)

        team1 = nextMatch.teams[0]
        team2 = nextMatch.teams[1]

        # TODO: old version implemented a check for live games here. It is
        # probably a good idea to check for a live game (the user may be
        # interested to know) but the TODO is to consider if here is the best
        # place to do that.
        liveMatchContent = ""

        # Prepare speech output
        nextMatchContent = "The next match will be"
        if isToday(matchTime):
            nextMatchContent = "{} today at {}.".format(
                nextMatchContent, matchTime.strftime(clkfrmt.clkstr))
        elif isTomorrow(matchTime):
            nextMatchContent = "{} tomorrow at {}.".format(
                nextMatchContent, matchTime.strftime(clkfrmt.clkstr))
        else:
            nextMatchContent = "{} on {}.".format(
                nextMatchContent, matchTime.strftime(clkfrmt.datetimestr))

        nextMatchContent = "{} The {} will {} the {}.".format(
            nextMatchContent, team1.name, getRandomEntry(vs), team2.name)

        speechOutput = "{}{}".format(liveMatchContent, nextMatchContent)

        # Setup card
        title = "Match Details"
        img = Image(small_image_url=resource.OWL['LOGO'],
                    large_image_url=resource.OWL['LOGO'])
        content = speechOutput

        handler_input.response_builder.speak(speechOutput) \
            .set_card(StandardCard(title, content, img)) \
            .set_should_end_session(True)

        return handler_input.response_builder.response
Пример #25
0
 def handle(self, handler_input):
     logger.info("In HelloWorld")
     speechText = '<lang xml:lang="en-US">Hello World</lang>, <lang xml:lang="es-ES">Hola ' \
                  'Mundo</lang>'
     handler_input.response_builder.speak(speechText).set_card(
         StandardCard(title='Standard Card / Tarjeta Estandar',
                      text='Lorem ipsum dolor sit amet, consectetur adipiscing',
                      image=Image(small_image_url=standard_small_img,
                                  large_image_url=standard_large_img))).\
         ask(speechText).\
         set_should_end_session(False)
     return handler_input.response_builder.response
Пример #26
0
 def handle(self, handler_input):
     """
     Creates a response for the given input
     Args:
         handler_input(HandlerInput): The input to the handler
     Returns: (Response) The response
     """
     handler_input.response_builder.speak(speechs["nero"]) \
         .add_directive(ConfirmIntentDirective()) \
         .set_card(StandardCard("Nero", speechs["nero_card"],
                                Image(images["nero"], images["nero"])))
     return handler_input.response_builder.response
Пример #27
0
    def handle(self, handler_input):
        slots = handler_input.request_envelope.request.intent.slots
        skill_locale = handler_input.request_envelope.request.locale

        name = slots["name"].value

        s1 = True

        sentence = "Let me search for " + name + " on my database"
        self.progressive_response(handler_input, sentence)

        # check molecule on Pubchem
        cids = get_cids(name, 'name')
        if not cids:
            speech_text = "Sorry, I could not find {} on PubChem. What else can I do for you?".format(
                name)
        else:
            Natoms, atoms, geom, charge = get_parameters(cids)

            if geom is None:
                speech_text = "Sorry, I could not find the coordinates of {} on PubChem. What else can I do for you?".format(
                    name)

            else:
                # run calculation on TCC
                sentence = "I Launched the calculation on TeraChem Cloud."
                self.progressive_response(handler_input, sentence)

                pool = ThreadPool(processes=1)
                async_result = pool.apply_async(
                    solvatochromic, (s1, name, cids, atoms, geom, charge,
                                     receiver_email, user_name))

                speech_text = None
                try:
                    speech_text = async_result.get(timeout=5)
                except:
                    if receiver_email is None:
                        speech_text = "The calculation is taking too long. If you grant the permission, I will email you the results. What else can I do for you?"
                    else:
                        speech_text = "The calculation is taking too long. I will email you the results. What else can I do for you?"


# type: (HandlerInput) -> Response
        small = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" + name.replace(
            " ", "") + "/PNG"
        structure = Image(small)
        handler_input.response_builder.speak(speech_text).set_card(
            StandardCard("ChemVox", speech_text,
                         structure)).set_should_end_session(False)
        return handler_input.response_builder.response
Пример #28
0
    def card(title, text=None, blend=None):
        if blend:
            blend = stringcase.spinalcase(blend)
            image = Image(
                f"{NOISEBLEND_IMG}/bg/blend/bg_{blend}_768.jpg",
                f"{NOISEBLEND_IMG}/bg/blend/bg_{blend}_1280.jpg",
            )
        else:
            image = Image(
                f"{NOISEBLEND_IMG}/icons/app/app-android-512x512.png",
                f"{NOISEBLEND_IMG}/icons/app/app-android-1024x1024.png",
            )

        return StandardCard(title, text, image)
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # will help with figuring out errors in cloudwatch later
        logger.info("In GetTeamRecordIntent")

        slots = handler_input.request_envelope.request.intent.slots
        if 'Team' not in slots:
            print("Error: entered request without a slot")
            # TODO: Will we ever get here? If so we need to return an ASK error

        teamSlot = slots['Team']
        resolution = teamSlot.resolutions.resolutions_per_authority[0]

        if resolution.status.code == StatusCode.ER_SUCCESS_MATCH:
            resolutionValues = resolution.values[0]
            teamName = resolutionValues.value.name
            teamId = resolutionValues.value.id
        else:
            print("Error: not a valid team recognized in the slots")
            # TODO: implement data.TEAM_REPROMPT
            handler_input.response_builder.speak(data.INVALID_TEAM_MSG.format(teamSlot.value))\
                    .ask(data.TEAM_REPORMPT)
            return handler_input.response_builder.response

        team = APIRequest.teamfromid_v2(teamId)
        record = team.records

        W = record['matchWin']
        L = record['matchLoss']

        speechOutput = 'The {} have a record of {} wins and {}'.format(
            team.name, W, L)
        if L == 1:
            speechOutput = speechOutput + ' loss.'
        else:
            speechOutput = speechOutput + ' losses.'

        cardTitle = '{}: {}-{}'.format(team.name, W, L)
        cardContent = ''
        # TODO: With the /v2/teams endpoint the logo URL are a little more
        # formatted and varying. Need to go back and modify.
        cardImg = Image(small_image_url=team.logo.path['main']['svg'],
                        large_image_url=team.logo.path['main']['svg'])

        handler_input.response_builder.speak(speechOutput) \
            .set_card(StandardCard(cardTitle, cardContent, cardImg)) \
            .set_should_end_session(True)

        return handler_input.response_builder.response
Пример #30
0
    def handle(self, handler_input):
        """Handle the intent; fetch and serve appropriate response.

        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 MassTimeHandler__")
        userSession = session.KilianUserSession(handler_input)

        mass = events.MassResponse(userSession)
        speech, reprompt, cardTitle, cardText, cardImage, displayText = \
            mass.getMassTimeResponse()
        handler_input.response_builder.speak(speech).ask(reprompt)

        # Card for app:
        handler_input.response_builder.set_card(
            StandardCard(title=cardTitle, text=cardText, image=cardImage))
        handler_input.response_builder.set_should_end_session(True)

        # 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.")

        return handler_input.response_builder.response