码迷,mamicode.com
首页 > 微信 > 详细

微信开发系列之二 - 在微信公众号里开发一个自动应答的图灵机器人

时间:2020-09-11 14:17:18      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:http   loading   script   eva   option   href   encodeuri   function   some   

In previous blog Wechat development series 1 – setup your development environment I introduce the necessary step to setup environment for Wechat development.

In this blog, let’s try to achieve some features which makes more sense – the Q&A service implementation based on Wechat platform.
Q&A service typically has the following activity flow:

(1) The users of your Wechat subscription account send some text to your subscription account as question;
(2) The Wechat platform delegates the message sent by your user to the given url maintained in the subscription account. See mine below for example:

技术图片

(3) Now it is your turn: parse the text sent delegate from Wechat platform, and send answer back into the requested HTTP response. Once that has been done, your end user will receive the answer with the help of Wechat platform.

In this blog I will introduce two kinds of Q&A service implemented.
(1) Echo service: Your subscription account users will receive exactly the same text as they send. In order to prove that the text has really reached the nodejs server, I add a prefix “Add by Jerry:” in front of the echo string.
See example below:

技术图片

(2) Tuning service: this service is more smart than the echo service: it will call tuning API to try to chat with your subscription account user:

技术图片

Here below are the detail steps to implement these two kinds of Q&A service.

Echo service

(1) implement server.js which is the entry point of your nodejs server logic:

var express = require(‘express‘);
var routesEngine = require(‘./jerryapp/routes/index.js‘); 
var app = express();
routesEngine(app);

app.listen(process.env.PORT || 3000, function () {
  console.log(‘Listening on port, process.cwd(): ‘ + process.cwd() );
});

(2) implement index.js which is used in server.js:

var request = require(‘request‘);
var echoService = require("../service/echo.js");
module.exports = function (app) {
  app.route(‘/‘).post(function(req,res){
    echoService(req, res);
  });
};

The code above shows that when your user send a text to your subscription account, an HTTP post request containing this text will be delegated to your nodejs server by Wechat platform, as a result it is your responsibility to parse the text from HTTP post, do your own logic ( simple echo or tuning handling ) and send the response back. The echo service in this blog is implemented in module echo.js.

(3) Implement echo.js:

var getXMLNodeValue = require("../tool/xmlparse.js");
var replyMessage = require("../tool/replyMessage.js");
const content_pattern = /<!\[CDATA\[(.*)\]\]>/;
module.exports = function(req, res){
  var _da;
   req.on("data",function(data){
        _da = data.toString("utf-8");
    });
    req.on("end",function(){
        var Content = getXMLNodeValue(‘Content‘,_da);
        var body = content_pattern.exec(Content);
        if( body.length === 2) {
            Content = "Add by Jerry: " + body[1];
        } 
        var xml = replyMessage(_da, Content);
        res.send(xml);
    });
};

Here I simply add the hard coded prefix “Add by Jerry:” to the original text and send it back.
The source code of utility module xmlparse.js:

module.exports = function(node_name, xml){
    var tmp = xml.split("<"+node_name+">");
    var _tmp = tmp[1].split("</"+node_name+">");
    return _tmp[0];
};

replyMessage.js:

var getXMLNodeValue = require("./xmlparse.js");
module.exports = function(originalBody, contentToReply){
  var ToUserName = getXMLNodeValue(‘ToUserName‘, originalBody);
  var FromUserName = getXMLNodeValue(‘FromUserName‘,originalBody);
  var CreateTime = getXMLNodeValue(‘CreateTime‘,originalBody);
  var MsgType = getXMLNodeValue(‘MsgType‘,originalBody);
  var Content = contentToReply;
  var MsgId = getXMLNodeValue(‘MsgId‘, originalBody);
  var xml = ‘<xml><ToUserName>‘+FromUserName+‘</ToUserName><FromUserName>‘+ToUserName+‘</FromUserName><CreateTime>‘+CreateTime+‘</CreateTime><MsgType>‘+MsgType+‘</MsgType><Content>‘+Content+‘</Content></xml>‘;
  console.log("xml to be sent: " + xml);
  return xml;
};

Tuning Service

It has almost the same steps as done for Echo service except some small enhancement.
In index.js, simply replace echoService call with tuningService.

技术图片

The implementation of tuning service module:

var request = require(‘request‘);
var getXMLNodeValue = require("../tool/xmlparse.js");
var replyMessage = require("../tool/replyMessage.js");
const content_pattern = /<!\[CDATA\[(.*)\]\]>/;

const url = "http://www.tuling123.com/openapi/api?key=de4ae9269c7438c33de5806562a35cac&info=";

module.exports = function(req, res){
  var _da;
    req.on("data",function(data){
        _da = data.toString("utf-8");
    });
    req.on("end",function(){
        console.log("original text: " + _da);
        var Content = getXMLNodeValue(‘Content‘,_da);
        console.log("content: " + Content);
        var body = content_pattern.exec(Content);
        console.log("result size: " + body.length);
        var requesturl = "";
        if( body.length === 2){
            requesturl = url + encodeURI(body[1]);
        } 
        var options = {
            url: requesturl,
            method: "GET"
        };
        request(options,function(error,response,data){
           if(data){
              var text = JSON.parse(data).text;
              var xml = replyMessage(_da, text);
              res.send(xml);
           }else {
              res.send("Error when calling Tuning API: " + error);
              console.log(error);
           }
        });
    });
};

In this module I just use a free tuning service provided by http://www.tulin123.com, which is very convenient to consume via Restful API call.

技术图片

要获取更多Jerry的原创文章,请关注公众号"汪子熙":
技术图片

微信开发系列之二 - 在微信公众号里开发一个自动应答的图灵机器人

标签:http   loading   script   eva   option   href   encodeuri   function   some   

原文地址:https://www.cnblogs.com/sap-jerry/p/13586313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!