demand

He has always wanted to do a personal WeChat robot, has seen a big with his own personal WeChat realize voice control robot structures, backend systems, the envy at the same time, oneself also secretly made up his mind to do a self WeChat robot, found wechaty, seem to see the hope, is not true beyond who but now can be done.

Set up their own WeChat public, jd link, picture and text translation, intelligent conversation, a personal favorites now here it is, but I found that for small program’s size can not be sent to your subscription, and jd link every time I open the WeChat public number is repeated, find your subscription number after sending seems tedious, So I decided to build my own personal robot to solve the above pain points.

Surprise!! On the front

On the day of my post, I opened wechaty this afternoon

Wechaty free Version of the Web protocol to bypass the login restrictions re-glorious this article, can perfect implementation without a token to achieve wechat login

Your wechat will be on the desktop wechat login, perfect bypass can not web login wechat pain point, can also normally use your other functions

const { Wechaty } = require("wechaty"); const Qrterminal = require("qrcode-terminal"); const name = "wechat-puppet-wechat"; let bot = ""; bot = new Wechaty({ name, // generate xxxx.memory-card.json and save login data for the next login }); Function onScan(qrcode, status) {qrterminal. generate(qrcode); / / in the console display qr code const qrcodeImageUrl = [" https://wechaty.js.org/qrcode/ ", encodeURIComponent (qrcode),]. Join (" "); console.log(qrcodeImageUrl); } async function onLogin(user) {console.log(' nice little assistant ${user} login '); If (config.autoreply) {console.log(' bot chat mode enabled '); Function onLogout(user) {console.log(' ${user} has logged out '); } bot.on("scan", onScan); bot.on("login", onLogin); bot.on("logout", onLogout); bot.on("message", function(message){ console.log(message); }) / / message to monitor bot. The start (). Then (() = > console. The log (" start landing WeChat) "). The catch ((e) = > console. The error (e));Copy the code

introduce

Wechaty

Wechaty is a modern conversational RPA SDK for Chatbot Makers, creating a bot with just a few lines of code.

Wechaty provides out-of-the-box support to turn your IM account into a chatbot, giving you the generic functionality you expect that developers can easily customize and extend to create a chatbot that meets their exact needs.

The world’s shortest chatbot#

We can use Wechaty to build a chatbot with at least six lines of code

const { Wechaty } = require('wechaty')

async function main () {
  conswt bot = new Wechaty()
  bot
    .on('scan', (qrcode, status) => console.log(`Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`))
    .on('login',            user => console.log(`User ${user} logged in`))
    .on('message',       message => console.log(`Message: ${message}`))
  await bot.start()
}

main()
  .catch(console.error)
Copy the code

Before you run the code

The wechat account for enabling the Wechaty operation has been prepared. The token prefix for puppet_padLocal has been applied for

  • Wechaty-puppet-padlocal: specifies the iPad protocol implementation of wechaty

(The token applied by each person is different, so the protocol used is also different, which needs to be processed at the entrance)

Current functions

  • Automatically pass friend authentication
    • When someone adds a robot, decide whether to pass after the validation message key or pass directly
    • After verification, the robot will automatically reply and introduce the functions of the robot
  • Private chat keyword reply
    • For example, replyAdd groupPush group chat invitations
    • For example, replyThe name of the group chatAutomatic pull group
  • Automatic chat
    • Group chat is configured to chat with your robot
    • Private chat You can chat by sending messages
  • Parses applets information
  • Join the group chat automatically welcome
    • Automatically when a new friend joins a group chat@[New friend]Send a text welcome
    • Keyword trigger, send personal card link
    • Applets can be obtained by sending applets within the groupThe relevant information
    • The translation function is enabled for sending English within the group, and the maximum number of words cannot exceed 2000

API interface

Youdao Translation Baidu Translation

Day line API

The core code

Entrance to the file

bot.js

const { Wechaty } = require("wechaty"); const { PuppetPadlocal } = require("wechaty-puppet-padlocal"); Const QrcodeTerminal = require("qrcode-terminal"); // const onMessage = require("./onMessage"); // call callback const config = require("./config"); Const bot = new PuppetPadlocal({puppet: new PuppetPadlocal({token: config.token,}),}); On ("scan", (qrcode, status) => {console.log(' scan QR Code to login: ${status}\nhttps://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent( qrcode )}` ); QrcodeTerminal.generate(qrcode); }) / / login to monitor on (" login ", (user) = > {the console. The log (user, "logined"); }) / / quit listening. On (" logout ", (user) = > {the console. The log (user, "logout"); }) / / listening. On (" message ", onMessage (bot). The start ();Copy the code

onMessage.js

Type7, applet type9, card link type14. When using group chat @, you may encounter failure to send the message. You can use another method if you also encounter failure of room. Then I added a layer of judgment in the process of acquiring text information, because the message monitoring will also monitor all the messages of your group chats by default. When I tested, I met the robot chatting with people in the group actively, which was very awkward, so I formed a test group with several friends for convenience

Let member = msg.talker(); // group chat @group reply let response = 'reply to group member content'; msg.room().say(response,member);Copy the code
const { UrlLink } = require("wechaty"); const request = require("request"); const urlencode = require("urlencode"); const config = require("./config"); const miniProrReply = require(".. /utils/miniProReply"); // const translate = require(".. /utils/translate"); Const {rainbowFart, circle,drugInstruction} = require(".. /utils/txAPI"); // const name = config.name; const roomList = config.room.roomList; Module.exports = (bot) => {return async function onMessage(MSG) {return async function onMessage(MSG) { Return if (MSG. Self ()) return; Switch (msg.type()) {case 7: var reg = /^[\u4e00-\u9fa5]+$/; // Text regular console.log(" get text "); If (await isAddRoom(MSG)) return; If (await isRoomName(bot, MSG)) return; If (MSG. Payload-roomid) {// Add a message that is not specified in a group chat. Console. log(" got group chat messages "); If (msg.payload-roomid === "20856899751@chatroom") {// Check whether the reply in the group is a text if(! reg.test(msg.text())){ translate(msg); return; } else{ roomMessageReply(msg); return; } } } break; Case 9: console.log(" Get small program "); MiniProrReply (MSG); break; Case 14: console.log(" Get card link "); // Test successful break; Default: console.log(" This type of reception is currently not supported!" ); break; }}; }; @param {Object} MSG Message Object * @return {Promise} true- Yes false- No */ async function roomMessageReply(msg) { const room = msg.room(); const text = msg.text(); Const sendText = MSG. Text ().replace(" @blue ", ""); // let res = await requestRobot(sendText); // Return the message, and @ from the person can only padplus call // room.say(res, msg.fromid ()); // let member = msg.talker(); // let member = msg.talker(); // msg.room().say(response,member); room.say(res); } else { let content = await requestRobot(msg.text()); room.say(content); If (/ interactive /.test(text)) {room.say(" interactive test "); Return} else if(/ rainbowFart /.test(text)){let reply = await rainbowFart(params); room.say(reply); Return} else if(/ text /.test(text)){let reply = await circle(params); room.say(reply); Return}else if (/.test(text)) {room.say(new UrlLink(config.personal. IntroUrl)); Return} else if(/ drug /.test(text)){params.word = text.substring(2); console.log(params); let reply = await drugInstruction(params); room.say(reply); @param {Object} MSG Message Object * @return {Promise} true- Yes false- No */ async Function isAddRoom(MSG) {if (msg.text() == "MSG ") {let roomListName = object.keys (roomList); Let info = '${name}' let info = '${name}' ${roomListname. length} ' RoomListName. The map ((v) = > {info + = "" "+ v + "" +" \ n "; }); msg.say(info); return true; } return false; @param {Object} bot instance * @param {Object} MSG message Object * @return {Promise} */ async function isRoomName(bot, MSG) {if (object.keys (roomList).some((v) => v == msg.text())) {const room = await bot.Room.find({ id: roomList[msg.text()] }); Console. log(room); If (await room. Has (MSG. From ()))) {await MSG. Say (" you are in the room "); return true; } // send an invite to await room.add(msg.from()); Await MSG. Say (" group invite sent "); return true; } return false; } /** * @description {param {String} info * @return {Promise} return new Promise((resolve, reject) => { let url = `https://open.drea.cc/bbsapi/chat/get? keyWord=${urlencode(info)}`; request(url, (error, response, body) => { if (! error && response.statusCode == 200) { let res = JSON.parse(body); if (res.isSuccess) { let send = res.data.reply; Send = send. Replace (/Smile/g, name); resolve(send); } else {if (res.code == 1010) {resolve(" don't be old, I'm old, I'm old "); } else {resolve(" What are you saying, I don't understand "); }}} else {resolve(" What are you talking about, I'm a bit of a short fuse!" ); }}); }); }Copy the code

Utils folder

It mainly stores some onMessage methods, API requests and applets that extract parameter classes through XML-JS. This part is relatively simple and will not be described here

Use the utils- Translate file to replace the appID and key

Please replace the key in src-config file to ensure normal use of tianline API

The effect

Q&A

The upgrade description of github wechaty-puppet-PadPlus is as follows: Wechaty-puppet-hostie: wechaty-puppet-hostie: wechaty-puppet-hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie: Wechaty-puppet-Hostie

Wechaty-puppet-hostie has been renamed wechaty-puppet-Service. Use wechaty-puppet-service instead of wechaty-puppet-hostie

Protocol use service compatibility

Free token

Padlocal 7 days free (recommended)

The last

The process of exploring tokens and corresponding protocols is a bit painful, but I have built it, and I will provide you with the easiest way to build personal robots to communicate and learn together

Project making