Saturday 4 July 2020

Tutorial: Making Slack Apps with Python

I wrote this tutorial during Unity Hackweek 2020. I helped lead a group that focused on learning rather than producing (but to also hopefully create some small tools to help out the Documentation team!), and I created this to help the team get started with Slack apps. A few people in the group spent the week learning Python, and while I was looking for resources to share, I noticed that a lot of the tutorials available really over complicated the process! Thank you so much to Siobhan who edited this tutorial as she worked through it herself.

This tutorial covers: 

  • How to send a simple message to Slack
  • How to request API data from a service (such as Favro or Jira)
  • How to send that API data in a Slack message
This tutorial assumes at least a beginner-level understanding of writing Python scripts and working in the command line. Some knowledge of manipulating JSON will also be helpful for the later parts of this tutorial.

Part 1: Send a simple message to Slack

First, let’s learn how to send a simple message to Slack. To send messages and data to Slack, you need to use an HTTP POST request. An HTTP POST request is a method that asks a server to accept data. It carries this data in the body of the request message. 


To get set up, work through Slack's guide to Sending messages using Incoming Webhooks until you’ve completed step 4. You should now have a Slack App, and on the Incoming Webhooks page of your slack app you should see something like this:




Set up a webhook, and point it at a private test channel or your own slack user for now, while you test it.


You can copy these curl commands into your command line/terminal to run them and perform the action they represent. You can also translate them to Python and use Python’s Requests library to send POST requests. To use the Requests library, you need to install pip (if it is not already installed), and then open your command line terminal and type pip install requests.


This table demonstrates the curl command in the image above, and a Python translation. 


curl command
curl =X POST -H 'Content-type: application/json' --data '{"text:"Hello, World!"}'
YOUR_SLACK_WEBHOOK_URL_HERE
Python
import requests (put this line at the top of your python file)
slack_response = requests.post('YOUR_SLACK_WEBHOOK_URL_HERE', data='{"text":"Hello, World! I am posting from a Python script. Magic!"}', headers={'Content-type': 'application/json'})


In the translation, the curl command's -H parameter corresponds to headers in Python, and the --data parameter corresponds to data.


Run your Python script in the command line terminal. If everything is configured correctly, the message "I am posting from a Python script. Magic!" should appear in the target Slack channel. You did it!

Part 2: Get API data from a service and send it to Slack

Now that you know how to use Python to send a message to a Slack channel, let’s try to get some data from a service and send it in a Slack message. 

Part 2.1: Get API data from a service

To request data from a service's API, you need to send an HTTP GET request. An HTTP GET request is a method that requests data from a specified resource (in this case, the service API). 

For this tutorial, I use the Favro API as an example.


When you look at a service's API docs, you might see some examples in the form of CURL commands. CURL is a command line tool to transfer data to or from a server.




You can copy these curl commands into your command line/terminal to run them and perform the action they represent. You can also translate them to Python and use Python’s Requests library to send GET requests. This is useful if you want to do this repeatedly, or if you want to use the information you get from the output into another command.


This table demonstrates the curl command in the image above, and a Python translation. 


curl command
curl =X GET "https://favro.com/api/v1/users"
-H "'organizationId': YOUR_ORG_ID"
-u "user@example.com":"password"
Python
import requests (put this line at the top of your python file)
request = requests.get('https://favro.com/api/v1/users', headers={'organizationId': 'YOUR_ORG_ID', auth= ('user@example.com', 'password'))


In the translation, the curl command's -H parameter corresponds to headers in Python, and the -u parameter corresponds to auth.


NOTE: Don't put your Slack or service password in this file! Most API services let you generate a secret API key that you can revoke at any time. Use the API key in place of a password here.


Once you have completed this translation, you can print the output to check the HTTP Status Code that it returns. To do this, insert the following underneath your requests.get code:


print(r)


Run your file in the command line terminal. Usually, an HTTP Status Code of 200 means your code works as expected.

Part 2.2: Send API data in a Slack message



It is common for an API to return data in JSON format, but you can send any data back to Slack as long as you format it.


The Slack Bot Kit Builder is a really convenient way to design how your message will look and then use the JSON it generates (on the right).


I won’t go into to how to parse JSON using Python in this tutorial, but you can replace the “text” sections that you generated using the Block Kit Builder with the information you got from the API you're getting data from (in my case, Favro). Here’s an example:


JSON as a multi-line Python string
data_to_send = '''{
"blocks": [
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "%s",
"emoji": true
}
},
{
"type": "divider"
}
]
}''' % favro_card_name
Python
slack_response = requests.post('YOUR_SLACK_WEBHOOK_URL_HERE', data=data_to_send, headers={'Content-type': 'application/json'})


Sending a response like the above will send a Slack message that looks something like this;
And you're done! Hopefully now you have a better understanding of how to use Python to get data from one API and send it to Slack using Slack's API.

No comments:

Post a Comment