Turning Our Hello-World Serverless Function into A Slack Dicebot
Modify app.py to use dicebot#
Open up the app.py
file, in the first_function
directory to modify the core lambda code.
Add imports to app.py#
First, we'll want to add two import statements to top of app.py
to support our bot. Add these lines at line 4, underneath the imports already in place.
import dicebot # used to import dicebot functionality
from urllib.parse import parse_qs # used to parse slack input
The dicebot
import allows us to handle dice rolling like we did in our interactive shell.
The line from urllib.parse import parse_qs
will give us access to the parse_qs
library from urllib.parse
. That function allows us to parse the slack slash command data from the default value of x-www-form-urlencoded
into a python dict.
Update code under lambda_handler function in app.py#
Next, we'll add some modifications to the lambda_handler
function in app.py
. We will remove all of the default code underneath the considerably huge default docstring, and replace it with the code below. Delete the get_message
function as well.
Ensure all code is properly indented throughout! Since this code is underneath the lambda_function
each line must have at least 4 spaces before any text.
dice_input = None
status_code = 500 # fallback value
result_output = {} # fallback
print(event) # ensure event input is logged
if "body" in event:
dice_input = event["body"]
try:
dice_query = parse_qs(event["body"])
print(dice_query) # log parsed message from slack
if "text" in dice_query:
dice_input = dice_query["text"][0] # The text field is an array
else:
dice_input = "" # default to empty string if missing
parsed_input = dicebot.parse_text(dice_input)
except Exception as e:
status_code = 400
result_output = {"text": str(e)}
else:
dice_results = dicebot.roll_dice(**parsed_input)
print(dice_results)
result_output = dicebot.format_slack_response(dice_results)
status_code = 200
finally:
return {
"statusCode": status_code,
"body": json.dumps(result_output)
}
Save these changes, and if you are tracking your project in a git repo, go ahead and commit now.
Most of that code is just there for error handling, which we will explain in-depth in chapter 2. The core bot logic works as follows:
Check that the key
body
was provided in theevent
that was passed to thelambda_handler
function by API Gateway.
This page is a preview of Create a Serverless Slackbot with AWS Lambda and Python