DIY ChatBot: Run your Python Scripts as Slack Commands [Chatops]

Yogesh Ingale
3 min readMar 2, 2019

--

Have a python script for boring and repetitive tasks but not sure how everyone can use it? then this article is for you!

Slack commands for repetitive and boring tasks is what your team needs.

You can achieve this using AWS chalice framework.

AWS Chalice allows you to quickly create and deploy applications that use Amazon API Gateway and AWS Lambda.

$ pip install chalice
$ chalice new-project helloworld && cd helloworld
$ cat app.py
from chalice import Chaliceapp = Chalice(app_name="helloworld")@app.route("/")
def index():
return {"hello": "world"}
$ chalice deploy
...
https://endpoint/dev
$ curl https://endpoint/api
{"hello": "world"}
$ chalice deploy

Up and running in less than 30 seconds.

My GitHub repo for this article has all the prerequisites and steps to get you started.

You just need to configure AWS access credentials, generate Slack API token and add your python functions in app.py and /chalicelib/workers.py. After deploying your app using $ chalice deploy, configure your slash commands with API gateways.

It might look too much but here is the step by step guide.

Master-Slave Lambda Integration:

Slack requires your command to respond within 3 seconds otherwise you will get a Timeout error. What if your python function requires more than 3 seconds to respond.

Don’t worry we got you covered with Master and Slave Lambda integration using SNS service.

Master lambda will respond within 3 seconds and will inform the user that it’s working on the request. On the backend using SNS, Master lambda will trigger Slave lambda with all the inputs to start the work. After completing the work Slave Lambda will directly send the message to Slack using Slack API token.

AWS chalice has some beautiful functions to tackle the above situations. Make sure to follow the instructions from GitHub repo.

Structure:

.
├── app.py
├── chalicelib
│ ├── __init__.py
│ └── helpers.py
├── requirements.txt

app.py : This file includes all your route information including Master-Slave integration. In our case route information is nothing but API URLs which we feed to Slack commands.

chalicelib/helpers.py : This is where you can add additional application modules. Your python functions go here.

Chatbot in Action:

Command 1: /dns-check-list facebook.com, fb.com

Response :

Command 2: /ssl-info-list google.com, www.facebook.com

Response :

Code for the above commands is present in my GitHub repository.

For more DIY Chatbots article Click Here.

--

--