Post File to Slack Using Python
akhilsharmascripting

Post File to Slack Using Python


Hey there! Today, I’m here to discuss one of the several ways we have to post a file to slack channel. We can write script for the same in a lot of languages like PowerShell, Python, etc. And today, I’ll be discussing this using Python.

Prerequisites?

Well, we don’t have much of the prerequisites for implementing this script but there are a few important and mandatory ones:

  • Access to Slack
  • Basic knowledge of Python (Incase you run into an issue and you have to debug. Mostly, you won’t require debugging this script ever! However, you never know what may happen when! So always keep the tools handy!)
  • And a file which you plan to post (yeah, I really wrote it :D)

How to start?

Well, now that you are prepared with all the prerequisites and are ready to start, let me share you the script first. (I like directly coming to the point!)

 my_file = {   'file' : (<pathToFile>, open(<pathToFile>, 'rb'), '<typeOfFile>') }

payload={   "filename":"<FileNameYouWishToShowInSlackMessage>.<ExtensionOfFile>",    "token":'<SlackToken>',    "channels":['#<SlackChannelName>'],  }
 
r = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file) 

GitHub URL: https://github.com/akhilvatts/PySlack/blob/master/PySlack-SendFile.py

Here, most of the parameters are self explanatory like pathToFile is bascially the physical path to file.
However, there’s one interesting parameter named, SlackToken. SlackToken is nothing but your Slack API Token generated to authenticate and uniquely identify you. Hence, you may consider this as very confidential and secret, so please don’t push this into some repo directly. Manage this as a secret!
You may consider learning more about this at: https://slack.dev/python-slackclient/auth.html

Update:
Slack recommends using Slack Apps instead of using API Tokens for posting messages using scripts. And I would soon be updating the PySlack repo with the latest code as well.
Github Repo: https://github.com/akhilvatts/PySlack
But don’t worry, your current and old code won’t stop working immediately.
In my next post, I shall be discussing ways to migrate these kind of apps or scripts to use Slack Apps. So, Stay Tuned!