Skip to content

Instantly share code, notes, and snippets.

@chrisgilmerproj
Created November 18, 2016 17:45
Show Gist options
  • Save chrisgilmerproj/ce285bf317c02e23231be6a3e6de5e04 to your computer and use it in GitHub Desktop.
Save chrisgilmerproj/ce285bf317c02e23231be6a3e6de5e04 to your computer and use it in GitHub Desktop.
Slack Python Incomming Webhook API
import re
import requests
DEFAULT_TIMEOUT = 10
class IncomingWebhook(object):
"""
https://api.slack.com/incoming-webhooks
https://api.slack.com/docs/message-formatting
"""
def __init__(self, url=None, timeout=DEFAULT_TIMEOUT):
self.url = url
self.timeout = timeout
def post(self, data):
"""
Posts message with payload formatted in accordance with
this documentation https://api.slack.com/incoming-webhooks
"""
if not self.url:
raise Exception('URL for incoming webhook is undefined')
resp = requests.post(self.url, json=data,
timeout=self.timeout)
if resp.ok:
return resp
else:
raise Exception(resp.text)
def message(self, text,
username=None,
icon_emoji=None,
icon_url=None,
channel=None):
data = {
"text": text,
}
if username:
data["username"] = username
if icon_emoji and icon_url:
raise Exception("Please provide either icon_emoji or icon_url, not both") # noqa
if icon_emoji:
if not re.match(r'^:[\w-]+:$', icon_emoji):
raise Exception("Please provide a valid emjoi")
data["icon_emoji"] = icon_emoji
if icon_url:
data["icon_url"] = icon_url
if channel:
data["channel"] = channel
return self.post(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment