How to Build Slack Bot with Python

Mahesh Oruganti
6 min readMar 12, 2019

Bots are a useful way to interact with chat services such as Slack. If you have never built a bot before, this post provides an easy starter tutorial for combining the Slack API with Python to create your first bot. here I am going to explain an example of how to interact(run) Jenkins jobs from slack using slack bot.

What is Bot/slackbot:

  • Bots are handy little assistants that hang out in your app, wait for commands, and then find or create the things you need
  • A bot is a type of Slack App designed to interact with users via conversation.
  • A bot is the same as a regular app: it can access the same range of APIs and do all of the magical things that a Slack App can do.

What Do you Need to Build a Bot?

Ex: Slack(A place to type your text) , Bot(to read your text) , python server which interacts with Jenkins (to do something)

Tools We Need

I think most of the organizations have slack, jenkins to automate CI/CD processes.

Creating Custom Bot :

Create a Bot and Setup integration

Notes: Assuming you already installed slack. go to your slack settings and create custom bot. below is the screen shot for reference(there are many ways creating custom slack bot). add the bot name(ex: jenkins-bot)and click Add bot integration button and add all other below required details. keep note that Api token is confidential and don’t share it it anyone.we are going to use that API token value to connect slack API’s.

  • API Token : The library you are using will want an API token for your bot.(Be careful when sharing bot user tokens with applications. Do not publish bot user tokens in public code repositories.)
  • Customize Name: Choose the username for this bot.
  • Customize Icon: Change the icon used for this bot.
  • Full Name: You can choose to display your bot’s full name rather than its username.
  • What this bot does: Let others on your team know what this bot is used for (optional).
  • Channels: This bot is currently in the following channels.(please create one slack channel in your installed slack if you don’t have any)

Setting up Local Environment

Note: if you are on Mac, Linux, open terminal and go to your home directory or any working directory you like and run below commands.

virtualenv slcakbot
source slackbot/bin/activate
pip install slackclient

All the files and required code provided below, you can keep all methods in one file(slackbot.py) as well ( it’s up to you).

Download source code from gitHub

please download source code over here and make changes as per your needs. https://github.com/MaheshOruganti/Slackbot

  1. bot.py ( which is base class)

2) slackbot.py (create file and add all the below code into )

Slack API Methods used

SlackClient(token) :

The Slack Client makes API Calls to the Slack Web API as well as managing connections to the Real-time Messaging API via websocket

  • It also manages some of the Client state for Channels that the associated token (User or Bot) is associated with.

rtm_connect():

  • Connects to the RTM WebSocket

rtm_read():

  • Reads from the RTM WebSocket stream then calls self.process_changes(item) for each line in the returned data.
  • Multiple events may be returned, always returns a list [], which is empty if there are no incoming messages.

api_call(method, **kwargs): Call the Slack Web API

Ex: self.slack_client.api_call(“chat.postMessage”, channel=self.channel, text=message, as_user=True)

Notes:

1)please go through python documents , slack API docs to understand each imports used in this file.

2)I commented out Bot token here, please use your slack api token which you got when you create custom bot the above mentioned.

3) bot id you will get once you run the program..please update that later.

4) please make sure all lines of code added in this slackbot.py file.

3) user-info.py ( to get user info)

4. JenkinsJobCommands.py (this file has actual method to run/trigger jenkins job.)

Notes: here you need to get headers(authorization, jenkins-crumb ): construct it from your jenkins user credentials you are going to use for triggering your jobs. ask Devops people to get these details. you can also keep this method in slackbot.py and call it.

Search in google how to create authorization key using jenkins credentials(userID, password).

please post me if you don’t find.I can help on that.

example to build url for job with parameters:

url = “<jenkins job url path>/buildWithParameters" + \
“?PROJECT=” + self.projectName + “&ENV=” + self.env + “&DEVICE=” + device + “&TEST=” + self.test+ “”

1)parse chat data/slack command from slackbot and keep values in variables(self.projectName ,self.env ,self.test etc..).

2) send the variable values to jenkins job parameters.

Running slackbot:

Now that all of our code is in place we can run our SlackBot on the command line with the python slackbot.py command.

Important Notes:

Source code available

1.check the console logs, that slackbot started and up and running .

2. check your Bot(jenkins-bot) is active in your slack. if you dont’ see slackbot in your slack, please invite it into slack(just type @jenkins-bot and invite). you can also invite in to slack channels/groups.

3. Run the commands from the jenkins-bot. command should start with “jenkins” . you can change the command whatever you like but you need to update that in your slackbot.py

4. understand that what code is doing, and probably you need to handle/add logic that what command you need to pass to slackbot to run the jenkins job.

5. if your jenkins job expecting parameters (Ex: project name , type of device, type of tests) here is the commands I use from the slack , ( @jenkins-bot jenkins <test-project> <mobile> <SmokeTests>).

@jenkins-bot help

6. This slackbot can also use for handling multiple jenkins jobs, also can use different purposes (Ex: building projects from gitHub etc..) (not only handling jenkins jobs)

7. you can build and deploy this code on any environment where it runs as a server. but you need setup.py file(you can google it , how to create setup.py)

8. I did not explain that what each method perform separately, but all the methods has method descriptions. please read it understand.

I know this is crazy :) :) . but this type of bots useful to trigger jenkins jobs from your mobile if you have slack app installed(you don’t have to be in office/office network). I hope you guys understand . please try and understand the logic before making any changes. please also look for other posts online to build slack bots.

About Me:

This is Mahesh Oruganti working as an Automation QA Engineer at Dotdash(https://www.dotdash.com/) . Happy learning . Thanks.

--

--