新建图文回复模板reply_pictext.xml:
$def with (toUser,fromUser,createTime,title1,description1,picurl1,url1)
<xml>
<ToUserName><![CDATA[$toUser]]></ToUserName>
<FromUserName><![CDATA[$fromUser]]></FromUserName>
<CreateTime>$createTime</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>3</ArticleCount>
<Articles>
<item>
<Title><![CDATA[$title1]]></Title>
<Description><![CDATA[$description1]]></Description>
<PicUrl><![CDATA[$picurl1]]></PicUrl>
<Url><![CDATA[$url1]]></Url>
</item>
<item>
<Title><![CDATA[$title1]]></Title>
<Description><![CDATA[$description1]]></Description>
<PicUrl><![CDATA[$picurl1]]></PicUrl>
<Url><![CDATA[$url1]]></Url>
</item>
<item>
<Title><![CDATA[$title1]]></Title>
<Description><![CDATA[$description1]]></Description>
<PicUrl><![CDATA[$picurl1]]></PicUrl>
<Url><![CDATA[$url1]]></Url>
</item>
</Articles>
</xml>
更改WeixinInterface类
class WeixinInterface:
def __init__(self):
self.app_root = os.path.dirname(__file__)
self.templates_root = os.path.join(self.app_root, 'template')
self.render = web.template.render(self.templates_root)
def POST(self):
str_xml = web.data() #获得post来的数据
xml = etree.fromstring(str_xml)#进行XML解析
msgType=xml.find("MsgType").text #text image voice event video shortvideo location
fromUser=xml.find("FromUserName").text
toUser=xml.find("ToUserName").text
if msgType=='event':
eventcont=xml.find("Event").text
if eventcont=='subscribe':
replayText = u'Hello,我是Amily,欢迎关注我的微信号'
return self.render.reply_text(fromUser,toUser,int(time.time()),replayText)
if eventcont == "unsubscribe":
replayText = u'我现在功能还很简单,知道满足不了您的需求,但是我会慢慢改进,欢迎您以后再来'
return self.render.reply_text(fromUser,toUser,int(time.time()),replayText)
if msgType=='text':
content=xml.find("Content").text
if type(content).__name__ == "unicode":
content = content.encode('UTF-8')
Nword = youdao(content)
return self.render.reply_text(fromUser,toUser,int(time.time()),u'有道翻译:
'+Nword) #reply_text是我们用来回复用户的模板
if msgType=='voice':
return self.render.reply_pictext(fromUser,toUser,int(time.time()),'B区来自世界的商店','女王节到了,还不快去买礼物?','http://images2015.cnblogs.com/blog/785499/201603/785499-20160308110435429-590906761.png','http://www.bqu.com')