Linux Automation Tip: How to Send Messages from Python to Your Slack Channels
Slack is a hugely popular live group chat system. While a lot of my notifications now go to Discord, as I wrote about here, Slack is still more popular with development teams, and it is what we use in my day job. Being able to notify your team when something happens programmatically can be very useful, and helps cut down on inbox clutter. Let's see how you can easily do that in your own tools.
The first thing you will need to do is get an API key in /apps/manage/custom-integrations:
Next you need the Python module, Slack Client:
sudo python3 -m pip install slackclient
As our mission is to send messages to our Slack, we need to first discover the ID of the channel. We can simply list all the channels and their associated IDs with the following quick script:
import os
from slackclient import SlackClient
# get the api key from the environment variables
secret = os.environ["SECRET"]
# connect to the api and create client
sc = SlackClient(secret)
# set up the channel api call
# excluding archived channels
api_call = sc.api_call(
"channels.list",
exclude_archived=1
)
# get the list of channels
channels = api_call.get('channels')
# output the channels and their IDs
# formatted in nice columns for readability
print()
for channel in channels:
print("{} {}".format(channel.get('name').ljust(25), channel.get('id')))
Notice I am keeping my API key in an environment variable.
Another option would be to store it in a text file, and read it like so:
with open("/home/example/slack.api") as file:
secret = file.read()
Once you have the ID, copy and paste it into the following code to send a message:
from slackclient import SlackClient
# get the api key from the environment variables
secret = os.environ["SECRET"]
# connect to the api and create client
sc = SlackClient(secret)
# send a message to a specific channel
# send a message to a specific channel
api_call = sc.api_call(
"chat.postMessage",
channel="ABCDEFG",
text="Hello World :wave:"
)
Posted from my blog with SteemPress : https://makerhacks.com/python-slack/
My upvote is more because of the discord article you linked than the slack article considering I dont use slack. I nevwr considwred how useful this could be! This means i could theoretically set up my own server with different channels and send alerts to the channels based on where they came from?
Yep! 👍
Cool article! I've seen some people make cool altcoin arbitrage monitoring bots with the slack API. You can make something really powerful with Slack notifications.
This post, with over $50.00 in bidbot payouts, has received votes from the following:
minnowbooster payout in the amount of $77 USD.
For a total calculated bidbot upvote value in the amount of $77 USD.
This information is being presented in the interest of transparency on our platform @makerhacks and is by no means a judgement of your work.