Python stepUpChallenge

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.


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 ="", params=payload, files=my_file)

GitHub URL:

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:

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:
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!

Akhil Sharma

Akhil Sharma
DevOps Engineer, Horizontal Digital India
Azure Content Hero
Microsoft Certified: Azure DevOps Engineer Expert
Microsoft Certified: Azure Administrator Associate
Google Cloud Certified: Associate Cloud Engineer
Oracle Cloud Infrastructure Architect Associate
Oracle Cloud Infrastructure Foundations Associate
Oracle Cloud Infrastructure Cloud Operations Associate
Oracle Cloud Infrastructure Developer Associate
Oracle Autonomous Database Cloud Specialist
Aviatrix Certified Engineer - Multi-Cloud Network Associate
Lean Six Sigma White Belt Certified - v4.0
5+ Years of experience in DevOps
For more info, please read "About Me!"

Please subscribe for updates using the bell icon on your screen!
Back To Top
error: Content is protected !!
%d bloggers like this: