# 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(), skill_id="amzn1.ask.skill.1fd6a485-84ff-406c-aba1-75007ce3df11", app=app) skill_response.register(app=app, route="/") if __name__ == '__main__': app.run()
class TestSkillBuilder(unittest.TestCase): def setUp(self): self.sb = SkillBuilder() def test_add_null_request_handler_throw_error(self): with self.assertRaises(SkillBuilderException) as exc: self.sb.add_request_handler(request_handler=None) assert "Valid Request Handler instance to be provided" in str( exc.exception ), ("Add Request Handler method didn't throw exception when a null " "request handler is added") def test_add_invalid_request_handler_throw_error(self): invalid_request_handler = mock.Mock() with self.assertRaises(SkillBuilderException) as exc: self.sb.add_request_handler( request_handler=invalid_request_handler) assert "Input should be a RequestHandler instance" in str( exc.exception), ( "Add Request Handler method didn't throw exception when an " "invalid request handler is added") def test_add_valid_request_handler(self): mock_request_handler = mock.MagicMock(spec=AbstractRequestHandler) self.sb.add_request_handler(request_handler=mock_request_handler) assert self.sb.request_handlers[0] == mock_request_handler, ( "Add Request Handler method didn't add valid request handler to " "Skill Builder Request Handlers list") def test_add_null_exception_handler_throw_error(self): with self.assertRaises(SkillBuilderException) as exc: self.sb.add_exception_handler(exception_handler=None) assert "Valid Exception Handler instance to be provided" in str( exc.exception ), ("Add Exception Handler method didn't throw exception when a null " "exception handler is added") def test_add_invalid_exception_handler_throw_error(self): invalid_exception_handler = mock.Mock() with self.assertRaises(SkillBuilderException) as exc: self.sb.add_exception_handler( exception_handler=invalid_exception_handler) assert "Input should be an ExceptionHandler instance" in str( exc.exception), ( "Add Exception Handler method didn't throw exception when an " "invalid exception handler is added") def test_add_valid_exception_handler(self): mock_exception_handler = mock.MagicMock(spec=AbstractExceptionHandler) self.sb.add_exception_handler(exception_handler=mock_exception_handler) assert self.sb.exception_handlers[0] == mock_exception_handler, ( "Add Exception Handler method didn't add valid exception handler " "to Skill Builder Exception Handlers list") def test_add_null_global_request_interceptor_throw_error(self): with self.assertRaises(SkillBuilderException) as exc: self.sb.add_global_request_interceptor(request_interceptor=None) assert "Valid Request Interceptor instance to be provided" in str( exc.exception), ( "Add Global Request Interceptor method didn't throw exception " "when a null request interceptor is added") def test_add_invalid_global_request_interceptor_throw_error(self): invalid_request_interceptor = mock.Mock() with self.assertRaises(SkillBuilderException) as exc: self.sb.add_global_request_interceptor( request_interceptor=invalid_request_interceptor) assert "Input should be a RequestInterceptor instance" in str( exc.exception), ( "Add Global Request Interceptor method didn't throw exception " "when an invalid request interceptor is added") def test_add_valid_global_request_interceptor(self): mock_request_interceptor = mock.MagicMock( spec=AbstractRequestInterceptor) self.sb.add_global_request_interceptor( request_interceptor=mock_request_interceptor) assert self.sb.global_request_interceptors[0] == \ mock_request_interceptor, ( "Add Global Request Interceptor method didn't add valid request " "interceptor to Skill Builder " "Request Interceptors list") def test_add_null_global_response_interceptor_throw_error(self): with self.assertRaises(SkillBuilderException) as exc: self.sb.add_global_response_interceptor(response_interceptor=None) assert "Valid Response Interceptor instance to be provided" in str( exc.exception ), ("Add Global Response Interceptor method didn't throw exception " "when a null response interceptor is added") def test_add_invalid_global_response_interceptor_throw_error(self): invalid_response_interceptor = mock.Mock() with self.assertRaises(SkillBuilderException) as exc: self.sb.add_global_response_interceptor( response_interceptor=invalid_response_interceptor) assert "Input should be a ResponseInterceptor instance" in str( exc.exception ), ("Add Global Response Interceptor method didn't throw exception " "when an invalid response interceptor " "is added") def test_add_valid_global_response_interceptor(self): mock_response_interceptor = mock.MagicMock( spec=AbstractResponseInterceptor) self.sb.add_global_response_interceptor( response_interceptor=mock_response_interceptor) assert self.sb.global_response_interceptors[0] == \ mock_response_interceptor, ( "Add Global Response Interceptor method didn't add valid response " "interceptor to Skill Builder " "Response Interceptors list") 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], HandlerAdapter), ( "Skill Configuration getter in Skill Builder didn't set default " "handler adapter") assert actual_config.exception_mapper is None, ( "Skill Configuration getter in Skill Builder created invalid " "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 = Skill(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( 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") def test_request_handler_decorator_creation(self): request_handler_wrapper = self.sb.request_handler(can_handle_func=None) assert callable(request_handler_wrapper), ( "Skill Builder Request Handler decorator returned an invalid " "wrapper object") actual_arg_spec = inspect.getargspec(request_handler_wrapper) assert len(actual_arg_spec.args) == 1, ( "Skill Builder Request Handler decorator created a wrapper of " "different signature than expected") assert "handle_func" in actual_arg_spec.args, ( "Skill Builder Request Handler decorator created a wrapper " "without named parameter handler_func") def test_request_handler_decorator_invalid_can_handle_func(self): request_handler_wrapper = self.sb.request_handler(can_handle_func=None) with self.assertRaises(SkillBuilderException) as exc: request_handler_wrapper(handle_func=None) assert "can_handle_func and handle_func input parameters should be callable" in str( exc.exception), ( "Request Handler Decorator accepted invalid can_handle_func " "parameter") def test_request_handler_decorator_invalid_handle_func(self): request_handler_wrapper = self.sb.request_handler( can_handle_func=lambda x: True) with self.assertRaises(SkillBuilderException) as exc: request_handler_wrapper(handle_func=None) assert "can_handle_func and handle_func input parameters should be callable" in str( exc.exception), ( "Request Handler Decorator was decorated on an invalid object") def test_request_handler_decorator_on_valid_handle_func(self): def test_can_handle(input): return True def test_handle(input): return "something" self.sb.request_handler(can_handle_func=test_can_handle)( handle_func=test_handle) actual_request_handler = self.sb.request_handlers[0] assert actual_request_handler.__class__.__name__ == "RequestHandlerTestHandle", ( "Request Handler decorator created Request Handler of incorrect " "name") assert actual_request_handler.can_handle(None) is True, ( "Request Handler decorator created Request Handler with incorrect " "can_handle function") assert actual_request_handler.handle(None) == "something", ( "Request Handler decorator created Request Handler with incorrect " "handle function") def test_exception_handler_decorator_creation(self): exception_handler_wrapper = self.sb.exception_handler( can_handle_func=None) assert callable(exception_handler_wrapper), ( "Skill Builder Exception Handler decorator returned an invalid " "wrapper object") actual_arg_spec = inspect.getargspec(exception_handler_wrapper) assert len(actual_arg_spec.args) == 1, ( "Skill Builder Exception Handler decorator created a wrapper of " "different signature than expected") assert "handle_func" in actual_arg_spec.args, ( "Skill Builder Exception Handler decorator created a wrapper " "without named parameter handler_func") def test_exception_handler_decorator_invalid_can_handle_func(self): exception_handler_wrapper = self.sb.exception_handler( can_handle_func=None) with self.assertRaises(SkillBuilderException) as exc: exception_handler_wrapper(handle_func=None) assert "can_handle_func and handle_func input parameters should be callable" in str( exc.exception), ( "Exception Handler Decorator accepted invalid can_handle_func " "parameter") def test_exception_handler_decorator_invalid_handle_func(self): exception_handler_wrapper = self.sb.exception_handler( can_handle_func=lambda x: True) with self.assertRaises(SkillBuilderException) as exc: exception_handler_wrapper(handle_func=None) assert "can_handle_func and handle_func input parameters should be callable" in str( exc.exception ), ("Exception Handler Decorator was decorated on an invalid object") def test_exception_handler_decorator_on_valid_handle_func(self): def test_can_handle(input, exc): return True def test_handle(input, exc): return "something" self.sb.exception_handler(can_handle_func=test_can_handle)( handle_func=test_handle) actual_exception_handler = self.sb.exception_handlers[0] assert actual_exception_handler.__class__.__name__ == "ExceptionHandlerTestHandle", ( "Exception Handler decorator created Exception Handler of incorrect name" ) assert actual_exception_handler.can_handle(None, None) is True, ( "Exception Handler decorator created Exception Handler with " "incorrect can_handle function") assert actual_exception_handler.handle(None, None) == "something", ( "Exception Handler decorator created Exception Handler with " "incorrect handle function") def test_global_request_interceptor_decorator_creation(self): request_interceptor_wrapper = self.sb.global_request_interceptor() assert callable(request_interceptor_wrapper), ( "Skill Builder Global Request Interceptor decorator returned an " "invalid wrapper object") actual_arg_spec = inspect.getargspec(request_interceptor_wrapper) assert len(actual_arg_spec.args) == 1, ( "Skill Builder Global Request Interceptor decorator created a " "wrapper of different signature than expected") assert "process_func" in actual_arg_spec.args, ( "Skill Builder Global Request Interceptor decorator created a " "wrapper without named parameter process_func") def test_global_request_interceptor_decorator_invalid_process_func(self): request_interceptor_wrapper = self.sb.global_request_interceptor() with self.assertRaises(SkillBuilderException) as exc: request_interceptor_wrapper(process_func=None) assert "process_func input parameter should be callable" in str( exc.exception ), ("Global Request Interceptor Decorator accepted invalid process_func parameter" ) def test_global_request_interceptor_decorator_on_valid_process_func(self): def test_process(input): return "something" self.sb.global_request_interceptor()(process_func=test_process) actual_global_request_interceptor = self.sb.global_request_interceptors[ 0] assert actual_global_request_interceptor.__class__.__name__ == "RequestInterceptorTestProcess" assert actual_global_request_interceptor.process(None) == "something" def test_global_response_interceptor_decorator_creation(self): response_interceptor_wrapper = self.sb.global_response_interceptor() assert callable(response_interceptor_wrapper), ( "Skill Builder Global Request Interceptor decorator returned an " "invalid wrapper object") actual_arg_spec = inspect.getargspec(response_interceptor_wrapper) assert len(actual_arg_spec.args) == 1, ( "Skill Builder Global Response Interceptor decorator created a " "wrapper of different signature than " "expected") assert "process_func" in actual_arg_spec.args, ( "Skill Builder Global Response Interceptor decorator created a " "wrapper without named parameter " "process_func") def test_global_response_interceptor_decorator_invalid_process_func(self): response_interceptor_wrapper = self.sb.global_response_interceptor() with self.assertRaises(SkillBuilderException) as exc: response_interceptor_wrapper(process_func=None) assert "process_func input parameter should be callable" in str( exc.exception), ( "Global Response Interceptor Decorator accepted invalid " "process_func parameter") def test_global_response_interceptor_decorator_on_valid_process_func(self): def test_process(input, response): return "something" self.sb.global_response_interceptor()(process_func=test_process) actual_global_response_interceptor = self.sb.global_response_interceptors[ 0] assert actual_global_response_interceptor.__class__.__name__ == "ResponseInterceptorTestProcess" assert actual_global_response_interceptor.process(None, None) == "something"
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")
@sb.exception_handler(can_handle_func=lambda i, e: True) def all_exception_handler(handler_input, exception): # type: (HandlerInput, Exception) -> Response # Log the exception in CloudWatch Logs print(exception) speech = "Sorry, I didn't get it. Can you please say it again?" handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response app = Flask(__name__) skill_response = SkillAdapter( skill=sb.create(), skill_id="AMAZON SKILL ID GOES HERE", app=app) skill_response.register(app=app, route="/") @app.route("/") def invoke_skill(): return skill_response.dispatch_request() if __name__ == '__main__': app.run()
from intents.catch_all_exception_handler import CatchAllExceptionHandler from intents.first_order_intent_handler import FirstOrderIntentHandler from intents.second_order_intent_handler import SecondOrderIntentHandler from intents.third_order_intent_handler import ThirdOrderIntentHandler load_dotenv() sb = SkillBuilder() sb.add_request_handler(LaunchRequestHandler()) sb.add_request_handler(CancelOrStopIntentHandler()) sb.add_request_handler(SessionEndedRequestHandler()) sb.add_request_handler(HelpIntentHandler()) sb.add_request_handler(FirstOrderIntentHandler()) sb.add_request_handler(SecondOrderIntentHandler()) sb.add_request_handler(ThirdOrderIntentHandler()) sb.add_exception_handler(CatchAllExceptionHandler()) app = Flask(__name__) skill_response = SkillAdapter(skill=sb.create(), skill_id=os.getenv('SKILL_ID'), app=app) skill_response.register(app=app, route="/") if __name__ == '__main__': app.run(threaded=True)
else: speech_text = 'Passenger {} is not on the manifest.'.format(hostname) return handler_input.response_builder.speak(speech_text).response @skill_builder.request_handler(can_handle_func=is_request_type('SessionEndedRequest')) def session_ended_request_handler(handler_input): return handler_input.response_builder.response @skill_builder.global_request_interceptor() def request_logger(handler_input): app.logger.debug('Request received: {}'.format(handler_input.request_envelope.request)) @skill_builder.global_response_interceptor() def response_logger(handler_input, response): app.logger.debug('Response generated: {}'.format(response)) skill_response = SkillAdapter(skill=skill_builder.create(), skill_id=config['applicationId'], app=app) skill_response.register(app=app, route='/') if __name__ == '__main__': app.run(host = '0.0.0.0', debug = True)
from ask_sdk_core.skill_builder import SkillBuilder from ask_sdk_model import request_envelope from ask_sdk_model import context import json sb = SkillBuilder() skill_obj = sb.create() def requestBuilder(request_type, attributes=None, intent_name=None, slots=None, ingredient=None, dialog_state=None, userid="amzn1.ask.account.[unique-value-here]"): #input: userid, request type, session attributes session = {} session["new"] = True session["sessionId"] = "amzn1.echo-api.session.[unique-value-here]" if attributes == None: session["attributes"] = {} else: if ingredient == None: session["attributes"] = { "current_recipe": "{\"py/object\": \"recipe.recipe\", \"directions\": [], \"ingredients\": {\"py/set\": []}, \"title\": \"" + attributes + "\"}" } else:
.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() # Register all handlers, interceptors etc. sb.add_request_handler(LaunchRequestHandler()) sb.add_request_handler(MoveNorthIntentHandler()) #sb.add_request_handler(HelloWorldIntentHandler()) 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()) app = Flask(__name__) app.config['ASK_SDK_VERIFY_TIMESTAMP'] = False skill_response = SkillAdapter( skill=sb.create(), skill_id='amzn1.ask.skill.327b488d-bf14-476a-8456-d092972cd5b5', app=app) skill_response.register(app=app, route="/") if __name__ == '__main__': app.run()
return (handler_input.response_builder.speak(speak_output).ask( speak_output).response) # # Create a skill builder and register the handles # print("Creating a skill builder ...") skill_builder = SkillBuilder() skill_builder.add_request_handler(LaunchRequestHandler()) skill_builder.add_request_handler(MoveRobotIntentHandler()) skill_builder.add_request_handler(FallbackIntentHandler()) skill_builder.add_request_handler(SessionEndedRequestHandler()) skill_builder.add_exception_handler(CatchAllExceptionHandler()) skill_obj = skill_builder.create() # # Define the routes for Flask # @app.route("/alexa-webhook", methods=['POST']) def post(): """ Process the request as following : - Get the input request JSON - Deserialize it to Request Envelope - Verify the request was sent by Alexa - Invoke the skill - Return the serialized response """
""" # type: (HandlerInput, Exception) -> Response logger.error(exception, exc_info=True) return handler_input.response_builder.speak(ERROR_PROMPT).set_should_end_session(True).response # --- aws lambda lambda_handler = sb.lambda_handler() # --- flask from flask import Flask from flask_ask_sdk.skill_adapter import SkillAdapter app = Flask(__name__) skill_adapter = SkillAdapter(skill=sb.create(), skill_id='TEST', app=app) @app.route("/", methods=['POST']) def invoke_skill(): """ POST Methode, die den Skill als FLASK app startet. :return: Startet den Skill :rtype: dispatch_request """ return skill_adapter.dispatch_request() if __name__ == '__main__': app.run(debug=True)
# type: (HandlerInput, Exception) -> None print("Encountered following exception: {}".format(exception)) #to do: changer le texte speech = "il y a un problème" handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response # Handler to be provided in lambda console. lambda_handler = sb.lambda_handler() #deploy on Kermit app = Flask(__name__) skill_response = SkillAdapter( skill=sb.create(), skill_id = config.skill_id, app=app) @app.route("/",methods=['GET','POST']) def invoke_skill(): return skill_response.dispatch_request() #API base de données #GET collection @app.route("/databases/<db_name>/collections/<db_collection>", methods= ['GET']) def get_collection_api(db_name,db_collection): # API utilisant la connection créée dès le début du programme collection = functions.get_collection(client_bdd, db_name, db_collection) documents = collection.find() response = [] for document in documents: del document['_id']
@skill_builder.exception_handler(can_handle_func=lambda i, e: True) def all_exception_handler(handler_input, exception): # """Catch all exception handler, log exception and # respond with custom message. # """ # type: (HandlerInput, Exception) -> Response logger.error(exception, exc_info=True) speech = "Sorry, there was some problem. Please try again!!" handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response # skill_id="amzn1.ask.skill.e909e9d9-3ad7-4563-bbfe-ec0247ab3f7a" skill_adapter = SkillAdapter(skill=skill_builder.create(), skill_id=10, app=app) skill_adapter.register(app=app, route="/moveplan") @app.route('/heartbeat') def default_route(): """Default route to return a simple message""" return jsonify('hi! I am alive') if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
# the below code was taken from a freely-available tutorial online # 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() # Register all handlers, interceptors etc. sb.add_request_handler(LaunchRequestHandler()) sb.add_request_handler(MoveIntentHandler()) sb.add_request_handler(BuildIntentHandler()) #sb.add_request_handler(HelloWorldIntentHandler()) sb.add_request_handler(HelpIntentHandler()) sb.add_request_handler(CancelOrStopIntentHandler()) sb.add_request_handler(SessionEndedRequestHandler()) sb.add_request_handler(FallbackIntentHandler()) sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers sb.add_exception_handler(CatchAllExceptionHandler()) app = Flask(__name__) app.config['ASK_SDK_VERIFY_TIMESTAMP'] = False skill_response = SkillAdapter( skill=sb.create(), skill_id='amzn1.ask.skill.df7f27ea-302a-487c-852b-725e8e35460d', app=app) skill_response.register(app=app, route="/") if __name__ == '__main__': app.run()
return handler_input.response_builder.response from ask_sdk_core.dispatch_components import AbstractExceptionHandler class AllExceptionHandler(AbstractExceptionHandler): def can_handle(self, handler_input, exception): # type: (HandlerInput, Exception) -> bool print('hey005') return True def handle(self, handler_input, exception): # type: (HandlerInput, Exception) -> Response # Log the exception in CloudWatch Logs print(exception) speech = "Sorry, I didn't get it. Can you please say it again!!" handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response sb.add_request_handler(LaunchRequestHandler()) sb.add_request_handler(HelloWorldIntentHandler()) sb.add_request_handler(HelpIntentHandler()) sb.add_request_handler(CancelAndStopIntentHandler()) sb.add_request_handler(SessionEndedRequestHandler()) sb.add_exception_handler(AllExceptionHandler()) myskill001 = sb.create()
sb.add_request_handler(AskForCocktailIntentHandler()) sb.add_request_handler(CocktailWithIngredientIntentHandler()) sb.add_request_handler(NonAlcoholicCocktailIntentHandler()) sb.add_request_handler(GlassIntentHandler()) sb.add_request_handler(MeasureIntentHandler()) sb.add_request_handler(RandomCocktailIntentHandler()) sb.add_request_handler(IngredientDescriptionIntentHandler()) sb.add_request_handler(YesMoreInfoIntentHandler()) sb.add_request_handler(NoMoreInfoIntentHandler()) sb.add_request_handler(RepeatIntentHandler()) sb.add_request_handler(HelpIntentHandler()) sb.add_request_handler(CancelOrStopIntentHandler()) sb.add_request_handler(FallbackIntentHandler()) sb.add_request_handler(SessionEndedRequestHandler()) sb.add_exception_handler(CatchAllExceptionHandler()) sb.add_global_request_interceptor(RequestLogger()) sb.add_global_response_interceptor(ResponseLogger()) skill_adapter = SkillAdapter( skill=sb.create(), skill_id='TEST', app=app) @app.route("/", methods=['POST']) def invoke_skill(): return skill_adapter.dispatch_request() if __name__ == '__main__': app.run()
@sb.request_handler(can_handle_func=is_request_type("SessionEndedRequest")) def session_ended_request_handler(handler_input): #any cleanup logic goes here return handler_input.response_builder.response @sb.exception_handler(can_handle_func=lambda i, e: True) def all_exception_handler(handler_input, exception): # Log the exception print(exception) speech_text = "Sorry, I didn't get it. Can you please say it again?" return build_response(handler_input, speech_text, "Sleep Schedule", ask=True) skill_adapter = SkillAdapter( skill=sb.create(), skill_id="amzn1.ask.skill.b134fcc6-c7e1-47f6-a1ac-46b2216f665a", app=app) def build_response(input, text, card_title="", card_content=None, end=False, ask=False): """ Function to build responses """ if not card_content: card_content = text input.response_builder.speak(text) input.response_builder.set_card(SimpleCard(card_title, card_content)) input.response_builder.set_should_end_session(end) if ask: input.response_builder.ask(text) return input.response_builder.response @app.route("/")