From 9510cbfe130159dc070f5b2e14e15a19c1f7d7d4 Mon Sep 17 00:00:00 2001 From: Faelix Incident Handler Date: Fri, 15 Jun 2018 20:49:47 +0000 Subject: [PATCH] beginnings of a module talking to mattermost --- fih.py | 40 ++++++++++++++++++++++++++++++++++++++++ incident.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 fih.py create mode 100644 incident.py diff --git a/fih.py b/fih.py new file mode 100644 index 0000000..f206541 --- /dev/null +++ b/fih.py @@ -0,0 +1,40 @@ + +from flask import Flask, request +import os +import incident + +app = Flask( __name__ ) +app.config.from_envvar( 'FIH_SETTINGS' ) + +mm = incident.Mattermost( app.config[ 'MATTERMOST_TEAM_ID' ], + url = app.config[ 'MATTERMOST_URL' ], + port = app.config[ 'MATTERMOST_PORT' ], + login_id = app.config[ 'MATTERMOST_USER_EMAIL' ], + password = app.config[ 'MATTERMOST_USER_PASSWORD' ], + ) + +@app.route( '/mattermost/incident', methods = [ 'POST' ] ) +def mattermost_incident(): + # channel_name: testing + # command: /incident + # channel_id: o3ob1utim3nummoswjyt4174mo + # user_name: marek + # test_domain: faelix + # text: test + # team_id: 3woo8mbjrbb1in53xwdzi4ynqh + # user_id: ko3uxmend7ne8ger4uw9mxkt1o + # token: XXXXXXXXXXXXXXXXXXXXXXXXXX + + if request.form[ 'token' ] in app.config[ 'MATTERMOST_COMMAND_TOKENS' ]: + fi_number = incident.generate_incident_number() + channel_name = fi_number.lower() + mm.create_channel( channel_name, request.form[ 'text' ] ) + mm.notify( request.form[ 'channel_id' ], fi_number, channel_name ) + + return "" # "Starting incident %s in channel #%s." % ( fi_number, channel_name ) + else: + return "Invalid command token." + +@app.route( '/' ) +def hello_world(): + return 'Hello, World!' diff --git a/incident.py b/incident.py new file mode 100644 index 0000000..34291cf --- /dev/null +++ b/incident.py @@ -0,0 +1,31 @@ + +import os +import datetime +import random +import mattermostdriver + +random.seed( os.urandom( 8 ) ) + +def generate_incident_number(): + return "FI" + datetime.datetime.now().strftime( "%Y%m%d" ) + ( "%4d" % int( random.random() * 10000 ) ) + +class Mattermost( object ): + def __init__( self, team_id, *args, **kwargs ): + self.team_id = team_id + self.mm = mattermostdriver.Driver( kwargs ) + self.mm.login() + + def create_channel( self, name, purpose = None ): + r = self.mm.channels.create_channel( options = { "team_id": self.team_id, + "name": name, + "purpose": "Incident " + name + ( purpose and " " + purpose or "" ), + "header": "", + "type": "P", + } ) + print( repr( r ) ) + + + def notify( self, notify_channel_id, incident_number, incident_channel_name ): + self.mm.posts.create_post( options = { 'channel_id': notify_channel_id, + 'message': 'Starting incident %s with discussion in channel -%s' % ( incident_number, incident_channel_name, ), + } )