Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python3
import os
import sys
import json
import requests
import argparse
import re
SLACK_WEBHOOK_URL = os.environ.get("SLACK_WEBHOOK_URL")
SLACK_DEFAULT_USER = os.environ.get("SLACK_DEFAULT_USER", "Python")
SLACK_DEFAULT_ICON = os.environ.get("SLACK_DEFAULT_ICON", "python")
def valid_channel(channel):
if channel[0] in ("@", "#"):
return channel
raise argparse.ArgumentTypeError(f"Invalid channel: {channel} does not begin with # or @.")
def valid_icon(icon):
if icon[0] != ":":
icon = f":{icon}"
if icon[-1] != ":":
icon = f"{icon}:"
return icon
def valid_colour(colour):
named_colours = [
"good",
"warning",
"danger",
]
if colour in named_colours or re.match(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", colour):
return colour
raise argparse.ArgumentTypeError(f"Invalid colour: {colour}")
parser = argparse.ArgumentParser(description="Send a slack message.")
parser.add_argument(
'-c', '--channel',
required=True,
type=valid_channel,
help="Channel to post to. Must begin with # or @."
)
parser.add_argument(
'-u', '--username',
default=SLACK_DEFAULT_USER,
help="Username to post as."
)
parser.add_argument(
'-m', '--message',
default=None,
help="Message to send."
)
parser.add_argument(
'-i', '--icon_emoji',
default=SLACK_DEFAULT_ICON,
type=valid_icon,
help="Emoji to use as icon."
)
parser.add_argument(
'--colour',
default=None,
type=valid_colour,
help="Post message as a block with a coloured left border."
)
args = parser.parse_args()
def post_json(url, payload):
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(payload))
return response
def post_to_slack(channel, username, message, icon_emoji, colour=None):
headers = {
'Content-Type': 'application/json'
}
if (args.colour):
payload = json.dumps({
'channel': channel,
'username': username,
'icon_emoji': icon_emoji,
"attachments": [
{
"text": message.replace('\\n', '\n'),
"color": args.colour,
"mrkdwn_in": ["text"]
}
]
})
else:
payload = json.dumps({
'channel': channel,
'username': username,
'text': message.replace('\\n', '\n'),
'icon_emoji': icon_emoji,
})
response = requests.post(
SLACK_WEBHOOK_URL,
data=payload,
headers=headers
)
return response
if __name__ == '__main__':
if not SLACK_WEBHOOK_URL:
print('ERROR: SLACK_WEBHOOK_URL is not defined.')
sys.exit(1)
if not args.message:
args.message = "".join(sys.stdin.readlines())
response = post_to_slack(
channel=args.channel,
username=args.username,
message=args.message,
icon_emoji=args.icon_emoji,
colour=args.colour
)
if response:
sys.exit(0)
else:
sys.exit(1)
@Setsuneh

This comment has been minimized.

Copy link

@Setsuneh Setsuneh commented Jun 3, 2020

Hi, thank you for this tip ! However I have one error after adding code:

SLACK_WEBHOOK_URL = os.environ.get("https://hooks.slack.com/services/XXXX")
SLACK_DEFAULT_USER = os.environ.get("Test", "Python")
SLACK_DEFAULT_ICON = os.environ.get("SLACK_DEFAULT_ICON", "python")
ERROR: SLACK_WEBHOOK_URL is not defined.

Have you got an idea ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment