Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting files to a chat through Slack API

I'm trying to deliver videos, through Slack API using Python's library slackclient.

I often use slack.api_call('chat.postMessage'...) and I am familiar with 'files.upload' but when I execute

slack = SlackClient(TOKEN)
slack.api_call('files.upload', file=open('video.mp4', 'rb')...)

the file is uploaded to the given channel, but is not posted as a message.

What I am trying to achieve is to create a message which I can send as a private message or to a channel that would look something like this

enter image description here

and maybe add some text above it if possible.

I've explored the Attachment section in the docs, but couldn't find anything related to files. If there is a way to not supply the file in binary format, but as a link that would also be ok (as long as it is displayed in an embedded fashion).

like image 236
bluesummers Avatar asked Aug 06 '17 10:08

bluesummers


2 Answers

How about this sample script? It uses io.BytesIO(f.read()) for the file. In order to use this, files:write:user has to be included in the scopes. About the text, you can import it using initial_comment. In my environment, attachments could not be used for files.upload. The API document is https://api.slack.com/methods/files.upload.

Script :

with open('./sample.mp4', 'rb') as f:
    slack.api_call(
        "files.upload",
        channels='#sample',
        filename='sample.mp4',
        title='sampletitle',
        initial_comment='sampletext',
        file=io.BytesIO(f.read())
    )

Result :

enter image description here

If I misunderstand your question, I'm sorry.

like image 171
Tanaike Avatar answered Sep 30 '22 21:09

Tanaike


I came across this question because I had the same issue - my file would upload and I would get a response, but the file would not be posted to the channel I had sent. It turned out to be a poor job by me of reading the Slack API documentation. I had used chat.postMessage many times and included a single 'channel' argument. Here is that API: https://api.slack.com/methods/chat.postMessage

The files.upload method it wants a comma separated list of channels in a 'channels' argument. See https://api.slack.com/methods/files.upload Once I changed from 'channel' to 'channels' and made sure to pass it as a list, I was successfully posting the image to the channel I wanted.

To the original question then, in your link to the code you used (https://ibb.co/hwH5hF) try changing channel='bla'to channels=['bla']

like image 25
Trashfire Avatar answered Sep 30 '22 21:09

Trashfire