When I just created this public number, one of my colleagues looked for my public number to chat, but at that time my public number is still only support according to keywords, if you want to support intelligent reply, it is basically impossible. Then I combined my previous experience with wechat auto-reply robot, and I first thought of Turing robot. Is it possible to connect Turing robot and wechat public number? So I started looking

Interface documentation for Turing robots

Wechat official account

Found in fact as long as we have a public web server address, WeChat public number and the web server to communicate, our WeChat public number to receive the message parsing forwarded to Turing robot, Turing robot according to our request returns the content of the corresponding reply, we will reply back to the WeChat public number. The whole process is as follows:

Configuration of wechat public account server

First of all, we need to build a Web server to receive the request of wechat official number, which can be built by flask.

Create a new project and main.py file in PyCharm and enter the following:

from flask import Flask
from flask import request
​
app = Flask(__name__)
​
@app.route("/")
def index(a):
    return "Hello World!"if __name__ == "__main__":
    app.run(host='0.0.0.0')
Copy the code

Once successful, you can access your own server from your browser

Then we need to map the server to the public network to obtain a public NETWORK URL. I use ngrok, open the downloaded EXE file, enter “ngrok HTTP 80”, and a public network mapping address appears as follows:

Copy the address marked in the red box to the server address of the wechat public account development – Basic configuration – server configuration (do not click save at this time, because we need to process the field information, otherwise the verification will not pass)

Check the development manual of wechat official account to learn the information processing process.

# -*- coding:utf-8 -*-
from flask import Flask
from flask import request
import hashlib
​
app = Flask(__name__)
​
@app.route("/")
def index(a):
    return "Hello World!"@app.route("/wechat", methods=["GET","POST"])
def weixin(a):
    if request.method == "GET":     GET request = GET request
        my_signature = request.args.get('signature')     Get the signature parameter carried
        my_timestamp = request.args.get('timestamp')     Get the timestamp parameter carried
        my_nonce = request.args.get('nonce')        # get the nonce parameter
        my_echostr = request.args.get('echostr')         # get the echostr argument carried
​
        token = 'Your token'     Make sure the token is the same as the one you just filled in
        Do dictionary sort
        data = [token,my_timestamp ,my_nonce ]
        data.sort()
        Hash hash hash hash hash hash hash hash hash hash hash hash
        temp = ' '.join(data)
        Create a hash object
        s = hashlib.sha1()
        Update the string that needs to be encrypted to the created hash object
        s.update(data.encode("utf-8"))
        # Encryption processing
        mysignature = s.hexdigest()
​
        # The encrypted string can be compared with signature to indicate that the request originated from wechat
        if my_signature == mysignature:
            return my_echostr
        else:
            return ""
            
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
Copy the code

Run the program again, and click Submit on the configuration page of wechat public account to see the prompt message of successful submission. Then we can see 200 OK GET connection information on our ngrok

Plug in the Turing robot

Just now we judged that the connection information of a GET in the program is the program for communication authentication. If the connection information is a POST request, it is the forwarding information of our public account. Next, we need to process the POST message, extract the message content and forward it to the Turing robot.

# -*- coding:utf-8 -*-
from flask import Flask
from flask import request
import hashlib
import tyuling_replay
import time
import re
import ReplayFromExcel
import xml.etree.ElementTree as ET
​
​
app = Flask(__name__)
​
@app.route("/")
def index(a):
    return "Hello World!"@app.route("/wechat", methods=["GET","POST"])
def weixin(a):
    if request.method == "GET":     GET request = GET request
        my_signature = request.args.get('signature')     Get the signature parameter carried
        my_timestamp = request.args.get('timestamp')     Get the timestamp parameter carried
        my_nonce = request.args.get('nonce')        # get the nonce parameter
        my_echostr = request.args.get('echostr')         # get the echostr argument carried
        # my_token = request.args.get('token')
        print(my_signature)
        print(my_timestamp)
        print(my_nonce)
        print(my_echostr)
        # print(my_token)
        token = '123456'     Make sure the token is the same as the one you just filled inDo dictionary sort
        data = [token,my_timestamp ,my_nonce ]
        data.sort()
        # Concatenate a string, which must be a string for hash encryption
        data = ' '.join(data)
        Create a hash object
        s = hashlib.sha1()
        Update the string that needs to be encrypted to the created hash object
        s.update(data.encode("utf-8"))
        # Encryption processing
        mysignature = s.hexdigest()
​
        print("handle/GET func: mysignature, my_signature: ", mysignature, my_signature)
​
        # The encrypted string can be compared with signature to indicate that the request originated from wechat
        if my_signature == mysignature:
            return my_echostr
        else:
            return ""
    else:
            # parse the XML
            xml = ET.fromstring(request.data)
            toUser = xml.find('ToUserName').text
            fromUser = xml.find('FromUserName').text
            msgType = xml.find("MsgType").text
            createTime = xml.find("CreateTime")
            # Determine the type and reply
            if msgType == "text":
                content = xml.find('Content').text
                Generate a Turing robot userID that meets the requirements according to the ID of the fans of the public account
                if len(fromUser)>31:
                    tuling_userid = str(fromUser[0:30])
                else:
                    tuling_userid = str(fromUser)
                tuling_userid=re.sub(r'[^A-Za-z0-9]+'.' ', tuling_userid)
                Call the Turing robot API to return the result returned by the Turing robot
                tuling_replay_text = tyuling_replay.get_message(content,tuling_userid)
                return reply_text(fromUser, toUser, tuling_replay_text)
​
            else:
                return reply_text(fromUser, toUser, "I only know words.")
​
def reply_text(to_user, from_user, content):
    "" reply to request as text type """
    return """ 
       
       
        
        
       
        
        
       
        {}
        
       
        
        
       
        
        
       """.format(to_user, from_user, int(time.time() * 1000), content)
​
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
Copy the code

We encapsulated the Turing robot call in a tyuling_replay module as follows:

import json
import urllib.request
tuling_key='Turing robot APIkey'
api_url = "http://openapi.tuling123.com/openapi/api/v2"
def get_message(message,userid):
    req = {
    "perception":
    {
        "inputText":
        {
            "text": message
        },
​
        "selfInfo":
        {
            "location":
            {
                "city": ""."province": ""."street": ""}}},"userInfo":
    {
        "apiKey": tuling_key,
        "userId": userid
    }
    }
    req = json.dumps(req).encode('utf8')
    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)
    response_str = response.read().decode('utf8')
    response_dic = json.loads(response_str)
    results_code = response_dic['intent'] ['code']
    print(results_code)
    if results_code == 4003:
        results_text = "4003:%s"%response_dic['results'] [0] ['values'] ['text']
    else:
        results_text = response_dic['results'] [0] ['values'] ['text']
    return results_text
Copy the code

For details, please refer to the Turing Robot API access documentation.

At this point, our wechat public account automatic reply robot is ready, but the free version of Turing robot calls the number of times every day is also limited, how to completely solve this problem? And we’ll talk about our approach later.

Follow the wechat public number “rookie xiaobai’s learning and sharing” reply “101” to get the wechat public number automatic reply robot source oh.

Mom no longer has to worry that I can’t find the way