入门指引之实现简单的被动回复和图来图往

预实现功能:

  1. 粉丝给公众号一条文本消息,公众号立马回复一条文本消息给粉丝,不需要通过公众平台网页操作。

    粉丝发给公众号的文本消息,后台显示的xml片段是这样的:   

<xml>
<ToUserName><![CDATA[公众号]]></ToUserName>
 <FromUserName><![CDATA[粉丝号]]></FromUserName>
 <CreateTime>1460537339</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[欢迎开启公众号开发者模式]]></Content>
 <MsgId>6272960105994287618</MsgId>
 </xml>

其中 MsgId:是公众平台为记录识别该消息的一个标记数值, 微信后台系统自动产生

  那么微信公众平台回复粉丝的文本消息,后台显示的xml片段是这样的:

<xml>
 <ToUserName><![CDATA[粉丝号]]></ToUserName>
 <FromUserName><![CDATA[公众号]]></FromUserName>
 <CreateTime>1460541339</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[test]]></Content>
 </xml>

收到粉丝消息后不想或者不能5秒内回复时,需回复“success”字符串,如果没有在服务器端回复“success",那么就会在微信前端出现 ”该公众号提高的服务出现故障,
请稍后再试"的提示

  2. 图来图往

粉丝发给公众号的图片消息,后台显示的xml片段是这样的:   

<xml>
<ToUserName><![CDATA[公众号]]></ToUserName>
 <FromUserName><![CDATA[粉丝号]]></FromUserName>
 <CreateTime>1460536575</CreateTime>
 <MsgType><![CDATA[image]]></MsgType>
 <PicUrl><![CDATA[http://mmbiz.qpic.cn/xxxxxx /0]]></PicUrl>
 <MsgId>6272956824639273066</MsgId>
 <MediaId><![CDATA[gyci5a-xxxxx-OL]]></MediaId>
 </xml>
MediaId: 是微信系统产生的id 用于标记该图片

  那么微信公众平台回复粉丝的文本消息,后台显示的xml片段是这样的:

xml>
 <ToUserName><![CDATA[粉丝号]]></ToUserName>
 <FromUserName><![CDATA[公众号]]></FromUserName>
 <CreateTime>1460536576</CreateTime>
 <MsgType><![CDATA[image]]></MsgType>
 <Image>
 <MediaId><![CDATA[gyci5oxxxxxxv3cOL]]></MediaId>
 </Image>
 </xml>

开发流程图:

   

 

 

 码代码:

  需要封装接收到的消息:

# -*- coding: utf-8 -*-
# filename: receive.py
import xml.etree.ElementTree as ET


def parse_xml(web_data):
    if len(web_data) == 0:
        return None
    xmlData = ET.fromstring(web_data)
    msg_type = xmlData.find('MsgType').text
    if msg_type == 'text':
        return TextMsg(xmlData)
    elif msg_type == 'image':
        return ImageMsg(xmlData)

class Msg(object):
    def __init__(self, xmlData):
        self.ToUserName = xmlData.find('ToUserName').text
        self.FromUserName = xmlData.find('FromUserName').text
        self.CreateTime = xmlData.find('CreateTime').text
        self.MsgType = xmlData.find('MsgType').text
        self.MsgId = xmlData.find('MsgId').text

class TextMsg(Msg):
    def __init__(self, xmlData):
        Msg.__init__(self,xmlData)
        self.content = xmlData.find('Content').text.encode('utf-8')

class ImageMsg(Msg):
    def __init__(self, xmlData):
        Msg.__init__(self,xmlData)
        self.PicUrl = xmlData.find('PicUrl').text
        self.MediaId = xmlData.find('MediaId').text

需要封装要回复的消息:

# -*-coding: utf-8 -*-
# filename: reply.py

import time

class Msg(object):
    def __init__(self):
        pass
    def send(self):
        return "success"

class TextMsg(Msg):
    def __init__(self, toUserName, fromUserName, content):
        self.__dict = dict()
        self.__dict['ToUserName'] = toUserName
        self.__dict['FromUserName'] = fromUserName
        self.__dict['CreateTime'] = int(time.time())
        self.__dict['Content'] = content

    def send(self):
        xmlForm="""
       <xml>
         <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
         <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
         <CreateTime>{CreateTime}</CreateTime>
         <MsgType><![CDATA[text]]></MsgType>
         <Content><![CDATA[{Content}]]></Content>
        </xml>
        """
        return xmlForm.format(**self.__dict)

class ImageMsg(Msg):
    def __init__(self, toUserName,fromUserName, mediaId):
        self.__dict = dict()
        self.__dict['ToUserName'] = toUserName
        self.__dict['FromUserName'] = fromUserName
        self.__dict['CreateTime'] = int(time.time())
        self.__dict['MediaId'] = mediaId

    def send(self):
        xmlForm = """
            <xml>
              <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
              <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
              <CreateTime>{CreateTime}</CreateTime>
              <MsgType><![CDATA[image]]></MsgType>
              <Image>
                <MediaId><![CDATA[{MediaId}]]></MediaId>
              </Image>
            </xml>
        """
        return xmlForm.format(**self.__dict)

在主流程中判断接收到的消息类型,然后依此来实现回复:

  

    def POST(self):
        try:
            webData = web.data()
            print("Handle Post webdata is ", webData) #后台打印日志
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg,receive.Msg):
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                if recMsg.MsgType == 'text':
                    print("文本消息")
                    content = "test"
                    replyMsg = reply.TextMsg(toUser,fromUser,content)
                    return replyMsg.send()
                elif isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'image':
                    print("图片消息")
                    mediaId = recMsg.MediaId
                    replyMsg = reply.ImageMsg(toUser,fromUser,mediaId)
                    return replyMsg.send()
                else:
                    print("暂时不处理")
                    return 'success'

 

posted @ 2019-10-15 15:21  AhMay  阅读(210)  评论(0)    收藏  举报