微信开发系列之二 - 在微信公众号里开发一个自动应答的图灵机器人
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.
- Android:一个高效的UI才是一个拉风的UI
- 什么是ORM?为什么用ORM?浅析ORM的使用及利弊
- .NET[C#]中实现实体对象深拷贝(克隆/复制)的几种方法
- Android中图片大小和屏幕密度的关系讲解
- C# WINFORM通过委托和事件窗体间(跨窗体)传值(自定义事件参数)--实例详解
- Apache Spark 2.0预览:机器学习模型持久性
- 推荐一个简单、轻量、功能非常强大的C#/ASP.NET定时任务执行管理器组件–FluentScheduler
- 携程Android App的插件化和动态加载框架
- Spring Boot构建RESTful API与单元测试
- Volley解析之表单提交篇
- JAVA中重写equals()方法的同时要重写hashcode()方法
- 调用CodeSmith类库实现代码生成(含源码)
- 1分钟生成Net对象的注释
- Android Studio之gradle的配置与介绍
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Laravel find in set排序实例
- Laravel 对某一列进行筛选然后求和sum()的例子
- 关于laravel 数据库迁移中integer类型是无法指定长度的问题
- laravel多条件查询方法(and,or嵌套查询)
- thinkphp框架使用JWTtoken的方法详解
- Laravel创建数据库表结构的例子
- laravel按天、按小时,查询数据的实例
- 浅谈laravel中的关联查询with的问题
- 解决Laravel 不能创建 migration 的问题
- 使用tp框架和SQL语句查询数据表中的某字段包含某值
- Laravel框架中集成MongoDB和使用详解
- thinkphp5 模型实例化获得数据对象的教程
- 浅谈laravel框架sql中groupBy之后排序的问题
- php 比较获取两个数组相同和不同元素的例子(交集和差集)
- Laravel 5.5 异常处理 & 错误日志的解决