Alexa + AWS Lambda Hello World in Python

I recently began to fool around with integrating Amazon Alexa with my Home Assistant install in a custom manner. By default, you can set up an emulated Hue in the HA configuration which allows you to toggle lights, but I wanted to do more – which means I had to build my own custom Alexa skills.

It’s amazing to me, that after hours and hours of research, I was unable to find a single solid “Hello World” tutorial online. Sure, there are plenty of tutorials, but they’re all fairly complex, or contain loads of code or information that I didn’t need. When developing in unfamiliar territory, I usually like to start with a simple “Hello World”. Below is an AWS Lambda function that you can use to echo “Hello World” through your Alexa or Echo Dot.

[code language=”python”]
from __future__ import print_function

def build_response_payload( title, output, reprompt_text, should_end_session ):
return {
‘outputSpeech’: {
‘type’: ‘PlainText’,
‘text’: output
},
‘card’: {
‘type’: ‘Simple’,
‘title’: "alexaHelloWorld – " + title,
‘content’: "alexaHelloWorld – " + output
},
‘reprompt’: {
‘outputSpeech’: {
‘type’: ‘PlainText’,
‘text’: reprompt_text
}
},
‘shouldEndSession’: should_end_session
}

def build_response( session_attributes, speechlet_response ):
return {
‘version’: ‘1.0’,
‘sessionAttributes’: session_attributes,
‘response’: speechlet_response
}

def say_hello_world():
session_attributes = {}
card_title = "Hello World"
speech_output = "Hello World"
should_end_session = True
return build_response( session_attributes, build_response_payload( card_title, speech_output, speech_output, should_end_session ) )

def lambda_handler( event, context ):
return say_hello_world()
[/code]

Here are a few pointers to get you started on your journey:
– Paste this into the inline editor in new AWS Lambda function
– Select “Python 2.7” and set the handler to lambda_function.lambda_handler
– Create a custom role and use the default options
– Set up the Lambda function and the Alexa skill pretty much how every other tutorial on the web tells you to
– The “Test” button in AWS Lambda will report errors. You should instead test directly from Alexa Skills in the AWS Developer Console. This is a little bit unintuitive and I’m not sure why it is this way. But test attempts from Lambda DO fail every time for me. I’ll update if I figure out why.

Since I typically prefer JS over Python, I’m going to do up another Hello World tutorial in Lambda Node.js shortly, this is just what I happened to get working first. I hope you can make some use of it. Enjoy!

One response to “Alexa + AWS Lambda Hello World in Python”

  1. […] Here is the Javascript version of my earlier tutorial Hello World in AWS Lambda + Amazon Alexa: […]

Leave a Reply

Discover more from Rich Collier

Subscribe now to keep reading and get access to the full archive.

Continue reading