background
I have operated a wechat public account for the answer query of online courses, but sometimes the pressure of the server will be great, and there will be the problem of not responding in time, so I suddenly developed a personal account for backup meditation.
The project address
Github:github.com/hurely/wech…
Technology stack
- Wechaty — Bot SDK for wechat individuals that can create a robot using 6 lines of JS
- Wechaty-puppet-padplus — wechaty-puppet-PadPlus — wechaty-puppet-PadPlus — wechaty-puppet-PadPlus — wechaty-puppet-PadPlus — wechaty-Puppet-PadPlus — wechaty-Puppet-PadPlus — wechaty-Puppet-PadPlus — wechaty-Puppet-PadPlus
- Axios — Node request library
- Qrcode-terminal — displays the qrcode on the terminal
- The nodemon –node file is hot deployed
- Xml-js — XML and JSON parsing (optional)
function
- Automatically reply online course answers according to keyword and user ID
- After receiving the applets, send the applets appId and path
- Follow-up Other functions
Projects show
-
Automatically reply online course answers
-
Receiving applet
The core code
1. SRC /index.js — Wechaty startup entry file
const config = require(".. /config/config")
const {
Wechaty,
ScanStatus,
log,
} = require('wechaty')
const { PuppetPadplus } = require("wechaty-puppet-padplus")
const replyToAMessage = require("./utils/reply")
function onScan (qrcode, status) {
if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
require('qrcode-terminal').generate(qrcode, { small: true }) // show qrcode on console
const qrcodeImageUrl = [
'https://wechaty.js.org/qrcode/'.encodeURIComponent(qrcode),
].join(' ')
log.info('StarterBot'.'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl)
} else {
log.info('StarterBot'.'onScan: %s(%s)', ScanStatus[status], status)
}
}
function onLogin (user) {
log.info('StarterBot'.'%s login', user)
}
function onLogout (user) {
log.info('StarterBot'.'%s logout', user)
}
async function onMessage (msg) {
log.info('StarterBot', msg)
var reply = await replyToAMessage(msg)
await msg.say(reply)
}
function onMini(msg){
log.info('onMini', msg)
}
const bot = new Wechaty({
name: config.name,
puppet: new PuppetPadplus({
token: config.token
})
})
bot.on('scan', onScan)
bot.on('login', onLogin)
bot.on('logout', onLogout)
bot.on('message', onMessage)
// bot.on('mini',onMini)
bot.start()
.then(() = > log.info('StarterBot'.'Starter Bot Started.'))
.catch(e= > log.error('StarterBot', e))
Copy the code
2. Config /config.js Basic configuration file
module.exports = {
// This project is based on wechaty-puppet-padPlus
token: "puppet_XXXXXXXX".// Robot name
name: "XXXXXXXX"./ / question bank address Apply for link to http://api.51aidian.com/index.php?id=kunggggyoyoyo
tikuApi:"".// Configure the bMOB database
bombApplicationId:' '.bombRestApiKey:' '.bombSecretKey:' '.bombMasterKey:' '.bombSafeCode:' './ / API security code
bmobHost:'https://api.bmobcloud.com/1/classes/'.// The database corresponds
}
Copy the code
3. SRC /utils/reply.js Replies the content according to the keyword
const axios = require("axios");
const {
FileBox
} = require("file-box") const {
log
} = require('wechaty') const config = require(".. /.. /config/config") const {
pareMiniProgramMsg,
pareseXmlToJson
} = require(".. /utils/utils")
module.exports = (msg, length) = >{
return new Promise(async(resolve, reject) = >{
if (msg.payload.type === 9 && msg.payload.fromId === 'mishi19900806') {
let text = msg.payload.text text = pareMiniProgramMsg(text) result = pareseXmlToJson(text) result = JSON.parse(result) var response = 'Applet appId:' + result.msg.appmsg.weappinfo.appid._cdata response += '\n\n applet path is: ' + (result.msg.appmsg.weappinfo.pagepath._cdata).replace('.html'.' ') resolve(response);
}
else if (msg.text().indexOf(The 'with answers') > -1 && msg.payload.fromId === 'mishi19900806') {
let requestUrl = "";
requestUrl = config.tikuApi + encodeURI(msg.text()) axios.get(requestUrl).then(async(response) = >{
log.info('Interface callback normal ----', response) let result = "❓ question:" + response.data.question + "" + "💡 Answer:" + response.data.answer resolve(result);
}).
catch(function(err) {
log.info('Interface callback error ----', err) resolve("HMMM ~~~, this question they don't know ~")})}else {
resolve(' ')}}}Copy the code
For the convenience of development, made a judgment, only allow me to send another wechat message reply content
4. The SRC/utils/utils. Js utility class
var convert = require('xml-js')
function pareseXmlToJson(xml) {
var json = convert.xml2json(xml, {
compact: true.spaces: 4
}) return json
}
function pareseJsonToXml(json) {
var options = {
compact: true.ignoreComment: true.spaces: 4
}
var xml = convert.json2xml(json, options)
return xml
}
/* * see msg. XML file **/
function pareMiniProgramMsg(msg) {
var str = msg.replace(/'\n'/g.' ').replace(/'\t'/g.' ').replace(/'\'/g.' ')
return str
}
module.exports = {
pareseXmlToJson,
pareseJsonToXml,
pareMiniProgramMsg
}
Copy the code
Wechaty Token application method
Official Documentation
Network course answer interface usage
1. Visit api.51aidian.com/index.php?i…
2. According to the page to request a custom id, such as wangkebot token73eF71417eC4652C561D4F30893a7F51 click the authorization to write down the at this time
3. Apply for the ID and token Joining together into http://api.51aidian.com/api/adct.php?uid=wangkebot&token=73eF71417eC4652C561D4F30893a7F51&q= (note that interface is paid
After completing the above steps, a simple online course answer query wechat robot is ready.
conclusion
The above code implementation is very simple. Wechaty is much more convenient. Can the public number fans drainage to personal number, facilitate the late private domain operation.
Pit points encountered
- Avoid the blocking of wechat signal, it is suggested to use wechat trumpet for development, and reply to the content according to the specific situation;
- For details about the wechaty-Puppet version problem, see the wechaty document
run
npm install
npm start
Copy the code