예제 #1
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
예제 #2
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)
예제 #3
0
 def movie_image(movie):
     # type: (dict) -> Image | None
     images = movie.get("images", []) if movie and 'images' in movie else list()
     if len(images) == 0:
         return None
     url = images[0]['url']
     return Image(large_image_url=url.replace("http:", "https:", 1))
예제 #4
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
예제 #5
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
예제 #6
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
예제 #7
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
예제 #8
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)
예제 #9
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
예제 #10
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
예제 #11
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
예제 #12
0
    def get_card(self) -> Card:

        card = StandardCard(
            title="Pi-hole Alexa",
            image=Image(small_image_url=self.get_images_url() + "/logo.png",
                        large_image_url=self.get_images_url() +
                        "/logo_large.png"),
            text=StatusIntent.CARD_TEXT_TEMPLATE.format(
                self.get_client().status,
                self.get_client().total_queries,
                self.get_client().unique_clients,
                self.get_client().blocked,
                Decimal(self.get_client().ads_percentage).normalize()))

        return card
예제 #13
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        slots = handler_input.request_envelope.request.intent.slots
        try:
            recipient = slots[
                'recipient'].resolutions.resolutions_per_authority[0].values[
                    0].value.name.title()
        except:
            recipient = slots['recipient'].value.title()

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

        if len(response['Items']) == 0:
            speech_text = 'There are no Medal of Honor recipients by the name of {}'.format(
                recipient)
            handler_input.response_builder.speak(speech_text)

            session_attributes = handler_input.attributes_manager.session_attributes
            session_attributes['last_request'] = {'speech_text': speech_text}
        else:
            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
예제 #14
0
    def play(handler_input, is_playback=False):
        # type: (HandlerInput) -> Response
        playback_info = get_playback_info(handler_input)
        response_builder = handler_input.response_builder

        play_order = playback_info.get("play_order")
        offset_in_ms = playback_info.get("offset_in_ms")
        index = playback_info.get("index")

        play_behavior = PlayBehavior.REPLACE_ALL
        podcast = data.AUDIO_DATA[play_order[index]]
        token = play_order[index]
        playback_info['next_stream_enqueued'] = False

        response_builder.add_directive(
            PlayDirective(
                play_behavior=play_behavior,
                audio_item=AudioItem(
                    stream=Stream(
                        token=token,
                        url=podcast.get("url"),
                        offset_in_milliseconds=offset_in_ms,
                        expected_previous_token=None),
                    metadata=None))
        ).set_should_end_session(True)

        if not is_playback:
            # Add card and response only for events not triggered by
            # Playback Controller
            handler_input.response_builder.speak(
                data.PLAYBACK_PLAY.format(podcast.get("title")))

            if can_throw_card(handler_input):
                response_builder.set_card(StandardCard(
                    title=data.PLAYBACK_PLAY_CARD.format(
                        podcast.get("title")),
                    text=data.PLAYBACK_PLAY_CARD.format(
                        podcast.get("title")),
                    image=Image(
                        small_image_url="https://quisutdeusapp.altervista.org/sanmichele_108.png",
                        large_image_url="https://quisutdeusapp.altervista.org/sanmichele_512.png"
                    )
                ))

        return response_builder.response
예제 #15
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        global user_name
        global receiver_email

        req_envelope = handler_input.request_envelope
        if not (req_envelope.context.system.user.permissions and
                req_envelope.context.system.user.permissions.consent_token):
            user_name = ''
            receiver_email = None
        else:
            apiaccessToken = handler_input.request_envelope.context.system.api_access_token
            key = 'Bearer ' + apiaccessToken
            headers = {
                "Host": "api.amazonalexa.com",
                "Authorization": key,
                "Accept": "application/json"
            }
            URL = "https://api.amazonalexa.com/v2/accounts/~current/settings/Profile.givenName"
            jname = requests.get(url=URL, headers=headers)
            user_name = jname.json()
            if not isinstance(user_name, str): user_name = ''

            URL = "https://api.amazonalexa.com/v2/accounts/~current/settings/Profile.email"
            jemail = requests.get(url=URL, headers=headers)
            receiver_email = jemail.json()
            if not isinstance(receiver_email, str): receiver_email = None

        if receiver_email is None or user_name == '':
            speech_text = "Welcome " + user_name + ", I am ChemVox, the voice of TeraChem. If you grant the permissions to access your email address and name in the skill setting, I will email you the results. How can I help you?"
            handler_input.response_builder.speak(speech_text).set_card(
                AskForPermissionsConsentCard(
                    permissions=permissions)).set_should_end_session(False)
        else:
            speech_text = "Welcome " + user_name + ", I am ChemVox, the voice of TeraChem. How can I help you?"
            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(False)

        return handler_input.response_builder.response
    def generate_recipe_output(self, handler_input, sauce_item):
        _ = handler_input.attributes_manager.request_attributes["_"]
        locale = handler_input.request_envelope.request.locale
        # Sauce exists
        if (sauce_item['id']):
            # Load i18n strings
            recipes = recipe_utils.get_locale_specific_recipes(locale)
            selected_recipe = recipes[sauce_item['id']]
            # Add image
            sauce_item['image'] = recipe_utils.get_sauce_image(
                sauce_item['id'])
            # Add a card (displayed in the Alexa app)
            cardTitle = _(data.DISPLAY_CARD_TITLE).format(
                _(data.SKILL_NAME), selected_recipe['name'])
            # Add speak output and reprompt
            handler_input.response_builder.speak(
                selected_recipe['instructions']).ask(
                    _(data.RECIPE_REPEAT_MESSAGE))
            handler_input.response_builder.set_card(
                StandardCard(title=cardTitle,
                             text=selected_recipe['instructions'],
                             image=Image(small_image_url=sauce_item['image'],
                                         large_image_url=sauce_item['image'])))
            # Add APL Template if device is compatible
            apl_utils.recipeScreen(handler_input, sauce_item, selected_recipe)
        else:
            # Spoken Sauce does not exist
            # Add prompt : Is the item slot is filled with a value ?
            if (sauce_item['spoken']):
                # Use spoken value to let user know no recipe exists for this value
                handler_input.response_builder.speak(
                    _(data.RECIPE_NOT_FOUND_WITH_ITEM_NAME).format(
                        sauce_item['spoken']))
            else:
                # No spoken value
                handler_input.response_builder.speak(
                    _(data.RECIPE_NOT_FOUND_WITHOUT_ITEM_NAME))

        # add reprompt
        handler_input.response_builder.ask(_(data.RECIPE_NOT_FOUND_REPROMPT))

        # Generate JSON response
        return handler_input.response_builder.response
예제 #17
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("*****  at handle launch request   *******")
        speech_text = "Welcome to the Alexa APLA demo"

        logger.info("about to return response")
        image_url = "https://duy7y3nglgmh.cloudfront.net/Depositphotos_referee.jpg"
        card = StandardCard(title="Premier League",
                            text="bla",
                            image=Image(small_image_url=image_url,
                                        large_image_url=image_url))

        session_attr = handler_input.attributes_manager.session_attributes
        session_attr["radioButtonText"] = "Form"
        handler_input.attributes_manager.session_attributes = session_attr

        return (handler_input.response_builder
                #.speak("this is the speak")
                .ask("this is the ask").set_card(card).response)
예제 #18
0
파일: lambda.py 프로젝트: srdecny/diasys
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In GetNewFactHandler")

        slots = handler_input.request_envelope.request.intent.slots
        cardType = slots['CardType'].value

        response = requests.get("https://api.scryfall.com/cards/random?q=t:" +
                                cardType).json()
        cardName = response['name']
        normalImage = response['image_uris']['normal']
        smallImage = response['image_uris']['small']
        speech = GET_FACT_MESSAGE + cardName

        handler_input.response_builder.set_card(
            StandardCard(title=SKILL_NAME,
                         text=cardName,
                         image=Image(small_image_url=smallImage,
                                     large_image_url=normalImage)))
        return handler_input.response_builder.speak(speech).response
예제 #19
0
    def handle(self, handler_input):
        card_text = "This is a AudioMixed response with 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_without_data_sources"
                },
                datasources={})).response)
예제 #20
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "Welcome to audioplayer sample"

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

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(expected_previous_token=None,
                              token=en_us_audio_data["url"],
                              url=en_us_audio_data["url"],
                              offset_in_milliseconds=0),
                metadata=AudioItemMetadata(
                    title=en_us_audio_data["card"]["title"],
                    subtitle=en_us_audio_data["card"]["text"],
                    art=display.Image(
                        content_description=en_us_audio_data["card"]["title"],
                        sources=[
                            display.ImageInstance(
                                url=
                                "https://alexademo.ninja/skills/logo-512.png")
                        ]),
                    background_image=display.Image(
                        content_description=en_us_audio_data["card"]["title"],
                        sources=[
                            display.ImageInstance(
                                url=
                                "https://alexademo.ninja/skills/logo-512.png")
                        ]))))

        handler_input.response_builder.speak(speech_text).set_card(
            card).add_directive(directive).set_should_end_session(True)
        return handler_input.response_builder.response
예제 #21
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = 'The Medal of Honor is the United States of America\'s highest and most prestigious personal '\
                      'military decoration that may be awarded to recognize U.S. military service members who have '\
                      'distinguished themselves by acts of valor. The medal is normally awarded by the President of the '\
                      'United States in the name of the U.S. Congress. Try saying "Alexa, ask Medal of Honor Info who is '\
                      'the latest recipient?"'
        img = 'https://s3.amazonaws.com/medalofhonorinfo/moh{}.jpg'.format(
            random.choice(range(1, 11)))
        handler_input.response_builder\
          .speak(speech_text)\
          .set_card(
            StandardCard('Medal of Honor Info', speech_text, Image(img, img)))\
          .set_should_end_session(False)

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

        return handler_input.response_builder.response
예제 #22
0
 def handle(self, handler_input):
     card_text = "This is a GridMixed response with 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))
     if get_supported_interfaces(
             handler_input).alexa_presentation_apl is not None:
         return (handler_input.response_builder.speak(
             "Welcome to Premier League").set_should_end_session(
                 False).add_directive(
                     APLRenderDocumentDirective(
                         token="developer-provided-string",
                         document={
                             "type": "Link",
                             "token": "my token",
                             "src": "doc://alexa/apl/documents/GridList"
                         },
                         datasources=datasources2)).response)
     else:
         return (handler_input.response_builder.speak(
             "no screen for you").set_should_end_session(False).response)
예제 #23
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # fetch data into dynamodb
        logger.info('searching for a recipient in dynamodb')
        table = boto3.resource('dynamodb').Table('MedalOfHonorInfo')
        random_name = ''.join([
            random.choice(string.ascii_uppercase) for i in range(1, 20)
        ]).title()
        random_year = str(random.choice(range(1800, datetime.now().year)))
        response = table.scan(Limit=1,
                              ExclusiveStartKey={
                                  'name': random_name,
                                  'year_of_honor': random_year
                              })

        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
예제 #24
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # fetch data into dynamodb
        logger.info('searching for latest recipient in dynamodb')
        table = boto3.resource('dynamodb').Table('MedalOfHonorInfo')
        min_year = str(
            datetime.now().year - 5
        )  # assume that the award will be given out at least every 5 years
        response = table.scan(
            FilterExpression=Key('year_of_honor').gt(min_year))
        print 'response={}'.format(response)

        # find recorded with greatest year_of_honor. there isn't much we can do about tie-breaking
        newest = max(response['Items'], key=lambda val: val['year_of_honor'])
        print 'newest={}'.format(newest)

        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
예제 #25
0
def play(url, offset, text, card_data, response_builder):
    """Function to play audio.

    Using the function to begin playing audio when:
        - Play Audio Intent is invoked.
        - Resuming audio when stopped / paused.
        - Next / Previous commands issues.

    https://developer.amazon.com/docs/custom-skills/audioplayer-interface-reference.html#play
    REPLACE_ALL: Immediately begin playback of the specified stream,
    and replace current and enqueued streams.
    """
    # type: (str, int, str, Dict, ResponseFactory) -> Response
    if card_data:
        response_builder.set_card(
            StandardCard(title=card_data["title"],
                         text=card_data["text"],
                         image=Image(
                             small_image_url=card_data["small_image_url"],
                             large_image_url=card_data["large_image_url"])))

    # Using URL as token as they are all unique
    response_builder.add_directive(
        PlayDirective(play_behavior=PlayBehavior.REPLACE_ALL,
                      audio_item=AudioItem(
                          stream=Stream(token=url,
                                        url=url,
                                        offset_in_milliseconds=offset,
                                        expected_previous_token=None),
                          metadata=add_screen_background(card_data) if
                          card_data else None))).set_should_end_session(True)

    if text:
        response_builder.speak(text)

    return response_builder.response
예제 #26
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("in AudioPlayIntent")
        persistence_attr = handler_input.attributes_manager.persistent_attributes

        if (is_intent_name("PlayAudio")(handler_input)):
            logger.info("play Audio")
            # first time - set track to zero
            track_number = 0
            persistence_attr["track_number"] = track_number

            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))

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

            speech_text = "Playing your music"
            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.speak(speech_text).set_card(
                card).add_directive(directive).set_should_end_session(True)

        else:
            # resume
            logger.info("Resume")
            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"]["url"] = audio_url
            persistence_attr["playback_settings"]["token"] = audio_key

            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=persistence_attr[
                        "playback_settings"]["offset_in_milliseconds"],
                    expected_previous_token=None),
                                     metadata=None))

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

        handler_input.attributes_manager.persistent_attributes = persistence_attr
        return handler_input.response_builder.response
예제 #27
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     print(DialogState)
     currentIntent = handler_input.request_envelope.request.intent
     slots = currentIntent.slots
     movie = slots["Movie"].value
     search_result = searches.movie_search.search(movie)
     if not search_result:
         speak_output = f"Sorry, there were no matches for {movie}."
         return (
             handler_input.response_builder
                 .speak(speak_output)
                 .response
         )
     for i, date in enumerate(search_result):
         year = datetime.strptime(search_result[i]['release_date'], '%Y-%M-%d')
         search_result[i]['year']=(year.year)
     if len(search_result) == 1:
         text = f"{search_result[0]['title']} ({search_result[0]['year']}) \n\n{search_result[0]['overview']}"
         #speak_output = search_result[0]['title']
         img = Image(small_image_url="https://image.tmdb.org/t/p/w440_and_h660_face" + search_result[0]['poster_path'])
         if movieDownload(search_result[0]) == True:
             speak_output = f'{search_result[0]["title"]} has succesfully been added to the request list.'
         elif movieDownload(search_result[0]) == 'connection_error':
             speak_output = 'Sorry, there was a connection problem when requesting the movie.'
         elif movieDownload(search_result[0]) == 'already_requested':
             speak_output = f'{search_result[0]["title"]} has already been requested.'
         else:
             speak_output = 'Sorry, there was a problem requesting the movie.'
         return (
             handler_input.response_builder
                 .speak(speak_output)
                 .set_card(StandardCard(text=text, image=img))
                 #.add_directive(DelegateDirective(currentIntent))
                 #.addDelegateDirective(currentIntent)
                 .response
         )
     else:
         sorted_x = (sorted(search_result, key = lambda i: i['year'], reverse=True))
         session_attr = handler_input.attributes_manager.session_attributes
         session_attr["sorted_x"] = sorted_x
         #searches.dialogue_constructor.get_cast(sorted_x)
         for i, x in enumerate(sorted_x):
             actor = searches.dialogue_constructor.get_cast(sorted_x[i])
             sorted_x[i]['actor']=actor
         
         test = searches.dialogue_constructor.construct(sorted_x)
         handler_input.response_builder.speak(test)#.ask(speak_output)
         #handler_input.request_envelope.session.sorted_x.value = sorted_x
         #print("sorted :", handler_input.request_envelope.session.sorted_x.value)
         print(DialogState)
         return (
             handler_input.response_builder
             #handler_input.response_builder
                 .speak(test)
                 .add_directive(DelegateDirective(currentIntent))
                 #.ask(speak_output)
                 # .ask("add a reprompt if you want to keep the session open for the user to respond")
                 #.set_card(StandardCard(title=len(search_result), text=title))
                .response
         )
예제 #28
0
                                                  AudioItemMetadata,
                                                  StopDirective)
from ask_sdk_model.interfaces import display

small_image_url = create_presigned_url("Media/Note108.png")
large_image_url = create_presigned_url("Media/Note512.png")

audio_data = {
    "card": {
        "title": 'My music',
        "text": 'I like music',
    }
}
card = StandardCard(title=audio_data["card"]["title"],
                    text=audio_data["card"]["text"],
                    image=Image(small_image_url=small_image_url,
                                large_image_url=large_image_url))


class LaunchRequestHandler(AbstractRequestHandler):
    """Handler for Skill Launch."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool

        return is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "Hello, I can play your music, just say play my music"

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