Turing robot interface call limit solution

As we noted in yesterday’s article, using a Turing robot as an answering robot would suffice, but the number of responses per day would only be 100 for free. How is it possible for a poor person like me to spend 99 dollars a month on automatic reply. So I wondered if there was another way to make a request and reply list quickly. Based on my previous work experience, I understand that it is necessary to directly put the key words of the request statement and the required reply in an Excel form, and then directly query the Excel form, so that the automatic reply can be achieved. The whole process is shown as follows:

Look from the flow chart we are still in the subsequent new fault-tolerant processing on the overall framework of yesterday, once detected after Turing robots API request has been finished, we will start our tolerance, in our Excel spreadsheet to find we need to return the content, if not found, we return to a regular statement directly tell fans friends, We may not understand that now.

Now that we’re done, let’s get to work. First of all, we need to read an Excel table. I’m using the XLRD library. Since we’ve already compiled a module for reading and writing Excel tables — ReadAndWriteExcel. So HERE I will directly take the module to call it, the specific code is as follows:

# _*_coding=utf-8_*_
import xlwt
import xlrd

class WriteExcel:
    def __init__(self, sheet_name=None):
        """ Initializes the write table object: Param sheet_name: The name of the sheet to write the sheet. Default is 1 ""
        if sheet_name:
            self.sheetname = sheet_name
        else:
            self.sheetname = "1"
        self.workbook = xlwt.Workbook()
        self.worksheet = self.workbook.add_sheet(sheetname=self.sheetname)
​
    def write_values(self, row, col, values):
        """ Write values to a row of the target sheet :param row: target row: param col: Target column :param values: desired value """
        self.worksheet.write(row, col, values)
​
    def save_file(self, filename=None):
        """ save table :param filename: save filename ""
        if filename:
            self.filename = filename
        else:
            self.filename = "test.xls"
        self.workbook.save(self.filename)
class OpenExcel:
    def __init__(self, file_name=None, sheet_id=None):
        """ Initializing to read Excel :param file_name: name of the table to read: Param sheet_id: Sheet to read """
        if file_name:
            self.file_name = file_name
            self.sheet_id = sheet_id
        else:
            self.file_name = 'example.xlsx'
            self.sheet_id = 0
        self.data = self.get_data()
    def get_data(self):
        """ Return: returns the table data read """
        data = xlrd.open_workbook(self.file_name)
        tables = data.sheets()[self.sheet_id]
        return tables
​
    def get_lines(self):
        Return: returns the total number of rows in the table """
        tables = self.data
        return tables.nrows
​
    def get_cols(self):
        Return: returns the total number of columns in the table """
        tables = self.data
        return tables.ncols
​
    def get_value(self, row, col):
        """ Param row: destination row: destination column :param col: destination column :return: destination row: destination column """
        return self.data.cell_value(row, col)

if __name__ == '__main__':
    openexcel = OpenExcel(file_name="work.xls",sheet_id=0)
    print (openexcel.get_lines())
    write_excel = WriteExcel()
    for j in range(0,openexcel.get_cols()):
        for i in range(0,openexcel.get_lines()):
            write_excel.write_values(i,j,openexcel.get_value(i,j))
    write_excel.write_values(100.100."Who am I?")
    write_excel.save_file()
Copy the code

Let’s make a call to ReadAndWriteExcel. Py to return the second column’s response based on the first column’s keyword. The code is as follows:

import ReadAndWriteExcel
​
def excel_reply(msg):
    """ Keyword reply """
    keyword_read = ReadAndWriteExcel.OpenExcel(file_name="KeyWord.xlsx",sheet_id=0)
    for i in range(0,keyword_read.get_lines()):
        if msg in keyword_read.get_value(i,0) :return keyword_read.get_value(i,1)
    if "What's your name?" in msg or 'What's your name?' in msg:
        return 'Wudten, Wisemore, Ramo, Handsome De Bouyoy.'
    elif 'I love you' in msg:
        return  "I love you too."
    elif 'good morning'in msg:
        return "Good morning, my friend."
    else:
        return 'I don't understand what you are saying, \n maybe IF I take a day off, \n will have a better IQ tomorrow.'
    pass
Copy the code

Here we debug not only by reading Excel, but also by putting some fixed responses in the code. Now let’s look at the main program code.

# -*- 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)
                # Send the Turing robot back to your fans
                if '4003' in tuling_replay_text:
                    return reply_text(fromUser, toUser,ReplayFromExcel.excel_reply(content))
                else:
                    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

When we checked the Turing robot API document, we found that when the return code was 4003, the number of CALLS to the API interface had been used up. Therefore, we judged whether 4003 was in the return information of the API interface. If there was, the Turing robot API call had been used up, and we needed to use the Alternative plan of Excel to reply.

Automatic responses to images and concerns

After this configuration, we also found some problems, such as: due to the use of API development interface, resulting in the default automatic reply public account can not be used. One, the same concern of the automatic reply can not be used at the same time; Second, the above reply has always been for the text, the picture message can not be answered. In view of these two problems, we have optimized our program again, and added the case of paying attention to the automatic reply and the original picture of the picture reply. Code first:

 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)
                # Send the Turing robot back to your fans
                if '4003' in tuling_replay_text:
                    return reply_text(fromUser, toUser,ReplayFromExcel.excel_reply(content))
                else:
                    return reply_text(fromUser, toUser, tuling_replay_text)
            # Follow the automatic reply of the public account
            elif msgType == "event":
                Event = xml.find('Event').text
                if Event == "subscribe":
                    subscribe_reply = "Rookie white finally got you ~\n" \
                                      "We can learn to clock in together, \n" \
                                      "Work together to grow. \n" \
                                      "When you are upset, I can chat with you to relieve boredom oh ~"
                    return reply_text(fromUser, toUser, subscribe_reply)
            elif msgType == "image":
                mediaId = xml.find('MediaId').text
                return reply_image(fromUser, toUser, mediaId)
            else:
                return reply_text(fromUser, toUser, "I only know words.")
​
def reply_text(to_user, from_user, content):
    "" "Copy the code

Reply to request as a text type

    return """ 
       
       
        
        
       
        
        
       
        {}
        
       
        
        
       
        
        
       """.format(to_user, from_user, int(time.time() * 1000), content)
def reply_image(to_user, from_user, mediaId):
Copy the code

Reply to the request as an image type, returning the original image

return """ 
       
       
        
        
       
        
        
       
        {}
        
       
        
        
        
       
        
         
       """.format(to_user, from_user, int(time.time() * 1000), mediaId)
Copy the code

Through reading the development documents of wechat official accounts, we find that the difference between text messages and picture messages lies in msgType, where text messages are text and picture messages are image. For the image class, the message image is saved in the MediaId field, we just need to return this to the fan, that is, the original image back to the fan.

We also found that when we added fans’ attention, we received an msgType event. When the content contained in the event was SUBSCRIBE, it was regarded as fans’ attention. We judged that after receiving such a message, we just returned the content that needed to be replied to fans.

Of course, there will be some other problems, such as how to reply to audio and video. This method is similar. You can refer to the development manual of wechat public account and think about how to solve it yourself. Follow the wechat public number “rookie xiaobai’s learning and sharing” reply “101” to get the wechat public number automatic reply robot source oh. Follow the wechat public number “rookie xiaobai’s learning and sharing” reply “100” to obtain the wechat public number automatic reply robot can execute the program oh. Mom no longer has to worry that I can’t find the way