Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Ennis committed Jul 14, 2016
0 parents commit 3c1be6b
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 0 deletions.
17 changes: 17 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from setuptools import setup

import slackhook as mod

setup(
name='slackhook',
version='0.1',
author='Ben Ennis',
author_email='[email protected]',
description='python script to interact with slack webhooks',
packages=[mod.__name__],
entry_points={
'console_scripts': [
'slackhook = slackhook.slackhook:main',
],
},
)
9 changes: 9 additions & 0 deletions slackhook/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env python


from .slackhook import Slack, main
from .logger import SlackLog


if __name__ == "__main__":
main()
62 changes: 62 additions & 0 deletions slackhook/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import sys
import logging

from slackhook import Slack


class SlackLog(logging.StreamHandler):
""" Custom logger to message slack
***Note***
All messages require a pipe ('|') character on which to split. Putting this
character at the end of the line seems to only result in a blank new line
following the message, useful for readability.
"""
def __init__(self, url, token, channel):
logging.Handler.__init__(self)
self.slack = Slack(url, token, channel)

def flush(self):
""" Since slack messages are atomic, pass when the buffer tries to clear
"""
pass

def emit(self, record):
try:
msg = self.format(record)
attach = None
if msg.find('|') != -1:
msg, attachment = msg.split('|')
attach = [{"text": attachment}]
self.slack.send_message(msg, attachments=attach)
except Exception:
self.handleError(record)


def new_excepthook(log):
def excepthook(type, value, traceback):
log.error("Uncaught exception", exc_info=(type, value, traceback))
return excepthook


def add_slacklog(url, token, channel):
log = logging.getLogger('slackhook')
log.setLevel(logging.DEBUG)
sys.excepthook = new_excepthook(log)

# create a console handler
ch = logging.StreamHandler()
ch_formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - '
'%(message)s')
ch.setFormatter(ch_formatter)

# create a slack handler
sh = SlackLog(url, token, channel)
sh_formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - '
'%(message)s')
sh.setFormatter(sh_formatter)

log.addHandler(ch)
log.addHandler(sh)
63 changes: 63 additions & 0 deletions slackhook/slackhook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/usr/bin/env python

import json
import argparse
from urllib.request import urlopen, Request


class Slack:
def __init__(self, url, token, channel):
self.url = url
self.token = token
self.channel = channel

def build_request(self, info):
"""
Takes the dict `info` and turns it into a json dump. Uploads with
requests module, and returns the response.
"""
params = json.dumps(info).encode('utf8')
req = Request(
self.url,
data=params,
headers={'content-type': 'application/json'},
)
return req

def send_message(self, text, username, icon_url, attachments=None):
""" text and username should not be None, but icon_url may be None. """
info = {
"text": text,
"token": self.token,
"channel": self.channel,
"username": username,
}
if icon_url:
info['icon_url'] = icon_url
if attachments:
info['attachments'] = attachments
req = self.build_request(info)
response = urlopen(req)
return response


def main():
""" Creates a one shot message to slack. """
parser = argparse.ArgumentParser(description='Message slack.')
parser.add_argument('token', metavar='TOKEN', help='your private token')
parser.add_argument('channel', metavar='CHANNEL', help='channel to '
'message.')
parser.add_argument('url', metavar='URL', help='slack endpoint to access')
parser.add_argument('text', metavar='TEXT', help='message text')
parser.add_argument('--username', metavar='USER', default="slackhookbot",
help='user to message as')
parser.add_argument('--icon_url', metavar="URL", help="optional url to "
"an image that is used as the icon")
args = parser.parse_args()
s = Slack(args.url, args.token, args.channel)
resp = s.send_message(args.text, args.username, args.icon_url)
print(resp.read().decode('utf8'))


if __name__ == "__main__":
main()

0 comments on commit 3c1be6b

Please sign in to comment.