nodejs微信开发之自动回复的实现

2022-10-18,,

上一篇:

这部分是实现简单的自动回复,当然也是很大一部分功能的实现基础,这里使用了的接口。

效果图如下:

当然,这个机器人的效果如何不是我能管得了的事情了,类似图灵机器人,我们还可以实现段子推送,快递查询等一系列功能,这里不一一实现了。

微信的消息处理

对于公众平台,每一次发消息相当于发出一个post请求,但是需要注意的是不管是发出的请求还是收到的回复,他的数据格式都是xml,但是nodejs本身无法处理xml,所以需要对xml数据进行处理。
仍然使用的是body-parser这个库,但是需要引入body-parser-xml:

//解析xml
app.use(bodyparser.xml({
 limit: '1mb',  // reject payload bigger than 1 mb
 xmlparseoptions: {
  normalize: true,   // trim whitespace inside text nodes
  normalizetags: true, // transform tags to lowercase
  explicitarray: false // only put nodes in array if >1
 }
}));

这样req.body.xml就是处理好的数据了。

一般文本消息的格式如下所示:

<xml>
 <tousername><![cdata[touser]]></tousername>
 <fromusername><![cdata[fromuser]]></fromusername>
 <createtime>1348831860</createtime>
 <msgtype><![cdata[text]]></msgtype>
 <content><![cdata[this is a test]]></content>
 <msgid>1234567890123456</msgid>
 </xml>

其中tousername是接受者的openid,fromusername是发送者的openid,createtime就是一个整型的时间戳。msgtype就是消息类型,一般有文本(text),图片(image),语音(voice),视频(video),小视频(shortvideo),地理位置(location)以及链接消息(link)。下面就以文本消息为例进行编码。

router.post('/', function (req, res) {

 res.writehead(200, {'content-type': 'application/xml'});

 var data = req.body.xml;
 var resmsg = '<xml>' +
  '<tousername><![cdata[' + data.fromusername + ']]></tousername>' +
  '<fromusername><![cdata[' + data.tousername + ']]></fromusername>' +
  '<createtime>' + parseint(new date().valueof() / 1000) + '</createtime>' +
  '<msgtype><![cdata[text]]></msgtype>' +
  '<content><![cdata['+data.content+']]></content>' +
  '</xml>';
 res.end(resmsg);
});

只需要将header的content-type设置为xml,返回一个xml的响应,那么公众号就会相应的回复一个消息,这里回复的消息是文本格式。(mac的微信一年没更新了--)

如上图,发送消息则会回复一个内容一样的消息,一个简单的自动回复就实现了。

图灵机器人

这个接口的使用十分简单,get请求链接,记得带上apikey的头,然后就会返回响应的内容。我这里请求使用的是nodejs request库。

const request = require('request');
const config = require('../../config');

function getturingresponse(info) {
 if(typeof info !== 'string') {
  info = info.tostring();
 }
 var options = {
  method:'get',
  url: 'http://apis.baidu.com/turing/turing/turing?key=879a6cb3afb84dbf4fc84a1df2ab7319&info='+info,
  headers: {
   'apikey': config.turingkey
  }
 };
 return new promise((resolve, reject) => {
  request(options, function (err, res, body) {
   if (res) {
    resolve(body);
   } else {
    reject(err);
   }
  });
 })
}

module.exports = getturingresponse;

使用promise处理异步返回的结果,避免多次回调,记得把apikey设置为header内容。

公众号机器人

好了,上面是二者分开的讲的,如果看到这应该知道一个聊天机器人的实现是非常简单的了。就是将接口响应的内容返回给用户(?如果不是非要自己实现聊天机器人的话。。。),后台这里也就相当于一个跳板。

turingrobot.js

const request = require('request');
const config = require('../../config');

function getturingresponse(info) {
 if(typeof info !== 'string') {
  info = info.tostring();
 }
 var options = {
  method:'get',
  url: 'http://apis.baidu.com/turing/turing/turing?key=879a6cb3afb84dbf4fc84a1df2ab7319&info='+info,
  headers: {
   'apikey': config.turingkey
  }
 };
 return new promise((resolve, reject) => {
  request(options, function (err, res, body) {
   if (res) {
    resolve(body);
   } else {
    reject(err);
   }
  });
 })
}

module.exports = getturingresponse;

这部分代码很简单了,就是将图灵机器人的接口响应消息返回出来。下面要做的就是将消息返回给用户,这里有一点需要注意的是对于发出的响应,该接口不能直接响应中文字符串,需要进行urlencode。

//autoreply.js
const request = require('request');

function autoreply(requestdata, info) {
 switch (requestdata.msgtype) {
  case 'text':
   var resmsg = '<xml>' +
    '<tousername><![cdata[' + requestdata.fromusername + ']]></tousername>' +
    '<fromusername><![cdata[' + requestdata.tousername + ']]></fromusername>' +
    '<createtime>' + parseint(new date().valueof() / 1000) + '</createtime>' +
    '<msgtype><![cdata[text]]></msgtype>' +
    '<content><![cdata['+info+']]></content>' +
    '</xml>';
   break;
 }

 return resmsg;
}

module.exports = autoreply;

自动回复的模块,主要是返回一个xml字符串,方便发送给用户。

//weixin.js

router.post('/', function (req, res) {

 res.writehead(200, {'content-type': 'application/xml'});

 var content = req.body.xml.content;

 turingrobot(encodeuri(content)).then(function (data) {
  var response = json.parse(data);
  var resmsg = autoreply(req.body.xml, response.text);
  res.end(resmsg);
 })
});

好,这下算是完成机器人聊天的功能了。只要将代码部署到leancloud里,就算是成功了。

github地址奉上: 欢迎star

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《nodejs微信开发之自动回复的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。