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 api_call = sc.api_call( "chat.postMessage", channel="YOUR CHANNEL ID HERE", text="Hello World :wave:" )