Site icon Hamza Afridi

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:

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.

Exit mobile version