This repository has been archived by the owner on May 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathhandlers.py
70 lines (57 loc) · 2.18 KB
/
handlers.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# coding=utf-8
import logging
from tornado import web
from tornado.options import options
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from ai import AI
class WechatHandler(web.RequestHandler):
def get(self):
echostr = self.get_argument('echostr', '')
signature = self.get_argument('signature', '')
timestamp = self.get_argument('timestamp', '')
nonce = self.get_argument('nonce', '')
try:
check_signature(options.token, signature, timestamp, nonce)
except InvalidSignatureException:
logging.warning("Signature check failed.")
else:
logging.info("Signature check success.")
self.write(echostr)
def post(self):
signature = self.get_argument('signature', '')
timestamp = self.get_argument('timestamp', '')
nonce = self.get_argument('nonce', '')
try:
check_signature(options.token, signature, timestamp, nonce)
except InvalidSignatureException:
logging.warning("Signature check failed.")
return
self.set_header("Content-Type", "application/xml;charset=utf-8")
body = self.request.body
msg = parse_message(body)
if not msg:
logging.info('Empty message, ignored')
return
# new bot
bot = AI(msg)
if msg.type == 'text':
if options.debug:
logging.info('message type text from %s', msg.source)
response = bot.respond(msg.content, msg)
reply = create_reply(response, msg, render=True)
self.write(reply)
if options.debug:
logging.info('Replied to %s with "%s"', msg.source, response)
elif msg.type == 'location':
if options.debug:
logging.info('message type location from %s', msg.source)
elif msg.type == 'image':
if options.debug:
logging.info('message type image from %s', msg.source)
else:
logging.info('message type unknown')
handlers = [
('/', WechatHandler),
]