xv8
xv8

Reputation: 177

How to import a Python library into Alexa Skill

I am simply trying to import the random library into my Alexa Skill, but I'm getting "There was a problem with the requested skill's response" every time i try to use it in my lambda functions code (e.g. index = random.randrange(len(array)) ). Ive seen answers ranging from simply putting the library into your requirements.txt to using a zip file to do it. Nothing has worked and/or makes sense. Thanks for the help.

Upvotes: 0

Views: 760

Answers (1)

Greg Bulmash
Greg Bulmash

Reputation: 1957

The random library is part of the PSL. You just need to add import random at the top of your script with the other import statements. For non-PSL libraries, you should add them to the "requirements.txt" and then import them in the script, just like you'd do with Node and the "package.json" file.

Here's my edited version of the LaunchIntent from the default Python Hello World template in the Alexa Developer Console. The import random was added to the script after import logging up around line 8.

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
        rnum =  str(random.randint(0,9))
        speak_output = "Welcome, your random number is " + rnum

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

Because I'm combining the number with a string to produce a string, I have to cast the integer to a string, but that's about it.

Beyond that there's a "CloudWatch Logs" button at the top of the editor in the Alexa Developer Console. Click that and check your the latest log stream for the output of what error might be occurring.

For example, I don't write Python often and I'm so used to JavaScript's type coercion, I forgot to cast the random number to a string before adding it to a string. I know... bad habit. That error was clearly indicated in the CloudWatch logs. I fixed it and everything worked like a charm.

Upvotes: 0

Related Questions