Linux Automation Tip: How to Send Messages from Python to Your Slack Channels

in #linux7 years ago (edited)

alt

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:

alt

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/

Sort:  

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?

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.

Loading...