background
I am a front end, usually also like to write technology blog and make friends, I have also created WeChat technology exchange group and WeChat public, usually I will under the article posted on the public, and my personal qr code, add WeChat to interested friends then I pull them into the group of these, but I keep friends agree WeChat validation, is to send a group of invited really is too painful, I believe that a lot of public friends are like me, as a developer, this kind of repetitive labor is absolutely intolerable
I know that I have seen some bloggers wechat trumpet is a robot, very convenient, if I can also have a robot trumpet, just automatically through the friend verification, and then the keyword reply directly send group invitation is very practical, HMM ~, think about some excitement
SO, I started my journey of wechat robot one by one in October, 19
First of all, I found several wechat robot platforms, but the price is really not beautiful
Joke? I’m a pro 8 developer, and I know how to use this non-technical method? (Actually, no money! 😅)
There was no point in doing it, but developing from zero to one wasn’t practical, so I started looking for open source games on Github
Compared several well-known open source wechat robot projects
- itchat
itchat
Is an open source wechat personal number interface, based on Python call wechat- With less than 30 lines of code, you can build a wechat robot that can process all the information
- wechaty
Wechaty
Bot SDK is a Bot SDK for wechat individuals, which can create a robot with 6 lines of JS- Have included
linux
.Windows
.MacOS
andDocker
Cross-platform support, based on Node.js
- Vbot
- Is based on wechat Web version of the interface, use
http
Protocol and polling implementation Vbot
The highlight of the anonymous function is the ability to implement a variety of interesting gameplay- Through API, it is more convenient to create their own web version of wechat, based on PHP
- Is based on wechat Web version of the interface, use
These are the official descriptions of the project, which I copied directly. When I first saw these three works, I chose Wechaty without thinking
Why is that? First impressions alone
- For a front-end, the affinity of Node.js goes without saying
itchat
Officials say less than 30 lines of code,Vbot
I didn’t say much,Wechaty
Throw out JS, official says only 6 lines
Yes, that’s how I started my first experience with Wechaty
First contact with Wechaty
Wechaty is based on the NodeJS+TS implementation
Of course, we don’t have to use TS for development, js is fine. This is one of the things I like about Wechaty, because the official examples are based on JS, not TS
Wechaty documentation is one of the first things you need to know about wechaty before you start developing it
- wechaty-Github
After a quick look at the documentation, I started to download the official example project wechaty/ wechaty-Getting-Started
After downloading, install dependencies to run
The first run is slow and may not be successful, as the Puppeteer will have to be installed and run many times
However, I did not encounter any of these, it worked successfully, everything went smoothly, no accidents at all, hahaha
After successful operation, you can scan the code to log in as shown in the following figure
Then, the accident happened 😬
The login failed. It was embarrassing
"For the security of your account, this wechat account cannot be logged into the website wechat. You can log in on your computer using wechat on Windows or wechat on Mac. Mac WeChat Windows WeChat download address: https://pc.weixin.qq.com download address: https://mac.weixin.qq.com"
Copy the code
Failed to log in to wechat page
In fact, the original stuck here for a long time, I repeatedly tried many times are not good
The reason is that currently we are using the wechat API interface based on the Web side. Maybe the Web side interface is not very safe, right
Wechat official is slowly shrinking the use of wechat on the Web, the official web version of wechat for dynamic security policy adjustment
If you receive a security prompt when logging in to the web-based wechat, you are not allowed to log in to the web-based wechat
Wechat registered after 2017 can not log in to the webpage version of wechat, and before 2017 registered wechat account is also very likely to log in
I hurriedly tried all my micro signals, are very early registration of the kind, but still is not login, running up the board, this is not cool
Finally, I finally used a friend of the micro signal boarded, but that is a friend of the large, the family to use
Later I looked around for a solution to this thing, along with the money to receive the login page version of wechat number, dragged for a few days still fruitless
Verify that your wechat account only does not support wechat on the Web. Try logging in to wechat on the web
- wx.qq.com/
On this link, PC side enter and then mobile phone scan code login, you can board is available on the web wechat
In the early days, both Vbot and ItChat were quite popular, but they were both based on the web-based version of wechat
In particular, the first Github issuse for the Itchat project says
Login can not go up here to advise you, do not tangle in this problem for too long
Channel partners can try to receive a login page version of wechat number, but it is difficult to test
If you don’t have a number, don’t worry about it. It’s useless and a waste of time, experienced by yourself (someone who was aware of the official restrictions and still spent days obsessively looking for a solution 😭)
Now, you might say, after all this, you can’t tell me?
Don’t worry, if you use Vbot and ItChat, you can’t really proceed without a wechat account to log in to
But wechaty is what we’re using right now, and that’s where wechaty comes in
Of course, if you can log in, then you can see the official documentation or sample development, very easy
You can also look at a little demo I wrote below, although the protocol is different, but the API and ideas are the same
If you can’t log in, that’s all the more reason to look at the solution
wechaty-puppet-padplus
Web version of wechat login not on? Can you log in to wechat and can’t get it?
Don’t try so hard
Wechaty-puppet-padplus was developed by wechaty. It is based on the iPad protocol
- wechaty-puppet-padplus
A Token is required to use the package, officials said
Our Mission: Make it easy to build a WeChat Chatbot for developers.
We provide a free access using iPad protocol for the developers who have a strong will and ability to build a valuable chatbot for users.
Any developers can add JuziBOT Inc’s staff ( Wechat number : botorange_yeah ) as a Wechat friend. You will receive a review form after adding. If you pass the review and willing to Write a blog in Wechaty, you can use our iPad Protocol for Free!
Our mission: easily build wechat chatbots for developers
We offer free access to the iPad protocol for developers who have a strong desire and ability to build valuable chatbots for their users
Any developer can add a JuziBOT Inc staff member (wechat id: Botorange_yeah) as a wechat friend. Once added, you will receive a review form. If you pass the review and are willing to blog in Wechaty, you can use our iPad agreement for free!
After submitting the review form, we will receive a free Token for 15 days
To get a free token that works for a long time, sign up for what’s called an open source incentive plan. After 15 days, you have to submit a Github repository of MVP(minimum Viable Product). Wechaty forks it out to the community and offers a free token that works for a long time
On the contrary, it is necessary to continue to discuss the follow-up form of cooperation, I think it is very conscience
Yes, this post is an output of the 15-day free token I applied for
Of course, I will write some when I have time, after all, there is not much time, so the things developed are not many functions, slowly improve later
Said so much, next is the serious share, relatively simple, is the entry level, for everyone’s reference
Wechat robot based on iPad protocol
Clear requirements
Before development, we should first clarify the requirements, that is, what do I need the robot to do
- 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, reply
Add group
Push group chat invitations - For example, reply
The author WeChat
Push the author’s wechat name card
- For example, reply
- Automatic chat
- In a group chat
@[robot] XXX
You can chat with robots - Private chat You can chat by sending messages
- In a group chat
- Join the group chat automatically welcome
- Automatically when a new friend joins a group chat
@[New friend]
Send a text welcome
- Automatically when a new friend joins a group chat
OK, first realize these a few simple functions, or more useful, later say later things
The project structure
The function is relatively simple, divided into many is not to let all the code in a file, simple separate under
| - SRC / | -- index. | js # entry file -- config. Js # config file | -- onScan. Js # robots need to scan qr code to monitor the callback | -- onRoomJoin. Listen callback js # entered the room | -- onMessage. Js # message listener callback | -- onFriendShip. Js # friends add to monitor the callback | -- package. JsonCopy the code
In the early to prepare
First, create a folder and initialize it
npm init -y
Copy the code
Next we install the more important core packages
// Wechaty core package
npm install --save wechaty
// Padplus protocol package
npm install --save wechaty-puppet-padplus
Copy the code
In the development process, we also need to use the package qrcode-terminal, which is used to output the TWO-DIMENSIONAL code in the terminal for us to scan the code for login
npm install --save qrcode-terminal
Copy the code
And then you can have fun. Yeah, it’s that simple
The configuration file
The config file, which is the config.js file, just pulls out the configurable parameters we need to use
module.exports = {
// puppet_padplus Token
token: "IPad Protocol Token you applied for yourself".// The name of your robot
name: "Circle".// Room/group chat
room: {
// Manage the group list
roomList: {
// Group name (used to send group name plus group): group ID, described laterCircle of the Web:"*****@chatroom", Male god group:"*****@chatroom"
},
// Join room reply
roomJoinReply: Hello, welcome to join us
},
/ / private
personal: {
// Friend authentication automatically passes the keyword
addFriendKeywords: ["Add group"."Front end"].// Whether to enable grouping
addRoom: true}}Copy the code
Entrance to the file
The entry file, which is our index.js file in the SRC directory
There’s no logic to what we’re doing
Let’s start with our package
const { Wechaty } = require("wechaty") // Wechaty core package
const { PuppetPadplus } = require("wechaty-puppet-padplus") // Padplus protocol package
const config = require("./config") // Config file
Copy the code
Then initialize our bot
/ / initialization
const bot = new Wechaty({
puppet: new PuppetPadplus({
token: config.token
}),
name: config.name
})
Copy the code
And then a chain call, listen, start, done
const onScan = require("./onScan")
const onRoomJoin = require("./onRoomJoin")
const onMessage = require("./onMessage")
const onFriendShip = require("./onFriendShip")
bot
.on("scan", onScan) // The robot listens when it needs to scan the QR code
.on("room-join", onRoomJoin) // Join the room monitor
.on("message", onMessage(bot)) // Message listener
.on("friendship", onFriendShip) // Add friends to listen
.start()
Copy the code
All the above codes have comments. Scan, room-join, message and friendship are our event listeners at various stages
- Scan robot listens when it needs to scan a QR code
- Room-join Joins room listening
- Message Listener
- Friendship Add monitor
I’m just going to briefly explain these event listeners, because there’s nothing to say, it’s all documented in the API
Can’t help but think of especially big of that expression package: please read our document carefully!!
These are the ones that listen for callbacks, and I’m just taking them out of the loop, the files in the directory structure above
Here onMessage is making a method call, which actually returns a callback function, but we’re using the bot instance in the message listener, so we’re passing the value this way
So what do these files do in order
onScan
The onScan file is our listening callback when the robot needs to scan the QR code
The code is super simple
const Qrterminal = require("qrcode-terminal")
module.exports = function onScan(qrcode, status) {
Qrterminal.generate(qrcode, { small: true})}Copy the code
The qrcode-terminal package is introduced first
What is done in this callback is simple: the callback takes two arguments
- Qrcode qr codes
- State of the status
We use the API qrterminal. generate to output the QR code to the terminal. The small parameter in the back is because the qrcode output in the qrcode-terminal package is too large by default
onFriendShip
OnFriendShip is the callback of friendship event listener, friend add listener
const { Friendship } = require("wechaty")
// Config file
const config = require("./config")
// Friend add validation messages automatically agree key word count group
const addFriendKeywords = config.personal.addFriendKeywords
// Add friends to listen for callback
module.exports = async function onFriendShip(friendship) {
let logMsg
try {
logMsg = "Add a friend" + friendship.contact().name()
console.log(logMsg)
switch (friendship.type()) {
/** * 1. New friend request * after setting the request, we can get the validation message from request.hello and accept the request via 'request.accept ()' */
case Friendship.Type.Receive:
// Check whether the authentication message exists in the configuration information
if (addFriendKeywords.some(v= > v == friendship.hello())) {
logMsg = 'Automatically pass validation because the validation message is"${friendship.hello()}"`
// Pass validation
await friendship.accept()
} else {
logMsg = "Does not pass automatically because the validation message is:" + friendship.hello()
}
break
/** * 2
case Friendship.Type.Confirm:
logMsg = "friend ship confirmed with " + friendship.contact().name()
break
}
console.log(logMsg)
} catch (e) {
logMsg = e.message
}
}
Copy the code
As shown above, when we want to add friends, the verification message fills in the text we specify can automatically pass
So, we get this parameter from our configuration file and make a judgment call when a new friend request comes in
onRoomJoin
OnRoomJoin, that is, go into the room and listen for callbacks
// Config file
const config = require("./config")
// Join room reply
const roomJoinReply = config.room.roomJoinReply
// Manage the group list
const roomList = config.room.roomList
Call room- group chat inviteeList- inviter- inviter
module.exports = async function onRoomJoin(room, inviteeList, inviter) {
// Check whether the group ID exists in the group ID array of the configuration item
if (Object.values(roomList).some(v= > v == room.id)) {
// let roomTopic = await room.topic()
inviteeList.map(c= > {
// Send the message with @
room.say(roomJoinReply, c)
})
}
}
Copy the code
The requirement is in the group chat we need to manage, as soon as a new person joins, we send a welcome message and @him
Of course, these things are still configured in config, just get them here
This callback takes three parameters
- Room group chat example
- InviteeList list of invitees
- Inviter inviter
With rooms, invitees, invitees, it’s very easy
Here room. Id is the value of the management group list object we configured
Why have a managed group list object? Because when we log in to a micro signal, group access monitoring is for all groups in the micro signal
My requirement is to manage my group, so I ran the program in advance, outputed room, and then sent a message in the group, and got all the information of the group I want to manage, including id, and then wrote it into the configuration
Next is to listen to the new join, the list of invitees traversed, using room. Say method to send group messages, the list of invitees stored is to join the wechat instance, say method the first parameter is to send a message, the second parameter is to @ this person about… I feel that my statement is not nutritious, again, here is just to say what it means, the specific API read the documentation, the documentation is very simple, too
message
Finally, there’s the message callback, which is the one with the most code, the message listener callback
This is where there’s a little bit of logic in the code, because you have to make all kinds of judgments
Not to mention the program logic, the robot, always can chat is not, so the Internet to find a free robot chat interface docking
See the interface details
- drea.cc/mm.php
It’s just an API, so we wrap it up, call the incoming message, return message, and that’s it
Because there are requests, this one uses a request package, a parameter decoding package, so it has to be installed and imported
npm install --save request
npm install --save urlencode
Copy the code
Encapsulate the interface, because it’s a free robot, so it’s definitely not very good, but enough for personal use, as follows
// Node-request request module package
const request = require("request")
// Request parameter decoding
const urlencode = require("urlencode")
/ * * *@description Robot request interface handler *@param {String} Info Sends text *@return {Promise} Corresponding content */
function requestRobot(info) {
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
// Free interface, so you need to replace the robot name with the robot name you set
send = send.replace(/Smile/g, name)
resolve(send)
} else {
if (res.code == 1010) {
resolve("It's okay, don't old Art. I thought it was love.")}else {
resolve("What are you talking about? I don't understand.")}}}else {
resolve("What are you talking about? I've lost my mind!")}})})}Copy the code
Then you can write the logic of the message listener callback, instead of writing it in words, it is too laborious, the comments are all written in line, haha
const { Message } = require("wechaty")
// Config file
const config = require("./config")
// Robot name
const name = config.name
// Manage the group list
const roomList = config.room.roomList
// Message listening callback
module.exports = bot= > {
return async function onMessage(msg) {
// Check that the message came from you, return directly
if (msg.self()) return
// Determine whether the message type is text
if (msg.type() == Message.Type.Text) {
// Determine whether the message type is from a group chat
if (msg.room()) {
// Get group chat
const room = await msg.room()
// Receive a message and mention yourself
if (await msg.mentionSelf()) {
// Get to mention your own name
let self = await msg.to()
self = "@" + self.name()
// Get the message content, get the entire message text, remove the @+ name
let sendText = msg.text().replace(self, "")
// Request a reply from the robot interface
let res = await requestRobot(sendText)
// Returns the message with @ from the person
room.say(res, msg.from())
return
}
// Received message, did not mention that I ignored
} else {
// Reply message is the keyword "add group"
if (await isAddRoom(msg)) return
// The reply message is the name of the managed group chat
if (await isRoomName(bot, msg)) return
// Request the bot chat interface
let res = await requestRobot(msg.text())
// Returns the chat interface content
await msg.say(res)
}
} else {
console.log("Messages are not text!")}}}/ * * *@description The reply message is the keyword "add group" processing function *@param {Object} MSG Message object *@return {Promise} true- Yes false- No */
async function isAddRoom(msg) {
// keyword group processing
if (msg.text() == "Add group") {
let roomListName = Object.keys(roomList)
let info = `${name}The current management group chat has${roomListName.length}You can join by replying to a group chat name
roomListName.map(v= > {
info += "【" + v + "】" + "\n"
})
msg.say(info)
return true
}
return false
}
/ * * *@description The reply message is the managed group name handler *@param {Object} Bot instance object *@param {Object} MSG Message object *@return {Promise} true- Group chat false- Not group chat */
async function isRoomName(bot, msg) {
// The reply message is the managed group chat name
if (Object.keys(roomList).some(v= > v == msg.text())) {
// Get the group chat instance through the group chat ID
const room = await bot.Room.find({ id: roomList[msg.text()] })
// Determine if the room is in - prompt and end
if (await room.has(msg.from())) {
await msg.say("You're already in your room.")
return true
}
// Send a group invitation
await room.add(msg.from())
await msg.say("Group invitation sent")
return true
}
return false
}
Copy the code
Then you can try it locally
Arrive at this, also hope to be able to have some help to you, give a point to encourage can point a praise
Look at all the files and code, it’s just a logical judgment
If you take a look at the API documentation, it’s up to you to do what you want to do, but the message monitor is just a text message, right
The last
If you want to use my things, just pull down the code config.js to replace the token and some configuration information, of course, I keep updating, the functions will be more and more, so the code in the warehouse and the article will be a little different, when using the code, simply look at the code, have written detailed notes, also very simple
- Github.com/isboyjc/wec…
Current implementation are some basic functions, logout and fault tolerance and some other process also have no, because too busy these days, slowly add late, want to do here is to have but don’t know the friend wechaty under simple introduction, simple to use, go and try it, I introduced here is just the tip of the iceberg, like Python’s classmate, The wechat team also maintains a Python version, which can also be tried at 😄
I can also realize more fun functions (the function I think of is just for my personal needs, just to achieve seamless connection with the public account, my group chat, etc., you can also do other things, such as doing a scheduled task to send a message to his girlfriend at a certain time), I can now think of the later to add the following functions
- push
- For example, 8 am every day, pull day
IT news/Nuggets hot articles
Send it to a group chat - Can pass in group chat
@[robot] keyword
Check news and articles, etc - You can set a scheduled task to periodically send messages to yourself or a group chat
- For example, 8 am every day, pull day
- Group chat function message management
- Monitor messages in group chats and warn them of improper remarks or uncivilized words
- Record the number of warnings for the same person, delete the record every month, and automatically remove the person from the group chat when the number of warnings reaches a certain level in that month
- Group chat voting function
- Robots can be used to initiate a group vote on something
- Group chat games
- Guess crossword puzzle
- , etc.
- Background management system (visual configuration and group chat data statistics)
- Visualized configuration of the realized functions of the robot, including login and other functions in the Web side visual operation and processing
- Collect group chat member activity/joining status/warning and other series of data
Come on, life is enough and fun things always like to try it, after all, the cost is not much time, you can also add my little helper WeChat circle 】 【 experience, under the validation message to write the front-end/back-end/full stack/other 】 can through directly, and he chat, or reply to “add group” technical communication group of our play a can