-
Notifications
You must be signed in to change notification settings - Fork 44
/
app.py
181 lines (155 loc) · 5.18 KB
/
app.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/bin/env python
# -*- coding: utf-8 -*-
import hashlib, urllib, urllib2, re, time, json
import xml.etree.ElementTree as ET
from flask import Flask, request, render_template
from private_const import APP_SECRET_KEY, DOUBAN_APIKEY
app = Flask(__name__)
app.debug = True
app.secret_key = APP_SECRET_KEY
#homepage just for fun
@app.route('/')
def home():
return render_template('index.html')
#公众号消息服务器网址接入验证
#需要在公众帐号管理台手动提交, 验证后方可接收微信服务器的消息推送
@app.route('/weixin', methods=['GET'])
def weixin_access_verify():
echostr = request.args.get('echostr')
if verification(request) and echostr is not None:
return echostr
return 'access verification fail'
#来自微信服务器的消息推送
@app.route('/weixin', methods=['POST'])
def weixin_msg():
if verification(request):
data = request.data
msg = parse_msg(data)
if user_subscribe_event(msg):
return help_info(msg)
elif is_text_msg(msg):
content = msg['Content']
if content == u'?' or content == u'?':
return help_info(msg)
else:
books = search_book(content)
rmsg = response_news_msg(msg, books)
return rmsg
return 'message processing fail'
#接入和消息推送都需要做校验
def verification(request):
signature = request.args.get('signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
token = 'doumi' #注意要与微信公众帐号平台上填写一致
tmplist = [token, timestamp, nonce]
tmplist.sort()
tmpstr = ''.join(tmplist)
hashstr = hashlib.sha1(tmpstr).hexdigest()
if hashstr == signature:
return True
return False
#将消息解析为dict
def parse_msg(rawmsgstr):
root = ET.fromstring(rawmsgstr)
msg = {}
for child in root:
msg[child.tag] = child.text
return msg
def is_text_msg(msg):
return msg['MsgType'] == 'text'
def user_subscribe_event(msg):
return msg['MsgType'] == 'event' and msg['Event'] == 'subscribe'
HELP_INFO = \
u"""
欢迎关注豆米查书^_^
直接发送书名、作者或ISBN号等关键字,即可查询书籍信息
如发送“东野圭吾”,将回复豆瓣查询到的三条数据记录
"""
def help_info(msg):
return response_text_msg(msg, HELP_INFO)
#访问豆瓣API获取书籍数据
BOOK_URL_BASE = 'http://api.douban.com/v2/book/search'
def search_book(q):
params = {'q': q.encode('utf-8'), 'apikey': DOUBAN_APIKEY, 'count': 3}
url = BOOK_URL_BASE + '?' + urllib.urlencode(params)
resp = urllib2.urlopen(url)
r = json.loads(resp.read())
books = r['books']
return books
NEWS_MSG_HEADER_TPL = \
u"""
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%d</ArticleCount>
<Articles>
"""
NEWS_MSG_TAIL = \
u"""
</Articles>
<FuncFlag>1</FuncFlag>
</xml>
"""
#消息回复,采用news图文消息格式
def response_news_msg(recvmsg, books):
msgHeader = NEWS_MSG_HEADER_TPL % (recvmsg['FromUserName'], recvmsg['ToUserName'],
str(int(time.time())), len(books))
msg = ''
msg += msgHeader
msg += make_articles(books)
msg += NEWS_MSG_TAIL
return msg
def make_articles(books):
msg = ''
if len(books) == 1:
msg += make_single_item(books[0])
else:
for i, book in enumerate(books):
msg += make_item(book, i+1)
return msg
NEWS_MSG_ITEM_TPL = \
u"""
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
"""
def make_item(book, itemindex):
title = u'%s\t%s分\n%s\n%s\t%s' % (book['title'], book['rating']['average'],
','.join(book['author']), book['publisher'], book['price'])
description = ''
picUrl = book['images']['large'] if itemindex == 1 else book['images']['small']
url = book['alt']
item = NEWS_MSG_ITEM_TPL % (title, description, picUrl, url)
return item
#图文格式消息只有单独一条时,可以显示更多的description信息,所以单独处理
def make_single_item(book):
title = u'%s\t%s分' % (book['title'], book['rating']['average'])
description = '%s\n%s\t%s' % (','.join(book['author']), book['publisher'], book['price'])
picUrl = book['images']['large']
url = book['alt']
item = NEWS_MSG_ITEM_TPL % (title, description, picUrl, url)
return item
TEXT_MSG_TPL = \
u"""
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>
"""
def response_text_msg(msg, content):
s = TEXT_MSG_TPL % (msg['FromUserName'], msg['ToUserName'],
str(int(time.time())), content)
return s
if __name__ == '__main__':
app.run()