给你的公众号添加一个智能机器人( 五 )

修改 main.py
from flask import Flaskfrom flask import requestimport hashlibimport reimport tulingimport receiveimport replyapp = Flask(__name__)@app.route("/")def index():    return "Hello World!"# 公众号后台消息路由入口@app.route("/wechat", methods=["GET", "POST"])def wechat(): # 验证使用的GET方法    if request.method == "GET":        signature = request.args.get('signature')        timestamp = request.args.get('timestamp')        nonce = request.args.get('nonce')        echostr = request.args.get('echostr')        token = "公众号后台填写的token"  # 进行排序        dataList = [token, timestamp, nonce]        dataList.sort()        result = "".join(dataList)  #哈希加密算法得到hashcode        sha1 = hashlib.sha1()        sha1.update(result.encode("utf-8"))        hashcode = sha1.hexdigest()        if hashcode == signature:            return echostr        else:            return "" else:        recMsg = receive.parse_xml(request.data)        if isinstance(recMsg, receive.Msg):            toUser = recMsg.FromUserName            fromUser = recMsg.ToUserName            if recMsg.MsgType == 'text':                content = recMsg.Content    # userId 长度小于等于32位                if len(toUser) > 31:                    userid = str(toUser[0:30])                else:                    userid = str(toUser)                userid = re.sub(r'[^A-Za-z0-9]+', '', userid)                tulingReplay = tuling.tulingReply(content, userid)                replyMsg = reply.TextMsg(toUser, fromUser, tulingReplay)                return replyMsg.send()            elif recMsg.MsgType == 'image':                mediaId = recMsg.MediaId                replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)                return replyMsg.send()            else:                return reply.Msg().send()        else:            return reply.Msg().send()if __name__ == "__main__":    app.run(host='0.0.0.0', port=80) #公众号后台只开放了80端口耶 , 我们的机器人完成了 , 马上迫不及待的去试试 。


推荐阅读