1. Relationship with wechat robot
I have been shooting dance teaching videos with my friends in my spare time, called “Wu Li”, and created hundreds of original videos, which have been played nearly ten million times. Therefore, I set up a wechat group to communicate with fans.
When the number of people in a wechat group exceeds 100, it is up to the group leader to manually recruit people, so I registered a wechat account on my pad and asked people to join the wechat group by adding a small account. Every night at 9 o ‘clock, I log on the account, pass all the friend requests, and then recruit them. Sometimes there would be dozens of friend requests, so I would press the button to pass, then take photos of these new friends with my mobile phone, compare the photos to find these friends in my address book one by one, and pull them into the wechat group.
Until one time I went abroad to play, feel the Pad is too heavy, so I did not take it, which means that there are 10 days can not deal with wechat trumpet, and so I came back, I found a very tragic thing…… About 100 friend requests, and I had to take dozens of photos just to get those requests!
This is clearly some mechanized flow work ah! How can a programmer do that? So I started sorting out my needs, and there were only three:
- Automatically approve friend requests.
- When my fans chat with me on wechat, they can automatically reply by keyword. After all, 80% of the problems are the same.
- Automatically pull them into the group.
So I found Wechaty on GitHub and found that with just a few dozen lines of code, I could do what I needed. Most importantly, the mechanized flow operation, robots do much better than manual.
2. Introduction of a simple wechat robot framework
There are many open source projects related to wechat robots on GitHub, through JavaScript, Electron, Go, Perl, Python, etc.
Because I am only familiar with JavaScript, I chose Wechaty. Wechaty is a Node project written in Typescript. It is a bot framework built for personal wechat, using Wechaty API. It only takes 6 lines of Javascript code to build the simplest wechat bot that supports Linux, Windows, Darwin(OSX/Mac) and Docker.
What I really like about Wechaty is that I don’t have to worry about any implementation logic, just write business logic in JS. When I think about what I need to do, JS implementation is very simple and convenient.
Wechaty uses Chrome to monitor wechat web messages in real time and encapsulate the captured messages into interfaces for developers to use. She has 9 basic events, which basically cover all the events on our Web wechat, respectively:
- The Scan event is triggered when the user needs to scan the code to log in to wechat
- The login event is triggered when the robot successfully logs in
- The logout event is triggered when the robot is offline
- The Message event is raised when a new message is sent
- Error events are raised when an error occurs in the program
- The friend event is raised when there is a friend request
- The room-Join event is triggered when someone joins the group
- The room-leave event is triggered when the group owner moves a friend out of the group
- Room-topic events are triggered when the group name is changed
Wechaty also encapsulates bots, contacts, wechat groups, and friend requests into classes Wechaty, Contact, Message, and FriendRequest, so I can import these packages and use functions to simulate wechat operations. For example, to send a message to a specific person, I just use contact.say(‘ hello ‘). Wechaty’s function names are very user-friendly, and when writing business logic using JS, reading the code is as smooth and comfortable as reading English documents.
3. How do I install Wechaty
Wechaty can be installed in two ways:
- Docker
- NPM
It is highly recommended to use Docker to install Wechaty, although I initially used the second method. It is because I tried both methods that I am deeply impressed by the “Docker method is good”.
There are two ways to install Docker and NPM:
Docker
After Docker is installed (you can click here to see how to install Docker), Wechaty is successfully installed on your computer by running the following command.
docker run -ti --rm --volume="$(pwd)":/bot zixia/wechaty run demo
After the first run, the following screenshot will appear:
Docker will automatically deploy the relevant package to the computer. After successful installation, the following screenshot will be displayed when it is run in the future:
The creators of Wechaty are crazy about this particular font, so I’ve included all the screenshots just to make it clear.
Normally, I would give this command alias to wechaty:
Alias wechaty='docker run -t I --rm -e WECHATY_LOG="silly" --volume="$(PWD)":/bot wechaty: $(PWD) 'alias wechaty='docker run -t I --rm -e WECHATY_LOG="silly" --volume="$(PWD)":/bot wechaty: $(PWD)'
Add -e WECHATY_LOG=”silly” and later version: zixia/wechaty:0.5.9 and run like this:
wechaty run demo
-e WECHATY_LOG=”silly” -e WECHATY_LOG=”silly” -e WECHATY_LOG=”silly” -e WECHATY_LOG=”silly” -e WECHATY_LOG=”silly” -e wechaty:0.5.9 0.5.9 is what I consider to be a relatively stable version.
NPM
$ npm install --save wechaty
$ node mybot.jsCopy the code
The following points are worth noting:
- Wechaty requires at least version 6 of Node, and I’m currently using version 7.
- There are some environments that require Chromedriver installed, and depending on the version, you may want to pay attention to it.
- If it is on the server, run the xvfb.sh Script in the Script to provide a virtual operating environment for Chrome, and set the environment variables for running the program as prompted.
- You can also set WECHATY_LOG to print system logs: WECHATY_LOG=SILLY node mybot.js
Instructions about the server
Many of the packages Wechaty relies on are out of the wall. It is recommended to use foreign VPS. I use DigitalOcean.
4. How to use wechaty
After the environment is deployed, basic bot functions can be successfully implemented with the following six lines of code: Print out all messages received by the wechat robot:
const { Wechaty } = require('wechaty')
Wechaty.instance()
.on('scan', (url, code) => console.log(`Scan QR Code to login: ${code}\n${url}`))
.on('login', user => console.log(`User ${user.name()} logined`))
.on('message', message => console.log(`Message: ${message.content()}`))
.init()Copy the code
Here is a brief introduction to this code:
-
Scan event: Two return values
- Code: returns the scan status
- 0: initial state
- 200: Successfully logged in
- Wechat has scanned the code, waiting for confirmation
- 408: Waiting for wechat scan code
- Url: the address of the TWO-DIMENSIONAL code image that needs to be scanned for login. You need to paste the URL into the browser to open it and scan the code for login
- Code: returns the scan status
-
Login event: the return user, representing the login user, returns a Contact type, printed to see the nickname of the user you are currently logged in to. User.id () can obtain the unique ID of the user, user.name() can obtain the wechat nickname of the user, and user.weixin() can obtain the wechat signal of the user.
-
Message event: Returns a message, representing the received message, of type Message. Message.content () gets the content of the message, message.from() gets the sender of the message, and returns a Contact. The interface documentation is still being updated. If you want to clone the source code for more interfaces, you will find a lot of interesting things.
In addition, I’d like to share two useful Wechaty tools:
qrcode-terminal
It is still very troublesome to print the qr code image to be scanned as a link on the screen and copy the link to the browser for scanning. I prefer to directly scan the QR code in Terminal to log in, so as to achieve the cool effect in the demo. There are only two steps:
1. Install dependency packages:
npm install qrcode-terminal
2. Modify the code after scan event slightly:
wechaty.on('scan', (url, code) => { if (! /201|200/.test(String(code))){ let loginUrl = url.replace(/\/qrcode\//, '/l/') require('qrcode-terminal').generate(loginUrl) } console.log(`${url}\n[${code}] Scan QR Code in above url to login: `) })Copy the code
Server sauce
Although the robot can run stably in VPS, the web-based version of wechat often kicks users offline, so I need to know about Wechaty’s various anomalies. There is a simple third-party tool called Server Sauce, which can push alarms and logs from the Server to the phone. It is very easy to operate:
1. Log in with GitHub account, obtain a SCKEY (on the “Send messages” page), follow the guide, click “wechat Push”, scan the code to follow the “sugar cube” to complete binding 2. After login, logout, Scan, and error events are triggered, I will send some key information to sc.ftqq.com/SCKEY.send to Get request, and I will receive the message in my own wechat.
In this way, when my robot appears all kinds of abnormal conditions, I can know anytime and anywhere, need to scan code to enter, sugar this public number will push the TWO-DIMENSIONAL code to my phone, I just use the robot’s wechat scan code.
Yeah, that’s it. I realized my dream of being able to pull someone with my glasses closed.
5. Subsequent
When I started to use robots to do all the repeated operations, I had further thought about the work of adding groups. For example, I pulled many wechat business into the blacklist, and they could not enter my wechat group any more. In addition, I wrote a function to add the administrator function in the wechat group, so that the administrator can kick users out of the wechat group even if they are not the group leader; Sometimes rich imagination, but also do a prank, specialized collection of friends to withdraw information, entertainment the public……
Suddenly a sentence came to mind: “People should think, Bot should work”. When machines can help us do mechanized work, we will have more time to think about the truly valuable things.
Wechaty has freed me from repetitive tasks, and I want to do something for Wechaty, so I now update Wechaty documents in my spare time, and sometimes share some problems I have with Wechaty in the hope of helping more people learn to use Wechaty quickly.
If you are interested in Wechaty and want to communicate, share and learn together, you can add “Orange Secret” as your friend by scanning the code and replying to Wechaty to join Wechaty DEVELOPERS’ HOME. You can also check out the small functions wechaty implements.