Koa2微信公众号开发之消息管理(5)

现在就可以使用我们写好的模板回复XML消息了

...
const formatted = await parseXML(xml)
console.log(formatted)
let info = {}
let type = 'text'
info.msgType = type
info.createTime = new Date().getTime()
info.toUsername = formatted.FromUserName
info.fromUsername = formatted.ToUserName
info.content = 'JavaScript之禅'
return ctx.body = compiled(info)

我们可以把这个回复消息的功能写成一个函数

function reply (content, fromUsername, toUsername) {
 var info = {}
 var type = 'text'
 info.content = content || ''
 // 判断消息类型
 if (Array.isArray(content)) {
  type = 'news'
 } else if (typeof content === 'object') {
  if (content.hasOwnProperty('type')) {
   type = content.type
   info.content = content.content
  } else {
   type = 'music'
  }
 }
 info.msgType = type
 info.createTime = new Date().getTime()
 info.toUsername = toUsername
 info.fromUsername = fromUsername
 return compiled(info)
}

在回复消息的时候直接调用这个方法即可

...
const formatted = await parseXML(xml)
console.log(formatted)
const content = 'JavaScript之禅'
const replyMessageXml = reply(content, formatted.ToUserName, formatted.FromUserName)
return ctx.body = replyMessageXml

现在为了测试我们所写的这个功能,来实现一个【学我说话】的功能:

回复音乐将返回一个音乐类型的消息,回复文本图片,语音,公众号将返回同样的内容,当然了你可以在这个基础上进行各种发挥。

....
const formatted = await parseXML(xml)
console.log(formatted)
let content = ''
if (formatted.Content === '音乐') {
 content = {
  type: 'music',
  content: {
   title: 'Lemon Tree',
   description: 'Lemon Tree',
   musicUrl: 'http://mp3.com/xx.mp3'
  },
 }
} else if (formatted.MsgType === 'text') {
 content = formatted.Content
} else if (formatted.MsgType === 'image') {
 content = {
  type: 'image',
  content: {
   mediaId: formatted.MediaId
  },
 }
} else if (formatted.MsgType === 'voice') {
 content = {
  type: 'voice',
  content: {
   mediaId: formatted.MediaId
  },
 }
} else {
 content = 'JavaScript之禅'
}
const replyMessageXml = reply(content, formatted.ToUserName, formatted.FromUserName)
console.log(replyMessageXml)
ctx.type = 'application/xml'
return ctx.body = replyMessageXml

nice,到此时我们的测试号已经能够根据我们的消息做出相应的回应了

本篇再上一节的代码基础上做了一些优化,并重点讲解微信公众号的消息交互,最后实现了个【学我说话】的小功能。下一篇,我们将继续补充消息管理相关的知识。最后再说一句:看文档 😉