How to upload a file from slack using SlackClient?

Slack provides an official python client module which you can easily work with.

It’s simple and easy to use. For example, sending a text line to a specific channel is simple enough to call through just one API – api_call(chat.postMessage, channel=channel, text=msg, attachments=attachment, as_user=True)

You can also upload a file to a channel. However, when I was searching some info how to achieve that at the first time, the answer described in the SlackClient’s Github issue was actually wrong. So I tested and added a snippet. Please check the issue page.

Anyway, I also shared the snippet at the public gist. The ‘upload_file’ method takes a long text as the ‘content’ param and upload it as a file. You’ll also upload a file directory from disk or memory if you modify it slightly.


from slackclient import SlackClient
class SlackBot(object):
'''
SlackBot:
'''
def __init__(self, logger, slackclient):
self.logger = logger or logging.getLogger(__name__)
self.slack_client = slackclient or SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
def send_message(self, msg, attachment=None, channel="#general"):
'''
Plain send text method
'''
try:
res = self.slack_client.api_call("chat.postMessage", channel=channel, text=msg, attachments=attachment, as_user=True)
if not res.get('ok'):
self.logger.error('error: {}', res.get('error'))
except:
self.logger.exception('send_message failed')
def upload_file(self, filename, content, channel):
'''
upload a long text as a file
'''
ret = self.slack_client.api_call("files.upload", filename=filename, channels=channel, file= io.BytesIO(str.encode(content)))
if not 'ok' in ret or not ret['ok']:
# error
self.logger.error('fileUpload failed %s', ret['error'])

Thanks,

Heejune

2 thoughts on “How to upload a file from slack using SlackClient?

  1. Thank you Heejune!

    This helped me a lot.
    Besides the explanation above, I also needed to set the correct scope in the app, so it would let the user accept to write files. To send messages AND to upload files. The following are needed within the App settings, which you can find in the configuration of your app at slack.com.
    Goto ‘Your apps’ -> Select your app -> Features -> OAuth & Permissions -> Select the following scopes:

    Send messages as user
    chat:write:user

    Upload and modify files as user
    files:write:user

    Cheers,
    Jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s