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.
dicebot import allows us to handle dice rolling like we did in our interactive shell.
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.
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
bodywas provided in the
eventthat was passed to the
lambda_handlerfunction by API Gateway.