Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files to slack using file.upload and requests

I've been searching a lot and I haven't found an answer to what I'm looking for.

I'm trying to upload a file from /tmp to slack using python requests but I keep getting {"ok":false,"error":"no_file_data"} returned.

file={'file':('/tmp/myfile.pdf', open('/tmp/myfile.pdf', 'rb'), 'pdf')}
payload={
        "filename":"myfile.pdf", 
        "token":token, 
        "channels":['#random'], 
        "media":file
        }

r=requests.post("https://slack.com/api/files.upload", params=payload)

Mostly trying to follow the advice posted here

like image 429
arshbot Avatar asked Apr 18 '17 06:04

arshbot


People also ask

Why can't I attach files in Slack?

If you can't upload anything to Slack, try adding fewer files and update the app. If you use Slack from your web browser, clear the cache, update your browser and disable your extensions. Additionally, disable your antivirus and firewall and check if that helps.

Can you store documents in Slack?

When you upload a file to a channel or direct message, it will be stored in Slack. All PDFs, documents, images, screenshots, and audio and video files uploaded to a channel or direct message count towards the file storage limit.


1 Answers

Sending files through http requires a bit more extra work than sending other data. You have to set content type and fetch the file and all that, so you can't just include it in the payload parameter in requests.

You have to give your file information to the files parameter of the .post method so that it can add all the file transfer information to the request.

my_file = {
  'file' : ('/tmp/myfile.pdf', open('/tmp/myfile.pdf', 'rb'), 'pdf')
}

payload={
  "filename":"myfile.pdf", 
  "token":token, 
  "channels":['#random'], 
}

r = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)
like image 136
Caleb Lewis Avatar answered Sep 17 '22 19:09

Caleb Lewis