Python微信公众号接入图灵机器人

微信公众号配置


网上大部分都是用itchat插件。微信公众号官网上的代码复制下来格式会乱掉。对于python这样严格依赖格式的语言简直是噩梦。这里没有使用itchat,而是使用request直接post请求图灵api

微信公众平台

后台配置
 

后台配置

Python配置

[官方文档]


安装依赖库:


1、[Python2.7] python3版本的web.py有一些bug,无法使用。安装完以后配置环境变量。用pip安装依赖库

pip install web.py
pip install hashlib
pip install time
pip install requests

主入口:Main.py

# -*- coding: utf-8 -*-
# filename: main.py
import web
from handle import Handle  #引入Handle.py模块,这个模块在之后写。

urls = (
    '/wx', 'Handle',
)

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()


处理文件:Handle.py

# -*- coding=utf-8 -*-
import hashlib
import reply
import receive
import web
import robot #robot.py在之后写即可
class Handle(object):
 def GET(self):
  try:
   data = web.input()
   if len(data) == 0:
    return "hello, this is handle view"
   signature = data.signature
   timestamp = data.timestamp
   nonce = data.nonce
   echostr = data.echostr
   token = "微信公众号上的token值"

   list = [token, timestamp, nonce]
   list.sort()
   sha1 = hashlib.sha1()
   map(sha1.update, list)
   hashcode = sha1.hexdigest()
   if hashcode == signature:
    return echostr
   else:
    return ""
  except Exception as Argument:
   return Argument
 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':
                    content = recMsg.Content
                    rpyMsg= robot.get_response(content)
                    print rpyMsg
                    replyMsg = reply.TextMsg(toUser, fromUser,rpyMsg)
                    return replyMsg.send()
                if recMsg.MsgType == 'image':
                    mediaId = recMsg.MediaId
                    replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                    return replyMsg.send()
            else:
                print("none handler yet")
                return "success"
        except Exception as Argument:
            print Argment
            return "fail"

回复接口:reply.py

# -*- coding=utf-8 -*-
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)

注册免费的小机器人

在[图灵机器人官网](http://www.tuling123.com)注册自己的小机器人,并记住你的apikey
 

图灵机器人apikey

 请求图灵机器人api接口:robot.py

# -*- coding=utf-8 -*-
import requests

KEY = "图灵机器人官网的apikey"

def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : '机器人名',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text').encode("utf-8")
    except:
        return msg
    return msg

最后,运行主入口

python main.py 


效果测试:

个人微信公众号:

猜你喜欢

转载自blog.csdn.net/lisa0626/article/details/82420590