How to run my Alexa skill build Python code into aws Lambda?

0

Hello Experts,

Greetings!!

Back story: I have been learning Alexa skill building coding and I have been succeeded also. Then I decided I will write boto3 code to get ec2 programs run in backend for Alexa.

What I have tried till now:

  • Have created boto3 program on my local VScode for ec2 getting my ec2 servers and its working successfully.
  • Have run same program from Lambda aws also, thanks to this forum my previous question's answer helped there.
  • Have changed my Lambda function which is integrated with my Alexa skill program(through Alexa kit is added into the Lambda function and its arn is added to END points in Alexa)

Issue I am facing right now: Following is my program:

# -*- coding: utf-8 -*-

# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python.
# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
# session persistence, api calls, and more.
# This sample is built using the handler classes approach in skill builder.
import logging
import ask_sdk_core.utils as ask_utils
import boto3
import os
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.handler_input import HandlerInput

from ask_sdk_model import Response

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

# print("Helooooooooooooooo")
logger.info('Balle Balle Balle Balle!!!!')

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

        return ask_utils.is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("I am in first function launch one here.....")
        print("I am in first function launch one here.....")
        speak_output = "heeeeeeeeeeeey this is singh here......?"

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

class GetEC2Info(AbstractRequestHandler):
    """Handler for Skill Launch."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        logger.info("I am in region function here 1st.....")

        return ask_utils.is_intent_name("getmyallecsevers")(handler_input)
    # os.environ['AWS_ACCESS_KEY_ID'] = 'id'
    # os.environ['AWS_SECRET_ACCESS_KEY'] = 'key'

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        regions=['ap-northeast-1','ap-northeast-2','ap-south-1','ap-southeast-1','ap-southeast-2','ca-central-1','eu-central-1','eu-north-1','eu-west-1','eu-west-2','eu-west-3','sa-east-1','us-east-1','us-east-2','us-west-1','us-west-2'] 
        logger.info("I am in region function here 2nd.....")
        for region_name in regions:
            print("I am in region loop here....")
            # print(f'region_name: {region_name}')
            session = boto3.Session(
              aws_access_key_id='---------',
              aws_secret_access_key='-----------'
            )
            session = boto3.Session()
            ec2 = session.client('ec2')
            print("ec2 value here is")
            print(ec2)
            ec2= boto3.resource('ec2', region_name=region_name)
            instances= ec2.meta.client.describe_instances()
            print("????????????")
            print(instances)
            for instance in instances['Reservations']:
                id = instance['Instances'][0]['InstanceId']
                if(id):
                    instance_state = instance['Instances'][0]['State']['Name']
                    ##print("Instance id of region " + str(region_name) + " is:" + str(id) + ", its state is: " + str(instance_state))
                    out += "Instance id of region " + str(region_name) + " is:" + str(id) + ", its state is: " + str(instance_state)
        speak_output = "output from Ravinder Singh" ##+ str(out)

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


class HelloWorldIntentHandler(AbstractRequestHandler):
    """Handler for Hello World Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        print("I am in helloooooo world........")
        return ask_utils.is_intent_name("HelloWorldIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "Hello World!"

        return (
            handler_input.response_builder
                .speak(speak_output)
                # .ask("add a reprompt if you want to keep the session open for the user to respond")
                .response
        )


class HelpIntentHandler(AbstractRequestHandler):
    """Handler for Help Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "You can say hello to me! How can I help?"

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


class CancelOrStopIntentHandler(AbstractRequestHandler):
    """Single handler for Cancel and Stop Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
                ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "Goodbye!"

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

class FallbackIntentHandler(AbstractRequestHandler):
    """Single handler for Fallback Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In FallbackIntentHandler")
        speech = "Hmm, I'm not sure. You can say Hello or Help. What would you like to do?"
        reprompt = "I didn't catch that. What can I help you with?"

        return handler_input.response_builder.speak(speech).ask(reprompt).response

class SessionEndedRequestHandler(AbstractRequestHandler):
    """Handler for Session End."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return ask_utils.is_request_type("SessionEndedRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # Any cleanup logic goes here.

        return handler_input.response_builder.response


class IntentReflectorHandler(AbstractRequestHandler):
    """The intent reflector is used for interaction model testing and debugging.
    It will simply repeat the intent the user said. You can create custom handlers
    for your intents by defining them above, then also adding them to the request
    handler chain below.
    """
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return ask_utils.is_request_type("IntentRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        intent_name = ask_utils.get_intent_name(handler_input)
        speak_output = "You just triggered " + intent_name + "."

        return (
            handler_input.response_builder
                .speak(speak_output)
                # .ask("add a reprompt if you want to keep the session open for the user to respond")
                .response
        )


class CatchAllExceptionHandler(AbstractExceptionHandler):
    """Generic error handling to capture any syntax or routing errors. If you receive an error
    stating the request handler chain is not found, you have not implemented a handler for
    the intent being invoked or included it in the skill builder below.
    """
    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(GetEC2Info())
sb.add_request_handler(HelloWorldIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
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 = skill_builder.lambda_handler()
def lambda_handler(event, context):
    return lambda_handler(event, context)

Where lambda_handler line and its function I added because of Alexa was failing to response([ERROR] Runtime.HandlerNotFound: Handler 'lambda_handler' missing on module 'lambda_function' Traceback (most recent call last):). Here is the Lambda structure for same: Enter image description here

Could experts please do help me here, will be grateful to you.

asked 10 months ago502 views
1 Answer
1

I am getting an error that "lambda_handler" is not found in lambda_function.py. Is lambda_function.py deployed correctly?
Review the Lambda handler settings.
https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html

profile picture
EXPERT
answered 10 months ago
  • Thank you Riku for your answer but to which handler I should point out? I have few of them.

  • Which is the handler of lambda_function.py? I assume this is the handler because there is a lambda_handler in the last line. By the way, is the file name lambda_function.py correct? Also, can you share what the directory structure looks like?

  • Hello Riku, thanks for your response. This is Alexa SDK code where I need to put/write my code which connects to boto3/ec2. Names and all are out of the box only. I only created classed and my ec2 code into it. Its directory structure I will update in question.

  • Try changing the handler settings as follows.

    lambda/lambda_function.lambda_handler
    
  • Hello Riku, when I done with changes I am getting [ERROR] Runtime.ImportModuleError: Unable to import module 'lambda/lambda_function': No module named 'ask_sdk_core' Traceback (most recent call last): error in logs.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions