Ayush Ujjwal
Ayush Ujjwal

Reputation: 169

How to upload files to Slack using Python

I want to upload files to Slack using Slack API and Python. I tried to use webhooks but it didn't help me send the file. I am able to send messages only but not files. Is there a way to achieve uploading the file?

Upvotes: 0

Views: 2697

Answers (3)

Avro Vulcan
Avro Vulcan

Reputation: 11

Uploading a file cannot be accomplished using a single files.upload API.

1.Upload the file using the files.upload API.

2.Retrieve the link to the uploaded file from the result.

3.After obtaining the link to the file, use chat.postMessage to send the uploaded file to the channel in text format.

Here is the completed code (python slack-sdk)

https://github.com/password123456/slack_api_example/blob/main/send_a_file_to_the_channel/main.py

Upvotes: 0

Jason
Jason

Reputation: 267

Files cannot be uploaded to Slack via a webhook and can only be done by utilizing the Web API. Specifically, the method that you'll want to look into is the files.upload method. See here for more information on how this works: https://api.slack.com/methods/files.upload.

Upvotes: 0

Ayush Ujjwal
Ayush Ujjwal

Reputation: 169

Finally, this worked for me.

Steps

  1. Create a Slack app. If you are not the admin you need to request the same.
  2. Add the permissions to read, write.
  3. Get the Authorization token from oauth & permissions
  4. Use the following snippet to upload the file.
        url = "https://slack.com/api/files.upload" 
        headers = {
            "Authorization":"Bearer xxxx",  ----> this is the token you receive from oauth & permissions. It generally starts with xox
        }

        payload = { "channels":"channelXYZ"} 

        file_upload = { 
        "file":("./hello-world.txt", 
        open("./hello-world.txt", 'rb'), 'text/plain') 
        } 

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

Upvotes: 1

Related Questions