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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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
Thanks, Jeroen. I didn’t know it now requires an additional server configuration. Last time I checked the script(the Aug, here https://heejune.me/2018/08/01/crashdump-analysis-automation-using-slackbot-python-cdb-from-windows/) it didn’t exist so it might be added recently. Glad it helped.