-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser.py
More file actions
executable file
·52 lines (46 loc) · 1.93 KB
/
parser.py
File metadata and controls
executable file
·52 lines (46 loc) · 1.93 KB
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
# -*- coding: utf-8 -*-
"""
wechatpy_tornado.parser
~~~~~~~~~~~~~~~~
This module provides functions for parsing WeChat messages
:copyright: (c) 2014 by messense.
:license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import xmltodict
from wechatpy_tornado.messages import MESSAGE_TYPES, UnknownMessage
from wechatpy_tornado.events import EVENT_TYPES
from wechatpy_tornado.utils import to_text
def parse_message(xml):
"""
解析微信服务器推送的 XML 消息
:param xml: XML 消息
:return: 解析成功返回对应的消息或事件,否则返回 ``UnknownMessage``
"""
if not xml:
return
message = xmltodict.parse(to_text(xml))['xml']
message_type = message['MsgType'].lower()
event_type = None
if message_type == 'event' or message_type.startswith('device_'):
if 'Event' in message:
event_type = message['Event'].lower()
# special event type for device_event
if event_type is None and message_type.startswith('device_'):
event_type = message_type
elif message_type.startswith('device_'):
event_type = 'device_{event}'.format(event=event_type)
if event_type == 'subscribe' and message.get('EventKey'):
event_key = message['EventKey']
if event_key.startswith(('scanbarcode|', 'scanimage|')):
event_type = 'subscribe_scan_product'
message['Event'] = event_type
elif event_key.startswith('qrscene_'):
# Scan to subscribe with scene id event
event_type = 'subscribe_scan'
message['Event'] = event_type
message['EventKey'] = event_key[len('qrscene_'):]
message_class = EVENT_TYPES.get(event_type, UnknownMessage)
else:
message_class = MESSAGE_TYPES.get(message_type, UnknownMessage)
return message_class(message)