-->

How to upload files to slack using file.upload and

2020-05-28 18:42发布

问题:

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

回答1:

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)


回答2:

Base on the Slack API file.upload documentation What you need to have are:

  • Token : Authentication token bearing required scopes.
  • Channel ID : Channel to upload the file
  • File : File to upload

Here is the sample code. I am using WebClient method in @slack/web-api package to upload it in slack channel.

import { createReadStream } from 'fs';
import { WebClient } from '@slack/web-api';

const token = 'token'
const channelId = 'channelID'
const web = new WebClient(token);

const uploadFileToSlack = async () => {
   await web.files.upload({
     filename: 'fileName',
     file: createReadStream('path/file'),
     channels: channelId,
   });
}