def __init__(self,
                 bot: BotBase,
                 loglevel: int = logging.INFO,
                 logfile: Optional[str] = None) -> None:
        self._bot = bot
        self._skill_builder = SkillBuilder()
        self._skill_builder.request_handlers.extend([
            LaunchRequestHandler(self._bot),
            IntentRequestHandler(self._bot),
            SessionEndedRequestHandler(self._bot),
        ])
        self._skill_builder.add_exception_handler(
            DefaultExceptionHandler(self._bot))

        self._skill = Skill(
            skill_configuration=self._skill_builder.skill_configuration)

        super().__init__(loglevel=loglevel, logfile=logfile)
Exemple #2
0
    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speak_output = "Sorry, I had trouble doing what you asked. Please try again."

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


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(YesHandler())
sb.add_request_handler(NoHandler())
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(NatureChoiceRequestHandler())
sb.add_request_handler(IntroductionRequestHandler())
sb.add_request_handler(StareAtNatureRequestHandler())
sb.add_request_handler(FeelTheNatureRequestHandler())
sb.add_request_handler(DeepDiveIntoNatureRequestHandler())
sb.add_request_handler(LearnAboutNatureRequestHandler())
sb.add_request_handler(ParticipativeScienceNatureRequestHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(
        return True

    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speak_output = "Sorry, I had trouble doing what you asked. Please try again."

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

# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.


sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers

sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
Exemple #4
0
    "<speak>Bienvenido a la Skill de " + SKILL_NAME +
    ", aquí podré calcular tu <sub alias=\"I M C\">IMC</sub>, solo dime tu peso y estatura. <break time=\"500ms\"/> Si necesitas ayuda, solo dí: 'Ayuda'. Recuerda que este diagnostico es únicamente con fines informativos y educativos, y no es un sustituto del asesoramiento, tratamiento o diagnóstico médico profesional. Llame a su médico para recibir asesoramiento médico. ¿Qué deseas realizar? </speak>"
)
HELP_MESSAGE = ('''<speak> 
    <p>Si deseas tu <sub alias=\"I M C\">IMC</sub>, puedes pedirme: <s>"Alexa, abre '''
                + SKILL_NAME +
                ''' y dime cómo estoy"<break time=\"500ms\"/> </s> </p> 
    <p>También, puedes decirme: <s>"Calcula mi <sub alias=\"I M C\">IMC</sub>"<break time=\"500ms\"/> </s> </p> 
    <p>Si deseas saber que es el <sub alias=\"I M C\">IMC</sub>, puedes decirme: <s>"Quiero saber qué es <sub alias=\"I M C\">IMC</sub>"<break time=\"500ms\"/> </s> </p> 
    ¿Qué deseas realizar?
    </speak>''')
HELP_REPROMPT = (HELP_MESSAGE)
STOP_MESSAGE = "Gracias por usar esta skill. ¡Adiós! "
EXCEPTION_MESSAGE = "No entendí muy bien, ¿Qué deseas realizar?"

sb = SkillBuilder()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def apl_img_title_text(title, text):
    return {
        "json": "apl_img_title_text.json",
        "datasources": {
            "bodyTemplate1Data": {
                "type":
                "object",
                "objectId":
                "bt1Sample",
                "backgroundImage": {
                    "contentDescription":
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speak_output = "I'm sorry, I don't really know what you mean..."
        
        return (
            handler_input.response_builder
                .speak(speak_output)
                .ask(speak_output)
                .response
        )

# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.


sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(EmotionIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(OpinionIntentHandler())
sb.add_request_handler(PolarIntentHandler())
sb.add_request_handler(SituationIntentHandler())
sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
Exemple #6
0
import ask_sdk_core
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler, AbstractExceptionHandler
from ask_sdk_core.utils import is_request_type, is_intent_name

sb = SkillBuilder()


class ErrorHandler(AbstractExceptionHandler):
    def can_handle(self, handler_input, exception):
        return True

    def handle(self, handler_input, exception):
        speech_text = 'Sorry, your skill encountered an error'
        print(exception)
        handler_input.response_builder.speak(
            speech_text).set_should_end_session(False)
        return handler_input.response_builder.response


class LaunchRequestHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        return is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        speech_text = 'What Do you want to know'
        handler_input.response_builder.speak(
            speech_text).set_should_end_session(False)
        return handler_input.response_builder.response

Exemple #7
0
    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speak_output = "Desculpe, eu não entendi o que você pediu."

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


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
#========CRIADOS===========================

sb.add_request_handler(saldoBancarioIntentHandler())
sb.add_request_handler(pagementoPeriodoIntent())
sb.add_request_handler(realizarPagamentoIntent())
sb.add_request_handler(volumeVendasIntent())
sb.add_request_handler(melhorVendedorIntent())
sb.add_request_handler(agradeceIntent())
sb.add_request_handler(pitchIntent())

#=========================================
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
Exemple #8
0
# https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-python/develop-your-first-skill.html

from ask_sdk_core.skill_builder import SkillBuilder


sb = SkillBuilder()

from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
from ask_sdk_model.ui import SimpleCard

class LaunchRequestHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speech_text = "Welcome to the Alexa Skills Kit, you can say hello!"

        handler_input.response_builder.speak(speech_text).set_card(
            SimpleCard("Hello World", speech_text)).set_should_end_session(
            False)
        return handler_input.response_builder.response


class HelloWorldIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
Exemple #9
0
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.dispatch_components import \
    AbstractRequestHandler, \
    AbstractExceptionHandler, \
    AbstractRequestInterceptor
from ask_sdk_core.utils import \
    is_request_type, \
  is_intent_name
"""
thanks to https://github.com/dawoudt/JustWatchAPI
"""

# Skill Builder object
sb = SkillBuilder()
api = "https://api.justwatch.com/titles/en_US/popular"
head = {'User-Agent': 'StreamIt Amazon Alexa Skill'}
"""
code to get providers:
requests.Session().get("https://apis.justwatch.com/content/providers/locale/en_US").json()
we only want ones with 'flatrate' in monetization_types[]
map 'id' to 'clear_name'
"""
providers = {
    "2": "Apple iTunes",
    "3": "Google Play Movies",
    "7": "Vudu",
    "8": "Netflix",
    "9": "Amazon Prime Video",
    "10": "Amazon Video",
        
        speech_output = language_prompts["ERROR"]
        reprompt = language_prompts["ERROR_REPROMPT"]
        
        return (
            handler_input.response_builder
                .speak(speech_output)
                .ask(reprompt)
                .response
            )

# Skill Builder
# Define a skill builder instance and add all the request handlers,
# exception handlers and interceptors to it.

sb = SkillBuilder()
sb.add_request_handler(CheckAudioInterfaceHandler())
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(ResumeStreamIntentHandler())
sb.add_request_handler(UnhandledFeaturesIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(AboutIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(PlaybackStartedIntentHandler())
sb.add_request_handler(PlaybackStoppedIntentHandler())
sb.add_request_handler(PlaybackFailedIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())

sb.add_exception_handler(CatchAllExceptionHandler())
Exemple #11
0
import logging
import gettext

from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.dispatch_components import (
    AbstractRequestHandler, AbstractExceptionHandler,
    AbstractResponseInterceptor, AbstractRequestInterceptor)
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response

from alexa import data, util


sb = SkillBuilder()

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


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
        logger.info("In LaunchRequestHandler")
        _ = handler_input.attributes_manager.request_attributes["_"]
    Add function to request attributes, that can load locale specific data
    """
    def process(self, handler_input):
        locale = handler_input.request_envelope.request.locale
        i18n = gettext.translation('data',
                                   localedir='locales',
                                   languages=[locale],
                                   fallback=True)
        handler_input.attributes_manager.request_attributes["_"] = i18n.gettext


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(HelloWorldIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
# make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
sb.add_request_handler(IntentReflectorHandler())

sb.add_global_request_interceptor(LocalizationInterceptor())

sb.add_exception_handler(CatchAllExceptionHandler())

handler = sb.lambda_handler()
Exemple #13
0
    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)

        speak_output = "Perdón, he tenido un problema. Prueba de nuevo"

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


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(HelloWorldIntentHandler())
sb.add_request_handler(OpcionesIntentHandler())
sb.add_request_handler(DineroGravityIntentHandler())
sb.add_request_handler(DineroDestinyIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(PresupuestoGravityIntentHandler())
sb.add_request_handler(PresupuestoDestinyIntentHandler())
sb.add_request_handler(ComprometidoGravityIntentHandler())
sb.add_request_handler(ComprometidoDestinyIntentHandler())
sb.add_request_handler(ErogadoGravityIntentHandler())
sb.add_request_handler(ErogadoDestinyIntentHandler())
sb.add_request_handler(DiponibleGravityIntentHandler())
sb.add_request_handler(DiponibleDestinyIntentHandler())
        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).response)


# Lo and behold the function I am the most proud of creating
# This was when I realized that all that Alexa was sending was purely JSON data and I could navigate it because I knew what it meant.
def get_spoken_value(request, slot_name):
    if request.intent.slots[slot_name].slotValue["type"] == "List":
        return request.intent.slots[slot_name].slotValue["values"][0]["value"] + " " + \
               request.intent.slots[slot_name].slotValue["values"][1]["value"]
    else:
        return request.intent.slots[slot_name].value


# This is how the ASK SDK library works - with initializing a skill builder object and then adding a request handler of each object in order to give each function the ability to be called at once.
sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(TypeIntentHandler())
sb.add_request_handler(IDIntentHandler())
sb.add_request_handler(MoveIntentHandler())
sb.add_request_handler(HowLearnMoveIntentHandler())
sb.add_request_handler(DescriptionIntentHandler())
sb.add_request_handler(RepromptIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())

# sb.add_request_handler(
#     IntentReflectorHandler())  # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers

class CatchAllExceptionHandler(AbstractExceptionHandler):
    def can_handle(self, handler_input, exception):
        return True

    def handle(self, handler_input, exception):
        logger.error(exception, exc_info=True)

        speak_output = "O dado informado é inválido! Tente novamente."

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


sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(IntervalChangeIntentHandler())
sb.add_request_handler(TimeOfflineChangeIntentHandler())
sb.add_request_handler(GetIntervalIntentHandler())
sb.add_request_handler(GetTimeOfflineIntentHandler())
sb.add_request_handler(GetBraceletStatusIntentHandler())
sb.add_request_handler(GetDataIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(IntentReflectorHandler())
sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
Exemple #16
0
import boto3
import json
import logging
import sys
sys.path.append('./skill/ask-sdk')
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_model.ui import SimpleCard
from ask_sdk_model.slu.entityresolution import status_code

sb = SkillBuilder()
client = boto3.client('lambda')
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)


def getKakugen(code):
    if not code:
        raise Exception('BAD CODE')

    # logger.debug(str(code))
    request = {
        'FunctionName': 'ShogiKakugenAPI',
        'InvocationType': 'RequestResponse',
        'LogType': 'None',
        'Payload': json.dumps({
            'id': code['id'],
            'type': code['type']
        })
    }
Exemple #17
0
import speech_helper
import sentiment_helper
import random
import json
import string

from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response

from meme_helper import get_meme

sb = SkillBuilder()

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

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Greatle_Users')
GOAL_TO_DELETE_SESSION_ATTRIBUTE = "goal_to_delete"
LAST_QUERY_SESSION_ATTRIBUTE = "last_query"
LAST_QUERY_ID_SESSION_ATTRIBUTE = "last_query_id"
LAST_DOCUMENT_ID_SESSION_ATTRIBUTE = "last_document_id"
LAST_AUTHOR_SESSION_ATTRIBUTE = 'last_author'
card_title = 'Henry by Greatle'


class LaunchRequestHandler(AbstractRequestHandler):
        return (handler_input.response_builder.speak(speak_output).response)


class CatchAllExceptionHandler(AbstractExceptionHandler):
    def can_handle(self, handler_input, exception):
        return True

    def handle(self, handler_input, exception):
        logger.error(exception, exc_info=True)

        speak_output = "Desculpe, tive um problema ao atender sua solicitação. Tente novamente."

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


sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(NextBossByNameIntentHandler())
sb.add_request_handler(NextBossIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(IntentReflectorHandler())

sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
Exemple #19
0
                                   languages=[locale],
                                   fallback=True)
        handler_input.attributes_manager.request_attributes["_"] = i18n.gettext


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.


@app.route('/ddog/webhook')
def alert(payload):
    return payload


sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(GetMetricsIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
# make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
sb.add_request_handler(IntentReflectorHandler())

sb.add_global_request_interceptor(LocalizationInterceptor())

sb.add_exception_handler(CatchAllExceptionHandler())

skill_response = SkillAdapter(
    skill=sb.create(),
Exemple #20
0
import logging
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response
from pokedex_logic import pokedex

sb = SkillBuilder()


@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    speech_text = "Welcome to the Alexa Pokedex!"
    return handler_input.response_builder.speak(speech_text).set_card(SimpleCard("Hello World", speech_text)).set_should_end_session(False).response


@sb.request_handler(can_handle_func=is_intent_name("pokemon_intent"))
def pokemon_intent_handler(handler_input):
    pokemon_species = pokedex.get_species()
    pokemon_data = pokedex.get_pokemon_data(pokemon_species)
    pokemon = pokedex.generate_alexa_text_string(pokemon_species, pokemon_data)
    speech_text = "{}".format(pokemon)
    return handler_input.response_builder.speak(speech_text).set_card( SimpleCard("Pokedex", speech_text)).set_should_end_session(True).response


@sb.request_handler(can_handle_func=is_intent_name("AMAZON.HelpIntent"))
def help_intent_handler(handler_input):
    speech_text = "You can ask me for a pokemon!"
    return handler_input.response_builder.speak(speech_text).ask(speech_text).set_card(SimpleCard("Hello World", speech_text)).response
from ask_sdk_core.dispatch_components import (AbstractRequestHandler,
                                              AbstractExceptionHandler,
                                              AbstractRequestInterceptor,
                                              AbstractResponseInterceptor)
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput

from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response

from random import randint

SKILL_NAME = "Dice Coin Coins"
dice_slot = "dice"

sb = SkillBuilder()
# logger = logging.getLogger(_name_)
# logger.setLevel(logging.DEBUG)


class DefaultHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        return (is_request_type("LaunchRequest")(handler_input)
                or is_intent_name("AMAZON.HelpIntent")(handler_input))

    def handle(self, handler_input):
        logging.info("Starting Default")
        speech = "You can ask me to roll a dice or flip a coin"

        handler_input.response_builder.speak(speech).set_card(
            SimpleCard(SKILL_NAME, speech)).ask(speech)
Exemple #22
0
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_model import DialogState

from alexa.request_handler.buildin.cancel_and_stop import cancel_and_stop_request
from alexa.request_handler.buildin.exception import exception_request
from alexa.request_handler.buildin.fallback import fallback_request
from alexa.request_handler.buildin.help import help_request
from alexa.request_handler.intents.choose_scenario import choose_sceanrio_request, in_progress_choose_sceanrio_request
from alexa.request_handler.intents.close_box_start_game import close_box_start_game_request
from alexa.request_handler.intents.pose_riddle import pose_riddle_request
from alexa.request_handler.launch import launch_request
from escapehome import settings

sb = SkillBuilder()

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

MINUS_POINTS = -1
QUIT_MINUS_POINTS = -10


@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    """Handler for Skill Launch."""
    return launch_request(handler_input)


@sb.request_handler(
Exemple #23
0
import requests
import googlemaps
import json

from datetime import datetime

from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput

from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response

sb = SkillBuilder()

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


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


    def find_key(strInput, search):
        list_string = strInput.split()
        loc = list_string[list_string.index(search) + 1]
Exemple #24
0
        logger.debug("Alexa Request: {}".format(
            handler_input.request_envelope.request))


class ResponseLogger(AbstractResponseInterceptor):
    """Log the alexa responses."""

    def process(self, handler_input, response):
        # type: (HandlerInput, Response) -> None
        logger.debug("Alexa Response: {}".format(response))


# This handler acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.
sb = SkillBuilder()
sb.add_request_handler(WaterPlantsHandler())
sb.add_request_handler(SensorReadingHandler())
sb.add_request_handler(ReadingMaxDataHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())

# Register exception handlers
sb.add_exception_handler(CatchAllExceptionHandler())

# TODO: Uncomment the following lines of code for request, response logs.
sb.add_global_request_interceptor(RequestLogger())
sb.add_global_response_interceptor(ResponseLogger())
Exemple #25
0
    def can_handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> bool
        return True

    def handle(self, handler_input, exception):
        # type: (HandlerInput, Exception) -> Response
        logger.error(exception, exc_info=True)
        speak_output = "Sorry, I had trouble doing what you asked. Please try again."
        return (handler_input.response_builder.speak(speak_output).ask(
            speak_output).response)


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(NumberofThreatsIntentHandler())
sb.add_request_handler(TopOneorFiveThreatIntentHandler())
sb.add_request_handler(AlertNotifiactionThreatsIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
# make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
sb.add_request_handler(IntentReflectorHandler())
sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
Exemple #26
0
    the intent being invoked or included it in the skill builder below.
    """
    def can_handle(self, handler_input, exception):
        return True

    def handle(self, handler_input, exception):
        logger.error(exception, exc_info=True)

        speak_output = "Sorry, I had trouble doing what you asked. Please try again."

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


# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.

sb = SkillBuilder()

sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(BloodSugarIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
# make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
sb.add_request_handler(IntentReflectorHandler())

sb.add_exception_handler(CatchAllExceptionHandler())

lambda_handler = sb.lambda_handler()
import random
import string
import os

from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import (AbstractRequestHandler,
                                              AbstractExceptionHandler,
                                              AbstractRequestInterceptor,
                                              AbstractResponseInterceptor)
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput

from ask_sdk_model.ui import SimpleCard
from ask_sdk_model import Response

sb = SkillBuilder()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


# Built-in Intent Handlers
class StartSessionHandler(AbstractRequestHandler):
    """Handler for Skill Launch."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return (is_request_type("LaunchRequest")(handler_input)
                or is_intent_name("StartSessionIntent")(handler_input))

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In StartSessionHandler")
Exemple #28
0
class TestSkillBuilder(unittest.TestCase):
    def setUp(self):
        self.sb = SkillBuilder()

    def test_skill_configuration_getter_no_registered_components(self):
        actual_config = self.sb.skill_configuration

        assert actual_config.request_mappers is not None, (
            "Skill Configuration getter in Skill Builder didn't set request "
            "mappers correctly")
        assert actual_config.request_mappers[
            0].request_handler_chains is not None, (
                "Skill Configuration getter in Skill Builder didn't set handler "
                "chains in request mappers correctly")
        assert len(
            actual_config.request_mappers[0].request_handler_chains) == 0, (
                "Skill Configuration getter in Skill Builder added invalid "
                "handler in handler chain, "
                "when no request handlers are registered")
        assert actual_config.handler_adapters is not None, (
            "Skill Configuration getter in Skill Builder didn't set handler "
            "adapters correctly")
        assert isinstance(
            actual_config.handler_adapters[0], GenericHandlerAdapter
        ), ("Skill Configuration getter in Skill Builder didn't set default "
            "handler adapter")
        assert isinstance(
            actual_config.exception_mapper, GenericExceptionMapper), (
                "Skill Configuration getter in Skill Builder created invalid "
                "exception mapper, "
                "when no exception handlers are registered")
        assert len(actual_config.exception_mapper.exception_handlers) == 0, (
            "Skill Configuration getter in Skill Builder created invalid "
            "exception handlers in exception mapper, "
            "when no exception handlers are registered")
        assert actual_config.request_interceptors == [], (
            "Skill Configuration getter in Skill Builder created invalid "
            "request interceptors, "
            "when no global request interceptors are registered")
        assert actual_config.response_interceptors == [], (
            "Skill Configuration getter in Skill Builder created invalid "
            "response interceptors, "
            "when no global response interceptors are registered")
        assert actual_config.custom_user_agent is None, (
            "Skill Configuration getter in Skill Builder set invalid custom "
            "user agent")
        assert actual_config.skill_id is None, (
            "Skill Configuration getter in Skill Builder set invalid skill id")

    def test_skill_configuration_getter_handlers_registered(self):
        mock_request_handler = mock.MagicMock(spec=AbstractRequestHandler)
        self.sb.add_request_handler(request_handler=mock_request_handler)

        mock_exception_handler = mock.MagicMock(spec=AbstractExceptionHandler)
        self.sb.add_exception_handler(exception_handler=mock_exception_handler)

        actual_config = self.sb.skill_configuration

        assert actual_config.request_mappers is not None, (
            "Skill Configuration getter in Skill Builder didn't set request "
            "mappers correctly")
        assert actual_config.request_mappers[
            0].request_handler_chains is not None, (
                "Skill Configuration getter in Skill Builder didn't set handler "
                "chains in request mappers correctly")
        assert len(
            actual_config.request_mappers[0].request_handler_chains) == 1, (
                "Skill Configuration getter in Skill Builder didn't add valid "
                "handler in handler chain, "
                "when request handlers are registered")
        assert actual_config.request_mappers[0].request_handler_chains[
            0].request_handler == mock_request_handler, (
                "Skill Configuration getter in Skill Builder added invalid "
                "handler in handler chain, "
                "when request handlers are registered")

        assert actual_config.exception_mapper is not None, (
            "Skill Configuration getter in Skill Builder didn't create "
            "exception mapper, "
            "when exception handlers are registered")
        assert len(actual_config.exception_mapper.exception_handlers) == 1, (
            "Skill Configuration getter in Skill Builder added additional "
            "exception handlers than the registered ones "
            "in exception mapper")
        assert actual_config.exception_mapper.exception_handlers[
            0] == mock_exception_handler, (
                "Skill Configuration getter in Skill Builder added invalid "
                "handler in exception mapper, "
                "when exception handlers are registered")

    def test_create_skill(self):
        mock_request_handler = mock.MagicMock(spec=AbstractRequestHandler)
        self.sb.add_request_handler(request_handler=mock_request_handler)

        mock_exception_handler = mock.MagicMock(spec=AbstractExceptionHandler)
        self.sb.add_exception_handler(exception_handler=mock_exception_handler)

        actual_skill = self.sb.create()
        expected_skill = CustomSkill(self.sb.skill_configuration)

        assert actual_skill.request_dispatcher.request_mappers[0].request_handler_chains[0].request_handler == \
            expected_skill.request_dispatcher.request_mappers[0].request_handler_chains[0].request_handler, (
            "Skill Builder created skill with incorrect request handlers when "
            "using create method")

        assert actual_skill.request_dispatcher.exception_mapper.exception_handlers[0] == \
            expected_skill.request_dispatcher.exception_mapper.exception_handlers[0], (
            "Skill Builder created skill with incorrect exception handlers "
            "when using create method")

    def test_lambda_handler_creation(self):
        handler_func = self.sb.lambda_handler()
        assert callable(handler_func), "Skill Builder Lambda Handler " \
                                       "function returned an invalid object"

        actual_arg_spec = inspect.getargspec(handler_func)
        assert len(actual_arg_spec.args) == 2, (
            "Skill Builder Lambda Handler function created a handler of "
            "different signature than AWS Lambda")
        assert "event" in actual_arg_spec.args, (
            "Skill Builder Lambda Handler function created a handler without "
            "named parameter event")
        assert "context" in actual_arg_spec.args, (
            "Skill Builder Lambda Handler function created a handler without "
            "named parameter context")

    def test_lambda_handler_invocation(self):
        mock_request_handler = mock.MagicMock(spec=AbstractRequestHandler)
        mock_request_handler.can_handle.return_value = True
        mock_response = Response()
        mock_response.output_speech = "test output speech"
        mock_request_handler.handle.return_value = mock_response
        self.sb.add_request_handler(request_handler=mock_request_handler)

        mock_request_envelope_payload = {
            "context": {
                "System": {
                    "application": {
                        "applicationId": "test"
                    }
                }
            }
        }

        self.sb.skill_id = "test"
        lambda_handler = self.sb.lambda_handler()

        response_envelope = lambda_handler(event=mock_request_envelope_payload,
                                           context=None)

        assert response_envelope["version"] == RESPONSE_FORMAT_VERSION, (
            "Response Envelope from lambda handler invocation has version "
            "different than expected")
        assert response_envelope["userAgent"] == user_agent_info(
            sdk_version=__version__, custom_user_agent=None
        ), ("Response Envelope from lambda handler invocation has user agent "
            "info different than expected")
        assert response_envelope["response"][
            "outputSpeech"] == "test output speech", (
                "Response Envelope from lambda handler invocation has incorrect "
                "response than built by skill")
Exemple #29
0
    speech_text = GAME_META[
        state["game_type"]]["launch_message"] + state["ssml_pattern"]
    handler_input.response_builder.speak(speech_text).ask(
        REPROMPT_MESSAGE + state["ssml_pattern"]).set_card(
            SimpleCard(CARD_TITLE.format(1),
                       state["card_pattern"])).set_should_end_session(False)

    return handler_input.response_builder.response


# Request handlers, covering the following intents:
# LaunchRequest
# IntentRequest: AnimalIntent, HelpIntent, StopIntent, CancelIntent, FallbackIntent
# SessionEndedRequest

sb = SkillBuilder()


@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    """Create the game. Invoked when user says: 'Alexa, open Animal Patterns.'"""

    return create_game(handler_input)


@sb.request_handler(
    can_handle_func=lambda input: is_intent_name(ANIMAL_INTENT_NAME)
    (input) or is_intent_name("AMAZON.FallbackIntent")(input))
def animal_intent_handler(handler_input):
    """Handle AnimalIntent and FallbackIntent
Exemple #30
0
 def setUp(self):
     self.sb = SkillBuilder()