Posting files to a chat through Slack API

Viewed 11603

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).

3 Answers

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']

This works for me:

import slack

client = slack.WebClient(token='xoxb-XXX')

with open('/path/to/attachment.jpeg', 'rb') as att:
    r = client.api_call("files.upload", files={
        'file': att,
    }, data={
        'channels': '#my_channel',
        'filename': 'downloaded_filename.jpeg',
        'title': 'Attachment\'s title',
        'initial_comment': 'Attachment\'s description',
    })
    assert r.status_code == 200
Related