Building a Serverless Alerting Chatbot with AWS Lex
In this live AWS learning environment, you will go through all the required steps to create a serverless alerting chatbot that can integrate with Slack. Throughout this activity, you will create multiple Lambda functions, design and create the bot framework in Lex, publish the bot, and integrate it with a Slack account. When completed, you will have an understanding of how AWS serverless technologies can be utilized to design, develop, and deploy applications.
Building a Serverless Alerting Chatbot with AWS Lex
In this live AWS learning environment, we will be creating a serverless alerting chatbot that can integrate with Slack and send both email and text message alerts. We will create two Lambda functions, design and create the bot framework in Lex, publish the bot, and integrate it with a Slack account.
Using Your Own our Our AWS Environment?
While either environment will allow you to learn how to create a bot, the question is do you want to keep the bot after you have finished. If you decide to create a bot on the Linux Academy environment, then the bot will disappear after you finish the lab. If you want to keep the bot for later use, then we suggest using your own environment to make the bot.
Before we Begin
Before we can get started, we need to go to GitHub. The documents that appear will be used throughout the lab. We can either download them or have them open in a separate tab; do whichever is easiest for your work environment.
With our GitHub documents ready, we need to sign into our AWS instance (or your own, depending on which you have decided to use) using the username and password provided. Once logged in, go to the Services dropdown, then under the Compute section, select Lambda.
Creating Lambda Function - Validation
In the Lambda section, we will be creating two functions. One to act as the validation for the information we provide, and the other as the fulfillment of all of the information our chatbot will collect.
Create a Function
To get started with our functions, we need to select Create a Function. On the Create Function page, select Author from scratch. For our first function, name it Validation, set the Runtime to Python 3.6, the Role to Choose from existing, and then select the LambdaLexRole. This role may look familiar as you have already created this in a previous lab, though this one has been set up for your use in this environment. Once everything is set up, select Create Function.
Go down to the Function Code section. Remember the information in GitHub? This is where we'll be using it. Open the Validation folder and select the validation_handler.py file. In here, copy the code. It is recommended to select the Raw button before copying the code, as the Raw page gives only the code and removes the chance of highlighting other information on the page.
Back on our Create Function page, in the Function code section, delete everything that is already in the code box and then paste the code we just copied. Once pasted, we need to change our name. Right-click the function, which will currently be called lambda_function.py, and rename it as validation_handler.py. Once changed, select Save.
Once saved, we will still be on the Create Function page. We want to add a second file to our Validation folder. Right-click under the folder in the Function code section, and select New File. Name this one messages.py.
Go back to GitHub and copy the information from the messages.py file there. As we did before, paste the information into the code block, making sure to remove any default code that appears.
Once all of the code is inserted, select Save.
The last change we will make to this function is the name present in the Handler section. We want to change it from lambda_function.lambda_handler to validation_handler.validate. This makes sure that our handler references the correct file and the correct event within that file's code.
Save one more time.
With that, our validation function is completed.
Creating Lambda Function - fulfillment
Now we need to create our second function. Head back to the Functions page and then select Create a Function. Once again, select Author from scratch. For our second function, we will be naming it fulfillment, our Runtime will be set to Python 3.6, the Role will be Choose from existing, and then select the LambdaLexRole. Once everything is set up, select Create Function.
Go down to the Function Code section. Again go to GitHub, though this time go to the *fulfillment folder, and select the fulfillment_handler.py file. In here, copy the code.
Back on our Create Function page, in the Function code section, delete everything that is already in the code box and then paste the code we just copied. Once pasted, we need to change our function's name. Right-click the function and rename it as fulfillment_handler.py. Feel free to select Save, though we will still be working on this page.
Again, we want to add a second file to our Fulfillment folder. Right-click under the folder in the Function code section, and select New File. Name this one alerts.py.
Go back to our GitHub tab and copy the information from the alerts.py file. As we did before, paste the information in the code block, making sure to remove any default code that appears.
Now, there are a few things in this code that we need to change. For instance, in the line that starts
VERIFIED_EMAIL, we need to insert a valid email address that we can access. The next is on the line starting with
PHONE_NUMBER. Here, enter your cell number so that you can receive a text message from this bot. Note that the +1 is the country code for the United States, and if you are not in the United States, you will need to enter your country code. Remember, if you are doing this in the Linux Academy environment, this bot will be deleted once you end the lab, so this information will not be saved. You must add at least your email to complete this lab.
The email and phone number we insert will receive alerts. As the default, all alerts will send to the phone number provided unless we insert a specific one for specific alerts, the same with the email. If you are doing this in your own environment, and want to test this function, insert other emails that you have access to for the Yellow, Orange, and Red alerts along with a second phone number if you would like.
The last thing we need to change for this function is the name in the Handler section. We want to change it from lambda_function.lambda_handler to fulfillment_handler.handler. This makes sure that our handler references the correct file —fulfullment_handler.py— and the correct event —Handler— within that file's code.
Once all of the code is inserted, and the Handler has been updated, select Save.
Creating Our Lex Bot
With our functions created, we can now create our actual bot. To get started, we need to head to the Amazon Lex page. To do so, use the Services drop-down and look under Machine Learning. From the list, select Amazon Lex. On the Amazon Lex page, select Get Started, as we have no information here yet.
On the page that appears, select Custom Bot. The other options are sample bots.
Set up Our Bot
In the box for Bot name, enter AlertBot. Our Output voice needs to be set to None. This is only a text-based application since we are only having the bot reply by text. For the session timeout, select 5 if using the Linux Academy instance, or select another time for yourself. By default, we will be given an IAM role; if you are doing this on your own account, make sure you have permissions to this role. Lastly, we can select No for the COPPA if using the Linux Academy instance. If you are using your own instance, please read about COPPA with the link provided by the page and see if you need to select Yes or No for your personal bot. Once finished, select Create.
With our bot base created, we now need to make our Bot's intent.
Select Create Intent and then Create intent again from the options that appear. In the text box, name the new intent AlertTeam and then select Add. It appears under our Intents section on the page.
On this page, there are a few things we need to fill out. The first is for the Sample utterances. These utterances are possible things a user may input to trigger our bots alert. For our utterances, we will enter the following:
- Alert the team
- I want to alert the team
- Send an alert
Feel free to add more than just these if you are creating your own bot.
Create a Slot
Slots are the next item we need to create. While we could use one of the pre-made example slots, we will be making ours from scratch. To do so, select the Add button, which looks like a plus sign inside of a circle, that is located in the left-side menu bar next to Slot types. Select the Create slot type option out of the options that appear.
For the Slot type name, enter AlertLevel. As you can guess, this is where we will set up the values for the Yellow, Orange, and Red alerts that our Verification and Fulfillment code references. To add them —Yellow, Orange, Red, and Help— type in the value and then hit Enter on your keyboard or click the Add button. We also want to select Restrict to Slot values and Synonyms. The reason we want to do this is because we only want our bot to respond to the values we've entered or any synonyms that we attach to them. For instance, we could use amarillo, the Spanish term for yellow, for our Yellow synonym if we knew both English and Spanish speakers were going to use the bot. Once we have everything set up, select Add slot to intent.
Now, go to the Slots drop-down. Since we selected Add slot to intent, a slot has been added to our AlertLevel type. Name this slot AlertLevel as well. We need to name it this because in the code we entered earlier to our functions, the slot it will be searching for will be AlertLevel, and to have the code run correctly, the names need to match up. Also, something to remember; the Slot is the value we're trying to collect while the Slot type is the information we are pulling for that value.
Now, for this slot, in the Prompt section, we need to ask the user a question. This question needs to reflect what information the user needs to input. For this bot, that would be What level of alert should we use?, which lets them know they need to insert Yellow, Orange, Red, or Help.
Now, at the bottom of the page, select Save intent and then select Build. A second box will appear to confirm that we want to build; select Build again to confirm.
With our bot built, we can use the Test Bot chat that appears. For now, enter in Hello. The bot will respond with "Sorry, can you please repeat that?". This is because Hello is not one of the terms we taught our bot.
Now, we don't want our bot to say "Sorry, can you please repeat that?". To change the response, select Error Handling from the left menu bar. In here, you will see that "Sorry, can you please repeat that?" is a Clarification prompt that was automatically set. Go ahead and delete it and instead enter Please say 'Alert the team' if you want to send an alert.for our Bot's response. Note that we must use single quotes for the prompt as AWS doesn't currently support double quotes. All other defaults are fine as they are.
Save this before rebuild the bot using the Build button.
Initialize a Code Hook
Now when we type in Hello into our bot, we get the message "Please say 'Alert the team' if you want to send an alert." which is what we want. The issue is that if we enter something besides an alert level, we will only get the Prompt we entered for our slot, which is "What alert level should we use?". We want to give our users more information than that.
To do so, we need to initialize and validate a code hook from our lambda function. To do this, under Lambda initialization and validation, select the checkbox for Initialization and validate code hook. From the drop-down that appears, select validation and then permit its use by clicking Ok on the pop-up that appears. This is the lambda function we created earlier. Once we set this up, select Save intent and then Build.
Once built out, enter Hello to get our "Alert the team" message. Enter Alert the team. This time, we get back "The alerts are Red, Orange, and Yellow. You can also say 'help'". Now, let's enter a random command that is not Yellow, Orange, Red, or Help. The bot will again return the sentence "The alerts are Red, Orange, and Yellow. You can also say 'help'".
Note that if you wait longer than five minutes to respond, the session will begin again, as that is what we set our timeout as.
Now, let's go ahead and enter help. A message appears explaining the three alerts. This is the detailed message from the messages.py file we created in our Lambda function.
Type something random again to get our alert. Once we get our alerts message, enter 'Red'. As of right now, nothing is happening. That is because we have not set up our Fulfillment section.
Select the Fulfillment drop-down. Here, select ASWS Lambda function and then from the drop-down, select fulfillment. Once finished, select Save Intent and then Build.
Once again, enter Hello, Alert the team, and then one of our alerts. But what's this? We have an error. Why is this?
Well, if we go to our Lambda Management Console in a new tab, and review our fulfillment function, we can find out. To get there, go to Lambda and then select the fulfillment function. Select the Monitor tab. Here, we see there is an invocation error. Select Jump to logs, and from the list, find the error message.
It looks like we forgot to verify our email. Whoops.
Verify an Email
To verify an email, and remove the error, open a new tab and go to the Services drop-down, and then under Customer Engagement, select Simple Email Service. From the left menu bar, select Email Addresses. Select Verify a new email address. In this box, enter the email we entered at the beginning of the lab. Make sure it is exactly the same! The best way to do this is to go into the file and copy the email from it and paste it into the box. Once we've entered the email, select Verify This Email Address. A box appears telling us an email has been sent for verification. Close this box, and in a new tab, go to your email.
An email from AWS will appear in your inbox. Once it does, click on the link it provides to confirm your email. Once it is verified, go back to the AWS console. Refresh the Email Addresses page. Our e-mail now has the Status of verified.
Final Bot Test
Head back to the tab with our Test Bot chat. Once again, enter Hello, Alert the team, and then Red. We receive a new e-mail about the red alert. We will also receive a text message. If one did not send, check the phone numbered that was entered in our Fulfillment Lambda Function.
Great, we now have a working bot. One more step and we'll be able to use it with Slack!
Publishing and Integrating our Lex Bot
Now that everything is ready to go, select Publish. We need to create an alias for this version of our bot. If you are creating it in your own instance, then we suggest using a number for versioning, though if you're working in Linux Academy Environment, we'll be using Prod. Once we've entered an alias, select Publish.
Once the bot finishes publishing, we need to set up a channel. We can either select the Go to channels button on the box that appears or, if we accidentally closed this box, we can also go to the Channels tab.
Setting up Slack
From the left menu bar, select Slack. Now, there is a chance that the steps shown here may become out of date for this part, and for that reason, we highly advise having the AWS documentation on integrating a Lex Bot with Slack open. Click here to open the documentation for Integrating an Amazon Lex Bot with Slack.
Now, if you don't already have Slack, you will need to create a new workspace. Once you have one, we can continue.
With your workspace open, click on the workspace name at the top of the Slack client. A drop-down appears. Select Workspace Setting —it may be nested under Administration— and then go to API. Here, select Start Building. Fill out the information asked for on the Create a Slack App page. For those using Linux Acadamy's instance, make the App Name Team Alerter and set the Development Slack Workspace to whatever it is you named your workspace. In our video, it is named laslackbot. Once this is ready, select Create App.
Creating a Bot User
A new menu appears. From it select Bot Users and then Add a bot user. Let's name this one team_alerter for both the Display name and Default username. We also want to set Always Show my Bot as Online to On. When finished, click Add Bot User.
Now, select Interactive Components, and then Enable Interactive Components. For the Request URL, enter https://slack.com. We don't need to add anything to the Options Load URL (for Message Menus). Then, select Enable Interactive Components.
Finally, select Basic information. Here, we need to copy all of the information under the App Credentials section.
With this information, go back to our tab that has our AWS console.
Set up the Channel for AWS
Now that we have all the information, we can set up the channel. First, set the Channel name to AlertSlack, and the Channel Description to Sending Alerts Via Slack. For Alias, select the one we created, Prod. For the rest, past in the information from the Basic Information section from our Slack tab. Once filled out, select Activate.
Callback URLs appear at the bottom of the page, which we will be using shortly.
Setting up OAuth and Permissions
Head back to our Slack API page. Here, select OAuth & Permissions. Click on Add a new Redirect URL and then enter the OAuth URL we were given in AWS, then selectAdd, then Save URLs.
Go down to Scopes. It is time to set our permissions. We need to search and add the chat:write:bot permission and the team:read permission. Save changes after these are added.
Select Interactive Components from the sidebar. In here, replace our Request URL with the Postback URL that AWS gave us. Save the changes.
Now, we need to select Events subscription. Turn it to On. Past in the Postback URL for the Request URL. Select Add Bot User Event. From the list that appears, select message.im event. Save the changes.
Finally, we can attach our bot! From the left menu, select Manage Distribution. Here, we will need to select the Add to Slack button. We must then Authorize the bot.
Once authorized, go to the slack workspace. We will now see our team_alerter bot under the Apps section. Click on the bot and say Hello. The bot will react the same as it did in the AWS console. Test out the functionality by using help, a random term, and then the Red alert level.
You will receive a text message and an email, letting you know that the bot was created and attached correctly.
Now that we have completed the lab, we have an understanding of how AWS serverless technologies can be utilized to design, develop, and deploy applications. You can now set up validation and fulfillment requirements for a bot, create the actual bot, test the bot, and then connect it to slack. Congratulations on completing this lab! Feel free to keep testing with the bot in the Linux Academy environment until the lab testing period ends.