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
Esempio n. 2
0
def add_screen_background(card_data):
    if card_data:
        metadata = AudioItemMetadata(
            title=card_data["title"],
            subtitle=card_data["subtitle"],
            art=display.Image(
                sources=[display.ImageInstance(url=card_data['icon_url'])]))
        return metadata
    else:
        return None
Esempio n. 3
0
    def getNotImplementedResponse(self):
        """Plays an audio announcement that this feature is forthcoming.

        Until a shared calendar is in place, I cannot look up calendar events.
        So that the user knows that this feature is coming, this plays a nice
        song with a happy announcer telling the user that the feature is on
        its way.

        Args:
            N/A

        Raises:
            N/A

        Returns:
            str, str, str, ask_sdk_model.interfaces.audioplayer.PlayDirective, dict
            The speech for Alexa to speak,
            the title to display on the card,
            the text to display on the card,
            the play directive telling Alexa what audio file to play,
            session attributes to be passed to Alexa.

        """
        url = "https://st-killian-resources.s3.amazonaws.com/calendarGeneric_mixdown.mp3"
        token = "calendarGeneric_mixdown"
        speech = ""
        title = "St. Kilian calendar events"
        text = "Calendar events coming soon! Watch the bulletin for news."
        self.userSession.lastToken = token
        self.userSession.lastTrack = url
        self.userSession.savePersistentAttrs()

        sessionAttrs = {
            "lastTrack": url,
            "lastToken": token
        }
        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(
                    expected_previous_token=None,
                    token=token,
                    url=url,
                    offset_in_milliseconds=0
                ),
                metadata=AudioItemMetadata(
                    title="Calendar Events",
                    subtitle=text
                )
            )
        )
        return speech, title, text, directive, sessionAttrs
 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.add_directive(
         PlayDirective(
             PlayBehavior.REPLACE_ALL,
             AudioItem(Stream(token="lyra_token", url="https://"),
                       AudioItemMetadata("Highway to hell"))))
     return handler_input.response_builder.response
Esempio n. 5
0
    def handle(self, handler_input):
        language_prompts = handler_input.attributes_manager.request_attributes[
            "_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        playlist = persistent_attributes['playlist']
        loop = persistent_attributes["playback_session_data"]["loop"]
        index = int(persistent_attributes["playback_session_data"]["index"])

        if index != 0:
            index -= 1
        elif (index == 0) and loop:
            index = len(playlist) - 1
        else:
            speech_output = speech_output = random.choice(
                language_prompts["START_OF_PLAYLIST"])
            return handler_input.response_builder.speak(
                speech_output).set_should_end_session(True).response

        token = playlist[index]['token']
        url = playlist[index]['url']
        offset = 0
        title = playlist[index]['title']
        subtitle = "Episode {}".format(token)
        persistent_attributes["playback_session_data"].update({
            'token':
            token,
            'url':
            playlist[index]['url'],
            'offset':
            offset,
            'title':
            playlist[index]['title'],
            'index':
            index
        })
        handler_input.attributes_manager.save_persistent_attributes()

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(
                token=token,
                url=url,
                offset_in_milliseconds=offset,
            ),
                                 metadata=AudioItemMetadata(
                                     title=title, subtitle=subtitle)))

        return (handler_input.response_builder.add_directive(
            audio_directive).set_should_end_session(True).response)
Esempio n. 6
0
    def handle(self, handler_input):
        language_prompts = handler_input.attributes_manager.request_attributes[
            "_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        if persistent_attributes.get("playback_session_data") is not None:
            token = persistent_attributes["playback_session_data"]['token']
            url = persistent_attributes["playback_session_data"]['url']
            offset = persistent_attributes["playback_session_data"]["offset"]
            title = persistent_attributes["playback_session_data"]["title"]
            subtitle = "Episode {}".format(token)

        else:
            playlist = populate_playlist_from_rss(rss_url)
            index = len(playlist) - 1
            token = playlist[index]['token']
            url = playlist[index]['url']
            offset = 0
            title = playlist[index]['title']
            subtitle = "Episode {}".format(token)

            handler_input.response_builder.speak(
                random.choice(language_prompts["PLAY_LATEST_EPISODE"]))

            persistent_attributes['playlist'] = playlist
            persistent_attributes["playback_session_data"] = {
                'token': token,
                'url': url,
                'offset': offset,
                'title': title,
                'index': index,
                'loop': False,
                'shuffle': False
            }
            handler_input.attributes_manager.save_persistent_attributes()

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(token=token,
                                               url=url,
                                               offset_in_milliseconds=offset),
                                 metadata=AudioItemMetadata(
                                     title=title, subtitle=subtitle)))
        return (handler_input.response_builder.add_directive(
            audio_directive).set_should_end_session(True).response)
Esempio n. 7
0
    def handle(self, handler_input):
        language_prompts = handler_input.attributes_manager.request_attributes[
            "_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        print("REACHED THIS POINT")

        if persistent_attributes["playback_session_data"]["next_track_queued"]:
            return handler_input.response_builder.response

        playlist = persistent_attributes['playlist']
        loop = persistent_attributes["playback_session_data"]["loop"]
        index = int(persistent_attributes["playback_session_data"]["index"])

        if index != len(playlist) - 1:
            index += 1
        elif (index == len(playlist) - 1) and loop:
            index = 0
        else:
            return handler_input.response_builder.response

        old_token = persistent_attributes["playback_session_data"]["token"]
        new_token = playlist[index]['token']
        url = playlist[index]['url']
        offset = 0
        title = playlist[index]['title']
        subtitle = "Episode {}".format(new_token)
        persistent_attributes["playback_session_data"].update(
            {'next_track_queued': True})
        handler_input.attributes_manager.save_persistent_attributes()
        #persistent_attributes["playback_session_data"].update({ 'next_track_queued': True, 'token': new_token, 'url': playlist[index]['url'], 'offset': offset, 'title': playlist[index]['title'], 'index': index})
        #handler_input.attributes_manager.save_persistent_attributes()

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.ENQUEUE,
            audio_item=AudioItem(
                stream=Stream(token=new_token,
                              url=url,
                              offset_in_milliseconds=offset,
                              expected_previous_token=old_token),
                metadata=AudioItemMetadata(title=title, subtitle=subtitle)))
        print(audio_directive)
        return (handler_input.response_builder.add_directive(
            audio_directive).response)
 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
     """
     pellicula_slot = get_most_probable_value_for_slot(
         handler_input, "pellicula")
     if pellicula_slot is None:
         handler_input.response_builder.add_directive(
             PlayDirective(
                 PlayBehavior.REPLACE_ALL,
                 AudioItem(Stream(token="cantare_token", url="https://"),
                           AudioItemMetadata("Highway to hell"))))
     else:
         handler_input.response_builder \
             .add_directive(LaunchDirective(VideoItem("https://", Metadata("Orpheus et Eurydike"))))
     return handler_input.response_builder.response
Esempio n. 9
0
    def handle(self, handler_input):
        language_prompts = handler_input.attributes_manager.request_attributes[
            "_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        playlist = populate_playlist_from_rss(rss_url)
        token = handler_input.request_envelope.request.intent.slots[
            "EpisodeNumber"].value
        if token is None:
            token = handler_input.request_envelope.request.intent.slots[
                "OrdinalNumber"].value
        index = int(token) - 1
        url = playlist[index]['url']
        offset = 0
        title = playlist[index]['title']
        subtitle = "Episode {}".format(token)
        persistent_attributes['playlist'] = playlist
        persistent_attributes["playback_session_data"] = {
            'next_track_queued': False,
            'token': token,
            'url': url,
            'offset': offset,
            'title': title,
            'index': index,
            'loop': False,
            'shuffle': False
        }
        handler_input.attributes_manager.save_persistent_attributes()

        speech_output = random.choice(
            language_prompts["PLAYING_CHOSEN_EPISODE"]).format(token)

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(token=token,
                                               url=url,
                                               offset_in_milliseconds=offset),
                                 metadata=AudioItemMetadata(
                                     title=title, subtitle=subtitle)))
        return (
            handler_input.response_builder.speak(speech_output).add_directive(
                audio_directive).set_should_end_session(True).response)
Esempio n. 10
0
def add_screen_background(card_data):
    # type: (Dict) -> Optional[AudioItemMetadata]
    if card_data:
        metadata = AudioItemMetadata(
            title=card_data["title"],
            subtitle=card_data["text"],
            art=display.Image(
                content_description=card_data["title"],
                sources=[
                    display.ImageInstance(
                        url="https://alexademo.ninja/skills/logo-512.png")
                ]),
            background_image=display.Image(
                content_description=card_data["title"],
                sources=[
                    display.ImageInstance(
                        url="https://alexademo.ninja/skills/logo-512.png")
                ]))
        return metadata
    else:
        return None
Esempio n. 11
0
    def handle(self, handler_input):
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        playlist = persistent_attributes['playlist']
        token = persistent_attributes["playback_session_data"]["token"]
        url = persistent_attributes["playback_session_data"]["url"]
        offset = 0
        title = persistent_attributes["playback_session_data"]["title"]
        subtitle = "Episode {}".format(token)

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(token=token,
                                               url=url,
                                               offset_in_milliseconds=offset),
                                 metadata=AudioItemMetadata(
                                     title=title, subtitle=subtitle)))
        logger.info("Playback Failed: {}".format(
            handler_input.request_envelope.request.error))
        return (handler_input.response_builder.add_directive(
            audio_directive).set_should_end_session(True).response)
Esempio n. 12
0
    def handle(self, handler_input):
        """Handle the request.

        We need to look up the last track that was playing, along with its
        playback time from which we need to resume, expressed in milliseconds
        offset from zero.  We then need to build and send the playback directive
        which will contain that information.

        Ends session as is required by the AudioPlayer.

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

        """
        msg = "Resuming audio playback..."
        LOGGER.info(msg)

        userSession = session.KilianUserSession(handler_input)
        track = userSession.lastTrack
        token = userSession.lastToken
        offsetInMilliseconds = userSession.offsetInMilliseconds

        title = "Latest Homily"
        text = title

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(
                expected_previous_token=None,
                token=token,
                url=track,
                offset_in_milliseconds=offsetInMilliseconds),
                                 metadata=AudioItemMetadata(
                                     title="Latest Homily",
                                     subtitle=text,
                                 )))
        handler_input.response_builder.add_directive(directive)
        handler_input.response_builder.set_should_end_session(True)
        return handler_input.response_builder.response
Esempio n. 13
0
    def handle(self, handler_input):
        """Handle the request.

        We need to know the track that was playing last. We can give it
        an offset of zero, ensuring that it plays from the beginning as
        requested. We then need to build and deliver the directive.

        Ends session as is required by the AudioPlayer.

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

        """
        userId = handler_input.request_envelope.context.system.user.user_id
        dataMan = kilian_data.KilianDataManager()
        dbEntry = dataMan.getUserDatabaseEntry(userId)
        track = dbEntry.get("lastTrack")
        token = dbEntry.get("lastToken")
        if not track:
            LOGGER.info("No lastTrack found in database! Can't start over.")
            return {}
        LOGGER.info("Starting over, track: {}".format(track))

        offsetInMilliseconds = 0

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(
                expected_previous_token=None,
                token=token,
                url=track,
                offset_in_milliseconds=offsetInMilliseconds),
                                 metadata=AudioItemMetadata(
                                     title="Latest Homily",
                                     subtitle="Latest Homily",
                                 )))
        handler_input.response_builder.add_directive(directive)
        handler_input.response_builder.set_should_end_session(True)
        return handler_input.response_builder.response
Esempio n. 14
0
    def getLatestHomily(self):
        """Determine the latest recorded homily & return a directive for it."""
        #homilyUrl = "https://st-killian-resources.s3.amazonaws.com/homilies/06-17-19_TheChristianLifeIsLikeAJob.mp3"  # pylint: disable=C0301
        homilyUrl = "https://st-killian-resources.s3.amazonaws.com/homilies/killianGeneric_mixdown.mp3"  # pylint: disable=C0301
        #token = "06-17-19_TheChristianLifeIsLikeAJob"
        token = "kilianGeneric_mixdown"

        #speech = "Okay. Here is a homily from Sunday, "
        #speech += "June seventeenth by Father Dwyer. "
        #title = "Latest Homily"
        #text = "June 17, 2019 Father Dwyer"
        speech = ""
        title = "St. Kilian audio"
        text = "St. Kilian audio coming soon!"

        self.userSession.lastToken = token
        self.userSession.lastTrack = homilyUrl
        self.userSession.savePersistentAttrs()

        sessionAttrs = {
            "lastTrack": homilyUrl,
            "lastToken": token
        }

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(
                    expected_previous_token=None,
                    token=token,
                    url=homilyUrl,
                    offset_in_milliseconds=0
                ),
                metadata=AudioItemMetadata(
                    title="Latest Homily",
                    subtitle=text
                )
            )
        )
        return speech, title, text, directive, sessionAttrs
Esempio n. 15
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
Esempio n. 16
0
    def getLatestTalk(self):
        """Determine the latest recorded talk & return a directive for it."""
        dataMan = kilian_data.KilianDataManager()
        talk = dataMan.getLatestTalk()
        talkUrl = talk['url']
        token = talk['namespace']

        talkDate = datetime.date(talk["eventYear"], talk["eventMonth"], talk["eventDay"])
        speech = "Okay. Here is a talk from  "
        speech += "{}".format(talkDate.strftime("%A, %B %d, %Y"))
        title = "St. Kilian: Latest Talk"
        text = talk['eventTitle']

        self.userSession.lastToken = token
        self.userSession.lastTrack = talkUrl
        self.userSession.savePersistentAttrs()

        sessionAttrs = {
            "lastTrack": talkUrl,
            "lastToken": token
        }

        directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(
                stream=Stream(
                    expected_previous_token=None,
                    token=token,
                    url=talkUrl,
                    offset_in_milliseconds=0
                ),
                metadata=AudioItemMetadata(
                    title="Latest Talk",
                    subtitle=text
                )
            )
        )
        return speech, title, text, directive, sessionAttrs
Esempio n. 17
0
    def handle(self, handler_input):
        language_prompts = handler_input.attributes_manager.request_attributes[
            "_"]
        persistent_attributes = handler_input.attributes_manager.persistent_attributes

        playlist = persistent_attributes['playlist']
        index = int(persistent_attributes["playback_session_data"]["index"])
        token = persistent_attributes['playlist'][index]['token']
        url = persistent_attributes['playlist'][index]['url']
        title = persistent_attributes['playlist'][index]['title']
        subtitle = "Episode {}".format(token)

        audio_directive = PlayDirective(
            play_behavior=PlayBehavior.REPLACE_ALL,
            audio_item=AudioItem(stream=Stream(
                token=token,
                url=url,
                offset_in_milliseconds=0,
            ),
                                 metadata=AudioItemMetadata(
                                     title=title, subtitle=subtitle)))

        return (handler_input.response_builder.add_directive(
            audio_directive).set_should_end_session(True).response)
Esempio n. 18
0
    def handle(self, handler_input):
        # type: (handler_input) -> Response

        logger.info(">>>>> In LaunchRequestHandler")
        interfaces = (ask_utils.request_util.get_supported_interfaces(
            handler_input).to_dict())

        with open("parameters.json") as conf_data:
            conf = json.load(conf_data)
        locale = ask_utils.get_locale(handler_input)
        logger.debug(f"Locale is {locale}")
        # localized strings stored in language_strings.json
        with open("language_strings.json") as language_prompts:
            language_data = json.load(language_prompts)
        try:
            loc_data = language_data[locale[:2]]
            skill_name = loc_data['SKILL_NAME']
        except KeyError:
            loc_data = language_data['en']
            skill_name = loc_data['SKILL_NAME']
        speak_output = loc_data['NO_VIDEO']
        channel_id = loc_data['CHANNEL']
        youtube_url = (
            "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="
            + channel_id + "&maxResults=1&order=date&type=video&key=" +
            conf['youtube_key'])
        success = True
        try:
            url = urllib.request.urlopen(youtube_url)
        except URLError as e:
            speak_output = loc_data['URL_ERROR']
            logger.info("URLError %s", e)
            success = False
        except HTTPError as e:
            logger.info("HTTPError %s, %e", e, e.code)
            if e.code == 429:
                speak_output = loc_data['TOO_MANY_REQUESTS']
            success = False
        if success:
            try:
                data = json.loads(url.read().decode())
                videoId = data['items'][0]['id']['videoId']
                yt = YouTube('https://www.youtube.com/watch?v=' + videoId)
            except Exception as e:
                speak_output = loc_data['YOUTUBE_ERROR']
                success = False
        if success:
            logger.info("List of the available interfaces: %s", interfaces)
            if interfaces['video_app'] is not None:  # device has video support
                for stream in yt.streams.order_by('resolution').desc():
                    if stream.includes_audio_track:
                        break
                speak_output = loc_data[
                    'VIDEO_MESSAGE'] + ": " + stream.title + ". " + yt.description
                logger.info("Video {}. "
                            "Locale='{}'. "
                            "channel_id='{}'. "
                            "speak_output='{}'. "
                            "youtube_key='{}'".format(stream, locale[:2],
                                                      channel_id, speak_output,
                                                      conf['youtube_key']))
                directive = LaunchDirective(video_item=VideoItem(
                    source=stream.url,
                    metadata=Metadata(title=stream.title,
                                      subtitle=yt.description)))
                return (handler_input.response_builder.speak(
                    speak_output).add_directive(directive).response)
            elif interfaces[
                    'audio_player'] is not None:  # device has only audio support (no video)
                stream = (yt.streams.filter(
                    only_audio=True,
                    subtype='mp4').order_by('fps').desc().first())
                speak_output = loc_data[
                    'AUDIO_MESSAGE'] + ": " + stream.title + ". " + yt.description
                logger.info("Audio {}. "
                            "Locale='{}'. "
                            "channel_id='{}'. "
                            "speak_output='{}'. "
                            "youtube_key='{}'".format(stream, locale[:2],
                                                      channel_id, speak_output,
                                                      conf['youtube_key']))
                directive = PlayDirective(
                    play_behavior=PlayBehavior.REPLACE_ALL,
                    audio_item=AudioItem(
                        stream=Stream(expected_previous_token=None,
                                      token=stream.url,
                                      url=stream.url,
                                      offset_in_milliseconds=0),
                        metadata=AudioItemMetadata(
                            title=stream.title,
                            subtitle=yt.description,
                            art=display.Image(
                                content_description=stream.title,
                                sources=[
                                    display.ImageInstance(url=yt.thumbnail_url)
                                ]),
                            background_image=display.Image(
                                content_description=stream.title,
                                sources=[
                                    display.ImageInstance(url=yt.thumbnail_url)
                                ]))))
                return (handler_input.response_builder.speak(
                    speak_output).add_directive(
                        directive).set_should_end_session(True).response)
            else:
                speak_output = loc_data[
                    'NO_INTERFACE'] + ": " + stream.title + ". " + yt.description
        return (handler_input.response_builder.speak(speak_output).response)