Skip to content

Instantly share code, notes, and snippets.

@tom-henderson
Created January 7, 2020 03:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tom-henderson/bf672f4121ba1acf03bc7458c58f4aa6 to your computer and use it in GitHub Desktop.
Save tom-henderson/bf672f4121ba1acf03bc7458c58f4aa6 to your computer and use it in GitHub Desktop.
#!/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
Copy link

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 ?

@c00k3
Copy link

c00k3 commented Feb 16, 2023

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 ?

Hey @Setsuneh - I replaced the line with a straight-up variable for the webhook (not as secure) and it worked

from: SLACK_WEBHOOK_URL = os.environ.get("https://hooks.slack.com/services/XXXX")

to: SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/XXXX'

@c00k3
Copy link

c00k3 commented Feb 16, 2023

Great solution to the developers making this a paid feature. Thanks for the script!

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