WebEx teams bot scene and object detection
High Level Steps
- Create a bot in Webex teams and get the access token
- Create IAM role for our Lambda function with permissions to Rekognition and Cloudwatch logs
- Create a Lambda function for the bot - An API should be implicitly created for the Lambda function
- Register a Webhook in Webex Teams that points to API Gateway
- Become familiar with CloudWatch whilst debugging
Background
I have been wanting to create a Webex Teams bot for a while now. I had a look to see what examples I could find online and whilst there are multiple examples of Python based bots, most of them assume the use of a server which I wanted to avoid.
There were a couple of examples I came across that made use of Lambda however they were not immediately function, had poor documentation or made use of outdated APIs (ciscosparkapi instead of webexteamssdk).
So I thought I would take this opportunity to combine that with my passion for serverless applications and machine learning to create my own Webex Teams Machine Learning bot.
Services such as AWS Lambda let you run the bot code without provisioning or managing servers. You pay only for the compute time you consume and there is no charge when the code is not running.
And for the machine learning elements we have AWS Rekognition which is part of the Application Services section of the AWS ML Stack.
Rekognition makes high level APIs available which we can utilise to perform image analysis simply and easily. There is no need to gather and prepare training data, choose a model, train the mode, evaluate it, tune the hyper parameters before getting any predictions.
Although if we did want to build our own customer machine learning model then AWS also offers that capability through the Sage Maker managed service or even direct access to various Frameworks and Insfrascture such as TensorFlow, Keras, Caffe, PyTorch and more running GPU or CPU instances.
Introduction
This post will show you how to build a serverless scene and object detecting WebEx teams bot utilising AWS API Gateway, Lambda and Rekognition. The Lambda function is coded in Python.
Although this example uses the Rekognition Label Detection API to recognise object and scene labels, it could easily be modified to identify faces (including faces from custom collections), perform sentiment analysis or recognise celebrities.
At a high level, the following steps occur:
- A user sends a message to the Webex Teams Rekognition bot which includes an attached image
- Webex Teams sends a webhook request to API gateway address associated with the Rekognition Lambda function
- API gateway triggers the invocation of the Rekognition Lambda function which makes use of the Rekognition API to perform object and scene detection on the image
- A number of a number of labels are returned from the function and posted to the WebEx Teams space. The labels consist of an attribute and the confidence that it is correct in percentages
Register the WebEx Teams Bot
The first step is to head over to the WebEx Developer site and the Create a New App page. On there click on Create a Bot.
Make a note of the access token as you will need it later.
Create a IAM Role
- Within the IAM section of the AWS console, click on Roles and then Create a Role
- Select Lambda as the service that will use the role and then Next: Permissions
- Click on Create policy and then type Rekognition as the service
- Under Actions select Read and DetectLabels and DetectModerationLabels
- Back at the Service prompt type CloudWatch Logs and select CreateLogGroup,
CreateLogStream and PutLogEvents as the Actions. - Then Review Policy and give it a name such as mywebexfunctionpolicy
Create the lambda function
Now its time to create the lambda function that will perform the computations for our bot.
Within the lambda section of the AWS console click on Create function and Author from scratch. Give the function a name and select Python 2.7 as the runtime. Also create a new role with basic permissions for the execution role.
There should now be a new function. On the left hand side select API Gateway as the trigger. You want to create a new API with Security set to Open. Click Add and then Save.
Scroll down to the Execution role section and click on the View the WebexFunctionName role on the IAM Console.
On the Role Summary screen, click on Attach policies and search for the mywebexfunctionpolicy you created earlier. Attach that policy to your role. You should now have the mywebexfunctionpolicy and the AWSLambdaBasicExecutionRole policies attached.
Back on the Lambda screen, it is now time to upload the code which you can find on my GitHub page.
Start by cloning the repository to your local machine and navigating to the newly created directory.
1 | git clone https://github.com/cloud-commander/webex-teams-rekognition-lambda |
We will be making use of the webexteamssdk which is a non standard python library. In order for lambda to be able to make use of that library, we have to upload it to lambda.
This is achieved by installing the libraries to a local folder and packaging them up into a zip file which we then upload to lambda.
1 | pip install webexteamssdk -t . |
You should now have the packages that make up the webexteamssdk in your local folder which we will compress into a zip file with the below command.
1 | zip -r ../mylambdafunction.zip ./ -x \*.pyc |
The newly created zip file should be now uploaded to lambda. You will find the Upload a .zip file option under the code entry type drop box. Click Save for the file to be uploaded.
You should now see all the packages listed along with the lambda_function.py file that has our code.
An environment variable is required called WEBEX_TEAMS_ACCESS_TOKEN which should be populated with the Access Token value you noted down when creating the Bot.
Before we can try out our function, we need to register a webhook so Webex teams knows where to send the messages.
Create a Webex Teams Webhook
Webex Teams needs to know how it reach our Lambda function in order to invoke it. It does this by means of a webhook that points to API Gateway.
You can create the webhook by going to the Webex Developer site.
Make sure you are using the bot token in the bearer field which you will have noted down when registering the bot.
Enter a name for the webhook, the targetUrl should be the address of your API and enter all in the resource and event boxes which gives the webhook access to all features.
Testing our Bot
At this point, all being well, when you send a message to your bot from Webex teams it should respond to you.
But invariably something wont be quite right!
This is where CloudWatch is invaluable as it helps you debug your code so be sure to look through the logs.
Sometimes the code runs longer than expected, especially when processing a more complex image. Therefore it can help to set Lambda timer to 10 seconds to avoid time outs and give the code enough time to run.
Python Code
I thought I would also include a section on the Python code used to implement the lambda function for those interested.
1 | import json #used to handle JSON data |
Jumping to the bottom of the code we have the lambda handler which is the function lambda calls when invoked.
We have configured this to point to the main function in order to help us catch errors.
1 | # the lambda handler function |
The main function is where the majority of the work happens.
The main function loads the JSON data send from Webex teams into _message_data_.
You will note a number of commented out code that was used for debugging purposes. I have left that in case you find it useful. You can see the output from the print statements in CloudWatch logs.
Using the webex teams API we get the name of the sender based on the ID of the user who initiated the action in Webex teams.
We use that sender ID to confirm that the action was undertaken by a user and not the bot responding which would cause a loop.
1 | def main(event, context): |
We also get the roomId that the message was sent in so that we know which room to reply back to. We also need to find out what the current message ID is so that we can get the content and act accordingly.
1 | #help prompt for user |
In this section of code we check to see if the sure typed help in their message and if so to respond back with instruction on what they need to do.
1 |
|
Now we check to see if any files were attached to the message. As the URL of the file location is provided in JSON format, we need to strip out the unwanted characters first.
1 | if len(current_message.files) > 1: |
If the user tries to send more than one files we send out an error message otherwise we invoke the download_image function with the URL of the file in order to download it.
1 | def download_image(url): |
1 |
|
With the image downloaded, we now send a message to the Webex teams space preparing the user for the information then will see.
We then invoke the _find_labels_ function with an input the file we just downloaded.
1 | def find_labels(imageFile): |
The _find_labels_ function invokes the rekognition API to detect the labels in the provided image. We have set the threshold to a minimum 80% confidence and require a maximum of 10 labels for that image.
The function returns the Labels in the response object in JSON format.
1 | for label in find_labels(imageFile): |
When we invoke the find_labels function we iterate through it outputting the content to the Webex Space it was invoked from. As the data is in JSON format, we use to the json.dumps function to output it.
And that concluded the code. As you can see, it should be easy to modify it to make use of different Rekognition APIs. You can find examples of the other APIs here.