-
Notifications
You must be signed in to change notification settings - Fork 0
/
logicoma.py
49 lines (42 loc) · 1.69 KB
/
logicoma.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
from flask import Flask, Response, request, make_response
import json
import logging
import handlers
logger = logging.getLogger(__name__)
class Logicoma(object):
def __init__(self, config_path='configs/logicoma.json', other_opts={}):
self.app = Flask('Logicoma')
self.app.route('/', methods=['post'])(self.hook)
self.other_opts = other_opts
self.load_config(config_path)
def load_config(self, config_path):
with open(config_path) as fp:
conf = json.load(fp)
conf.update(self.other_opts)
self.token = conf['token']
self.debug = conf.get('debug', False)
self.handlers = [handlers.load_from_config(s) for s in conf['handlers']]
def run(self, *args, **kwargs):
return self.app.run(*args, **kwargs)
def dispatch(self, text):
for h in self.handlers:
response = h.handle(text)
if response is not None:
response_json = json.dumps(response)
return (response_json, 200, {'Content-Type': 'application/json'})
return ('', 200, {})
def hook(self):
try:
payload = request.form
logger.debug("payload: %s", payload)
if self.debug or payload and payload.get('token') == self.token:
if 'text' in payload and payload.get('user_id') != 'USLACKBOT':
return make_response(self.dispatch(payload.get('text')))
else:
return Response(status=200)
else:
return Response(status=400)
except:
logger.exception('got exception on handler')
return Response(status=500)