Send a Slack Message
Sending messages to Slack with Python is easy!
Sending messages to a Slack channel is a great option to be notified about events happening on your systems. If you’re still using email for notifications…please don’t, slack is much better suited at informing people than traditional methods. If you organize slack channels by topic, it allows people to subscribe to the channels they are interested in, and unsubscribe when they move on and are no longer on that project. Slack also allows you to forcibly notify all members of a channel which, If people have the mobile client configured, can result in an alert just like a text message.
The following script can be used as a command-line tool to send slack messages to any particular channel.
You will first need to obtain a Slack incoming Webhook URL. That URL is really just a "magic URL" that allows you to post to a particular channel via a POST request, no headers or authentication are needed. Obviously, you should protect it very carefully, using for instance the Python Encryption library. In this example, we'll use an environment variable named SLACK_WEBHOOK_URL, which is the entire URL provided by Slack including the protocol https://...
The code samples on this website are provided under the LGPL v3 license. By using this code you agree to the terms of this license agreement.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Sends a notification to a given Slack channel
'''
# I M P O R T S ###############################################################
from __future__ import print_function
# from future import standard_library
# standard_library.install_aliases()
# from builtins import input
import argparse
import requests
import json
import sys
import os
__author__ = "Videre Research, LLC"
# G L O B A L S ###############################################################
webhookURL = os.getenv('SLACK_WEBHOOK_URL', '')
# F U N C T I O N S ###########################################################
def main():
"""Main function."""
if os.getenv('SLACK_WEBHOOK_URL', '') == "":
print('Environment variable SLACK_WEBHOOK_URL not set')
sys.exit(1)
assert webhookURL.startswith('https://hooks.slack.com/services/')
parser = argparse.ArgumentParser()
parser.add_argument(
'-t', '--title', action='store',
required=True,
help='Title line of the Slack post (can contain markup).'
)
parser.add_argument(
'-b', '--body', action='store',
required=True,
help='Body of the Slack post (can NOT contain markup).'
)
parser.add_argument(
'-u', '--user', action='store',
default=':Slack-Bot:', required=False,
help='User Name to display with the post, default to: Slack-Bot.'
)
parser.add_argument(
'-i', '--icon', action='store',
default=':speaking_head_in_silhouette:', required=False,
help='Icon (built-in emoji) to display with the post, default to: :speaking_head_in_silhouette:.'
)
parser.add_argument(
'-c','--color', action='store',
default='36a64f', required=False,
help='Hex color code for the post content, default to: 36a64f.'
)
args = parser.parse_args()
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
data = {
"username": "SlackPost",
"icon_emoji": args.icon,
"text": args.title,
"attachments": [
{
"fallback": args.body,
"color": args.color,
"text": args.body
}
]
}
try:
r = requests.request(method='POST', url=webhookURL, data=json.dumps(data), headers=headers, timeout=25)
if r.status_code == 200:
response = r.content
print(response)
else:
print('Error:')
print(r.status_code)
print(r.headers)
print(r.text)
print(sys.exc_info()[:2])
sys.exit(1)
except Exception as e:
print("Error {0}".format(str(e)))
sys.exit(1)
sys.exit(0)
###############################################################################
if __name__ == "__main__":
main()
# E N D O F F I L E #######################################################
Using the command-line tool
As you can see by invoking the script with the '-h' parameter, the only two parameters that are required are the "-t" for the title of your slack post, and the "-b" for a body. You can specify any other parameters if you want or just change the default in the script itself.
Note that you can use '<!channel|channel>' in the body to alert all active users in that channel (equivalent to @channel). Please refrain from using @here if at all possible.
Happy slacking (figuratively of course), and please use responsibly!
python3 send_slack.py -h
usage: __main__.py [-h] -t TITLE -b BODY [-u USER] [-i ICON] [-c COLOR]
optional arguments:
-h, --help show this help message and exit
-t TITLE, --title TITLE
Title line of the Slack post (can contain markup).
-b BODY, --body BODY Body of the Slack post (can NOT contain markup).
-u USER, --user USER User Name to display with the post, default to: Slack-
Bot.
-i ICON, --icon ICON Icon (built-in emoji) to display with the post,
default to: :speaking_head_in_silhouette:.
-c COLOR, --color COLOR
Hex color code for the post content, default to:
36a64f.
Tagged with:
notification