-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeixinUtils.py
101 lines (91 loc) · 3.01 KB
/
WeixinUtils.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
# coding=utf-8
__author__ = 'Jayvee'
import time
import xml.etree.ElementTree as ET
import sys
# from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf8')
class NewsItem:
def __init__(self, url, title, picurl=""):
self.url = url
self.title = title
self.picurl = picurl
def recv_msg(oriData):
"""
获取从微信服务器post而来的消息
:param oriData: post的data
:return:返回一个包含发送者、接收者、消息内容的字典
"""
xmldata = ET.fromstring(oriData)
# 获取发送方的ID
fromusername = xmldata.find("FromUserName").text
# 接收方的ID
tousername = xmldata.find("ToUserName").text
# 消息的类别
msgtype = xmldata.find("MsgType").text
if msgtype == "event":
event = xmldata.find("Event").text
xmldict = {"FromUserName": fromusername, "ToUserName": tousername, "MsgType": msgtype, "Event": event}
else:
# 消息的内容
content = xmldata.find("Content").text
xmldict = {"FromUserName": fromusername, "ToUserName": tousername, "MsgType": msgtype, "Content": content}
return xmldict
def make_singletext(tousername="", fromusername="", text=""):
"""
编制回复信息
:param content_dict:
:return:
"""
# toname = content_dict["FromUserName"]
# fromname = content_dict["ToUserName"]
# content = content_dict["Content"]
# content = "对啊,%s,然后呢" % (text)
reply = """
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>"""
resp_str = reply % (tousername, fromusername, int(time.time()), text)
return resp_str
def make_news(newslist, touser, fromuser):
"""
根据NewsItem的列表等创建多图文消息
:param newslist:
:param touser:
:param fromuser:
:return:
"""
mainbody = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
%s
</Articles>
</xml>'''
post_count = min(10, len(newslist))
itemslist = []
for index in range(post_count):
item = newslist[index]
items_body = '''
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[description]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>'''
items_body = items_body % (item.title, item.picurl, item.url)
itemslist.append(items_body)
mainbody = mainbody % (touser, fromuser, str(time.time()), str(post_count), "".join(itemslist))
# soup = BeautifulSoup(mainbody)
# return soup.prettify()
return mainbody