Sending a file to a slack channel using API

For the past 3 years, I have been working with data-obsessed management. This management would want all the reporting to happen in one place with the most accessibility. Call it old school but some are really comfortable with excel files. As a data analyst, we always tend to move to a solution that would an additional (somewhat unnecessary) learning for the management. So I decided to send them these formant data report files over slack something that they had on their fingertips.

As per the API documentation of slack, you can send files easily using “files.upload” method. According to the documentation, the file can be sent using multipart/form-data or using POST var called content. For this article, we will be using multipart/form-data.

Setting up an app on slack

To create a new app on slack follow the following steps:

  • Goto slack create app page by clicking this link:
  • Click the “Create New App” button as shown in the above image.
  • Enter app name and select the slack workspace that you want to use this app for as in the image below:
  • Click the “Create App” button.
  • We will now add features for our app to access files feature. To do this click the “OAuth & Permission” button under features as shown in the image below:
  • Under scopes click the “Add an OAuth scope” button and search for “files:write:user” to add this scope as in the image below:
  • Click install to the workspace.
  • You will get OAuth access token which you will be for uploading app later on:

We are now done with setting up the slack app. It’s time to get our hands dirty with coding in PYTHON.

Coding API call in PYTHON

We will create a simple *.txt file and send it through PYTHON script as under:

import requests

# link to files.upload method
url = "https://slack.com/api/files.upload"

# this is where you add your query string. Please chage token value
querystring = {"token":"xxx-xxx-xxx-xxx"}

# this is where you define who do you want to send it to. Change channels to your target one
payload = {
"channels":"xxxxxxx"}

file_upload = {
    "file":("hello-world.txt", open("hello-world.txt", 'rb'), 'text/plain')
}
headers = {
    "Content-Type": "multipart/form-data",
    }

response = requests.post(url, data=payload,  params=querystring, files=file_upload)

You can change the file type to xls or csv however you like it by changing the text/plain parameter.