Writing in the front

A few months late posts, these months have been a little busy, I neglected, about why to develop wechat robot, technology selection, Token application, a simple development can see my article published in Nuggets 4 months ago

Hand rolled Wechaty | NodeJS based on the agreement of a simple WeChat robot assistant

Is it difficult to develop a wechat robot? Wechaty Plugin Conference on May 30th, Wechaty officially launched the Plugin system. It was very exciting to hear from Huan, the author of wechaty and Gcaufy, the developer of wechaty Plugin and Wepy, as well as the author of the open source project Wepy. It was trivial, and all the business logic code was piled on top of each other

However, wechaty Plugin solves this problem perfectly. One plugin, one function, is simple and simple, based on configuration, and the plugin ecosystem is strong enough to enable our robots to be equipped with all the desired functions anytime and anywhere, making development smoother and simpler

Apply for a free Token?

Those of you who are familiar with Wechaty or who have read the previous post may know that wechaty requires a token to use the PAD protocol. Many people will immediately withdraw from wechaty when they see the need for token. There is no way to do this. However, you can also participate in the open source incentive plan to obtain long-term tokens, this world is always a small number of big shots, maybe more people see the word open source incentive plan and feel that it has nothing to do with themselves, in fact, it is not as difficult as imagined

To put it this way, before wechaty Plugin was launched, all you had to do was develop a product with a trial token (don’t get me wrong, it was officially called MVP product, minimum viable product, as I understand it, a minimum viable product is a product that happens to have some features that help you express the core concept of the product. In simple terms, what do you want to use it, you put the things to core function, and in a lot of open source, no simple and complex, feasible product is ok, just like I have to do is to manage the product core WeChat group and automatically add friends, I realized that such a simple thing, nothing more), Once you’ve developed the product, open source the code to Github and write a post

So wechaty plugin after launch, you only need to develop a plugin, you might say to develop a plug-in hard, in fact is not, there are all kinds of plug-in, depending on the developer’s ideas, like this kind of stupid, I developed a few general plug-in, automatic invite people, into the group of welcome, kicking, group check-in, etc., Each plug-in the least may only need more than a dozen lines of code, in general, as long as a little development infrastructure can be developed, regardless of plug-in or is not very practical, simple sentence team is certainly comes to the net, because it promotes the development of wechaty ecological, after all, for a project, there are more and more developers are willing to participate, I believe it will only benefit the development of this project, and for the project initiating team, it will certainly be very happy

Might have someone afraid of code to write bad is fun, I think it’s nothing, I’m not a bosses, written code also pretty bad, personal feel of a programmer, thick-skinned is important, just like write a post, if someone is teasing, for fun, I also can learn from a wave of knowledge is changed, poking fun at no less competent person that will forgive me back to Dui directly, How to think is good for me, programmer, simple, good

I see this you may like a marketing products, what do you think are just a stranger to me, of course, the daydream, anodyne, standing on my position, I am only interested in WeChat robot comparison, feel the fun of practical, to wechaty plugin is also very attention, but the number development and the plugin is really not much, So give you a wave of blood, more fun plug-in, the robot will be more and more fun

In addition, I think WeChat robot for some well-known blogger or public, the author will be very useful, after all, can effective management activity in group of ascending group chat, of course, many public, V have their own robot, is also a variety of sources, but to free access should not be, free and will have all kinds of restrictions, Wechaty is different. As a programmer, it’s better to develop your own robot

Development needs

Or to simply introduce my needs, because my side doing public number, there are also some communication group of letter, interested friends can watch “shady front end”, someone with what communication group of a set of artificial operation process is really pain, I need a robot to automatically through friends, keyword automatically invited into the group, Convenient group management and active group atmosphere, are some very common needs

A version of the development is already enough for my daily needs, but the late extension require my own development, or more troublesome, so I put on a version of some of the required functionality encapsulated into a plug-in contract, it is simple to use and the code is concise, if other people have this module requirements can also be installed directly using the plugin, In addition to using some plug-ins developed by myself, I also used several official plug-ins to enrich my robot. In short, the total code amount is only about 10 lines if not counting the plug-in configuration items

Project introduction

In fact, there is nothing good to introduce, because the switch to the plug-in system, each function is a plug-in, plug-in is a function, I will directly use all the plug-ins to introduce you one by one, there are their own development, official development, other people’s development, but also look forward to using everyone’s development of the plug-in

Of course, if you don’t want to see the introduction of these plug-ins, you can just click on the project address, see the code, run, and forget about the configuration of a few lines of code

➡️ isboyjc/wechaty-plugin-robot – GitHub portal

Project building & plug-in use

Initialize the project instance

const { Wechaty } = require("wechaty") // Wechaty core package
const { PuppetPadplus } = require("wechaty-puppet-padplus") // Padplus protocol package

/ / initialization
const bot = new Wechaty({
  puppet: new PuppetPadplus({
    token: PUPPET_PADPLUS_TOKEN, / / your token
  }),
  name: ROBOT_NAME, // The name of your robot
})
Copy the code

Use the plug-in and start it

const pluginTest = require("wechaty-plugin-test") // Import plug-ins

// Use plug-in options to configure objects for the plug-in
bot.use(pluginTest(options))

// Start the robot
bot.start()
Copy the code

wechaty-plugin-contrib

Emphasis on the

Use (WechatyPlugin())) is a JavaScript function that returns a function that accepts an instance of wechat.wechatyPlugin. The first wechat plug-in system was designed by the core team developer @gcaufy. This package is used to publish wechat plug-ins commonly used by the core development team

The above paragraph is the official explanation for this package, in simple terms, the official release of the bag has some fun plugin for the use of all of us, it is a collection of plug-ins, we directly to install this package, can use all the plug-ins, now there are a dozen a plug-in, you can also give this package PR plugins, However, it is required that the code amount of each functional plug-in should not exceed 100 lines of code, and more than 100 lines of code are officially recommended to send their own packages

If you want to learn more about the plugins in this plugin collection 👇👇👇

Wechaty/wechaty-plugin-contrib-github portal

I used a few of them, and I’ll show you what they do, but we’ll install the package first

npm install wechaty-plugin-contrib

// or

yarn add wechaty-plugin-contrib
Copy the code

QRCodeTerminal

When the robot logs in, the terminal displays scanning two-dimensional code. Before, we need to install the Qrcode-Terminal plug-in by ourselves, and then listen to scan events. Now we use the plug-in, except for reference dependency, a line of code is enough

const { QRCodeTerminal } = require("wechaty-plugin-contrib")

bot.use( QRCodeTerminal({ small: false }))
Copy the code

Promise, after using it, we can print the TWO-DIMENSIONAL code in the terminal when starting the project, and then we can scan the code on wechat to log in

EventLogger

Official explanation is that the “scan” | “login” | “message” WeChat events… And so on, in fact, is simply a log output, after logging in all operations will print logs in the console, it is also very simple to use

Provide event logs: “dong” | “message” | “error” | “friendship” | “heartbeat” | “login” | “logout” | “ready” | “reset” | “room-invite” | “room-join” | “room-leave” | “room-topic” | “scan”

There is a parameter options, an array type, that can optionally print the event log. I did not fill in this parameter and print all events by default

const { EventLogger } = require("wechaty-plugin-contrib")

bot.use(EventLogger())
Copy the code

RoomConnector

This plug-in is interesting. It connects rooms and broadcasts information from any room to all other rooms. Because the upper limit of wechat group is 500 people, many public accounts may create multiple group chats for this purpose, but their messages are not interchangeable

It supports three modes

  • OneToManyRoomConnector can broadcast messages from one room to other rooms
  • ManyToOneRoomConnector can aggregate information from various rooms into one room
  • ManyToManyRoomConnector will broadcast all information from any room to all other rooms

I used its ManyToManyRoomConnector mode here to broadcast all the information from any room to all the other rooms

The details are as follows, of course, if you want to know more, you can click on the github address of the plugin collection package above to view the official documentation

bot.use(
  ManyToManyRoomConnector({
    / / blacklist
    blacklist: [async() = >true].// Multiple group chat lists
    many: [
      "10614174865@chatroom"./ / 0 x01 Web
      "22825376327@chatroom"./ / 0 x02 Web
      "24661539197@chatroom".// Wechat robot].// The message is traversed and sent out
    map: async (message) => {
      let roomName = await message.room().topic()
      let name = await message.room().alias(message.from())
      name ? null : (name = message.from().name())
      return 'From group chat [${roomName}"The"${name}】 said \ n \ n${message.text()}`
    },
    / / white list
    whitelist: [async (message) => message.type() === bot.Message.Type.Text],
  })
)
Copy the code

wechaty-voteout

Introduction to the

This plugin was developed by Gcaufy, it is a wechat vote plugin that can help you have a vote and kick out function for your room

When there are inappropriate speakers in your group chat, send @user [keyword or expression], you can initiate a vote, you can set the number, reach a certain number will be removed from the group chat

The installation

npm install wechaty-voteout --save
Copy the code

use

const VoteOut = require('wechaty-voteout')

bot.use(VoteOut({ /* options */ }))
Copy the code

For details about the options configuration, see the following example

The sample

const options = {
  // Which room do you want the robot to work with
	// Can be RegExp (for themes) or function (filter chamber instance)
	// For example room: function (room) {room.topic (). IndexOf (' my ') > -1}
  room: [/Room Topic 1/i.'room_id@chatroom'].// When the target is reached, it means that he will be removed
  threshold: 3.// Whitelist, people who will never be voted off
  // The contact name is RegEx and the contact ID is a string
  whitelist: [],
  // Different puppets get different symbols
	// Let's run more cases to see what it is, and update the comment here, which is emoji
  downEmoji: [
    '[]'.'[ThumbsDown]'.'< img class = "qqemoji qqemoji80 text" = "[less] _web" SRC = "/ images/zh_CN/htmledition/v2 / spacer GIF" / >',].// Warning template, set to falsy to disable warning messages
  warn: [
    {{downNum}}, {{threshold}}, you will be removed from the group when the total number of votes reached. ',]// Pop up the template and set it to falsy to disable messages
  kick: 'You are leaving the electorate after a few votes. '.repeat: 'You already voted {{votee}}, you don't need to vote again. ',
}

bot.use(VoteOut(options))
Copy the code

Take a look at a picture in action

The plugin is very simple to use, but I did not develop it, so please click 👇👇👇 for more details

Gcaufy/ wechaty-Voteout-Github portal

wechaty-friend-pass

Introduction to the

The function of this plug-in is to automatically pass the friend request, or set some keywords to verify whether to automatically pass the friend request, and automatically reply a paragraph when passing the friend request

Wechaty-plugin-contrib had a FriendshipAccepter installed in contrib that provided similar functionality, but I created it myself and you can use it optionally

The installation

npm install wechaty-friend-pass

// or

yarn add wechaty-friend-pass
Copy the code

use

const WechatyFriendPass = require("wechaty-friend-pass")

bot.use(WechatyFriendPass(options))
Copy the code

As shown above, to use the plug-in, simply pass in the configuration object Options as needed

Options parameter properties type Introduction to the
keyword String|Array In friend request, only one keyword can be used as the string type, and multiple keywords can be used as the array type. All the keywords can be passed without checking the string “*”. If not passed, the keyword will not be automatically passed
blackId String|Array User blacklist ID. This parameter can be filled with the ID of the user to identify the user, so that the user is not automatically passed
reply String After automatically passing the user’s friend application, the user will automatically reply one sentence. If it is empty or not filled, the user will not reply after passing the application

The sample

const options = {
  keyword: ["Add" Special group for blocking illegal fields"."Front end"."Back-end"."The whole stack"].blackId: ["*******@id"."*******@id"].reply: "Hello, I am a robot small assistant circle \n join the technical exchange group please reply [add" shield illegal field special "group] \n contact small master please reply [123]",
}

bot.use(WechatyFriendPass(options))
Copy the code

In use as shown below

For more details please click 👉 isboyJC/wechaty-friend-pass-Github portal

wechaty-room-invite

Introduction to the

Send some keywords to the robot, and the robot will invite you into the corresponding room through these keywords, of course, can manage multiple rooms

The installation

npm install wechaty-room-invite

// or

yarn add wechaty-room-invite
Copy the code

use

const WechatyRoomInvite = require("wechaty-room-invite")

bot.use(WechatyRoomInvite(options))
Copy the code

As shown above, to use the plug-in, simply pass in the configuration object Options as needed

Options parameter properties type Introduction to the
keyword String|Array Only one of the keywords that trigger the invitation to the user can be a string type, and multiple keywords can be an array type
roomList Array List of group chats managed by robots. This item is mandatory. See the following example for the specific configuration of the array object
reply String When the length of the roomList array is greater than 1, it is regarded as managing multiple group chats. Then, after the trigger of the keyword, the group chat list data currently managed by the user will be returned for the user to select a certain group. If the group chat data list is generated by the roomList configuration, when the length of the roomList array is equal to 1, The keyword trigger will directly pull up the group invitation, so this field is useless. The reply field is not a mandatory option. When managing multiple group chats, it is recommended to use the default text directly, and the default process can be seen in the last example picture

Let’s look at an example configuration of the roomList array

roomList: [
  {
    // Group chat name. When managing multiple group chats, users can select a group chat by group chat name
    name: "Wechat Robot"./ / group chat id
    roomId: "22275855499@chatroom".// Group chat alias. It is recommended to be short. When managing multiple group chats, users can select a group chat through the alias
    alias: "A05".// tag is used to make a simple identifier for each group chat when managing multiple group chats, which is convenient for users to choose
    label: "New group".// Whether to turn off entry, if true, the group will be triggered to prompt that the group is not accessible
    close: true,},... ]Copy the code

The sample

const options = {
  keyword: ["Add * to shield illegal field special * group"."The group"."Group"].roomList: [{name: "Web ring 0 x01".roomId: "10614174865@chatroom".alias: "A01".label: "Recommended"}, {name: "Web ring 0 x02".roomId: "22825376327@chatroom".alias: "A02".label: "New group"}, {name: "Wechat Robot".roomId: "24661539197@chatroom".alias: "A04".label: "Recommended"}, {name: "Men and Gods open doors.".roomId: "22275855499@chatroom".alias: "A05".label: "Test".close: true,}],reply: "",
}

bot.use(WechatyRoomInvite(options))
Copy the code

When managing multiple group chats, when the user sends the “add” group to the robot, the robot will reply by default, of course, you can also set your own

Please click 👉 isboyJC/wechaty-room-invite-Github portal for more details

wechaty-room-welcome

Introduction to the

This is a very simple plug-in, is used to monitor the group chat new people join, and then reply a welcome to the group, can manage multiple group chat

The installation

npm install wechaty-room-welcome

// or

yarn add wechaty-room-welcome
Copy the code

use

const WechatyRoomWelcome = require("wechaty-room-welcome")

bot.use(WechatyRoomWelcome(options))
Copy the code

The Options argument is an object with only one property, reply

Options parameter properties type Introduction to the
reply String|Array When the reply parameter is a string, all the group chats that the robot joins will reply with this greeting when it listens to new entries. When it is an array, what welcome will each group chat that the robot can freely configure respond to? For the specific configuration of the array type, please see the following example

Sample reply array format

reply: [
  {
    / / group chat
    name: "Wechat Robot"./ / group chat id
    roomId: "24661539197@chatroom".// Welcome to the group
    reply: '\n Hello, welcome to join, please consciously abide by the rules of the group, civilized communication, finally, please introduce yourself to everyone! 😊 `,},... ]Copy the code

The sample

const options = {
  reply: [{name: "Web ring 0 x01".roomId: "10614174865@chatroom".reply: '\n Hello, welcome to join, please consciously abide by the rules of the group, civilized communication, finally, please introduce yourself to everyone! 😊 `}, {name: "Wechat Robot".roomId: "24661539197@chatroom".reply: '\n Hello, welcome to join, please consciously abide by the rules of the group, civilized communication, finally, please introduce yourself to everyone! 😊 `}, {name: "Men and Gods open doors.".roomId: "22275855499@chatroom".reply: 'Male god hello, welcome to join',
    },
  ],
}

bot.use(WechatyRoomWelcome(options))
Copy the code

Use the following figure

For more details please click 👉 isboyjc/ wechaty-room-welcome-Github portal

wechaty-room-remove

Introduction to the

You can @ a person who breaks the rules in a group chat and carry the keyword you set. After listening to the robot, it will help you quickly remove him and give a hint, which is much more convenient than manually deleting a person in a group chat

The installation

npm install wechaty-room-remove

// or

yarn add wechaty-room-remove
Copy the code

use

const WechatyRoomRemove = require("wechaty-room-remove")

bot.use(WechatyRoomRemove(options))
Copy the code

As shown above, to use the plug-in, simply pass in the configuration object Options as needed

Options parameter properties type Introduction to the
keyword String|Array The keyword that triggers the removal of the user can only be a string, multiple keywords can use array type, default [” plane “, “kick “]
time Number Trigger the delay after removal /ms. The default value is 3000, that is, 3s
adminList Array List of administrators that can trigger commands, an array object, a single array object property see the following configuration example
replyInfo String|Function Function (MSG){return… function(MSG){return… function(MSG){return… }, this item has a default value, as shown in the following example
replyDone String The value is a string of characters. Done is returned on success
replyNoPermission String The bot replies when a member is removed without permission, that is, replies when a user not in the adminList configuration issues a command, and does not reply by default

Let’s look at an example configuration of the adminList array

adminList: [
  {
    // Administrator nickname, which is optional
    name: "isboyjc".// Administrator ID, mandatory
    id: "wxid_nrsh4yc8yupm22"}, {name: "Tool Man Xiao Yang".id: "wxid_vkovzba0b0c212",},... ]Copy the code

The sample

const options = {
  // Trigger key word count group
  keyword: ["Plane"."Play"."Walking"."Don't send"].// List of administrators
  adminList: [
    {
      name: "isboyjc".id: "wxid_nrsh4yc8yupm22"}, {name: "Poop".id: "wxid_4mnet5yeqo5d21"}, {name: "Tool Man Xiao Yang".id: "wxid_vkovzba0b0c212",}],/ / delay
  time: 3000.The following configuration is the default, which is used to show the function type configuration
  // You can use the MSG message instance parameter in the function callback, or you can directly fill in a string
  replyInfo: function (msg) {
    return 'You may have violated community rules and received a report,The ${this.time / 1000}s will remove you from the group chat, if you have any questions, please contact management!! 🚀\n\n Removed cause: Violation of community rules \n operation time: ${dateTimeFormat()}\n Operation administrator: ${msg.from().name()}\n\nYou may have violated the community rules and received a report. After ${this.time / 1000}S, you will be removed from the group chat. If you have any questions, please contact the management! 🚀\n\nReason for removal: Violation of community rules\nOperation time:${dateTimeFormat()}\ nOperation administrator:${msg.from().name()}`
  },
  // A message is displayed indicating successful removal
  replyDone: "Removed successfully".// No reply is given by default. This option is optional
  replyNoPermission: "You temporarily have no authority oh, contact the administrator 😊",
}

bot.use(WechatyRoomRemove(options))
Copy the code

The following figure

For more details, please click 👉 ISboyJC/wechaty-room-remove-Github portal

wechaty-room-clock

Introduction to the

Punch in the group chat, after each punch in the total number of check-ins +1, +1 points, only once a day, punch in total/total points/punch log, etc., can be used for points to give small gifts to improve group activity

You may think that these operations need to use the database, but in my understanding, the more simple and convenient the wechat robot is, the better, while the data volume of wechat group chat is not very large, it is very troublesome to use a plug-in, need to configure a lot of extra things, so this plug-in uses local storage, A tripartite lightweight JSON file database LOWDB based on Node is used to avoid the tedious configuration of database

The plugin automatically creates a [robot name].clock-logs folder in the project root directory to store data

Json files are used to store clock-logs-[year]. Json files are generated every year to avoid overload caused by excessive read/write data. In this way, each group chat has a maximum of 500 users

The clock-logs-main.json file is the main file, which stores the corresponding group chat/corresponding user check-in data and so on

Of course, if you have a better idea, please let me know

The installation

npm install wechaty-room-clock

// or

yarn add wechaty-room-clock
Copy the code

use

const WechatyRoomClock = require("wechaty-room-clock")

bot.use(WechatyRoomClock(options))
Copy the code

As shown above, to use the plug-in, simply pass in the configuration object Options as needed

Options parameter properties type Introduction to the
keyword String|Array Only one key can be a string, and multiple keywords can be array. The default is [” check in “, “punch in “].
success String|Function Function (data){return a string function(data){return a string function(data){return… }, see the following example for this default value
repeat String|Function Function (data){return a string function(data){return a string function(data){return… }, the default value of this item is “check in today, do not check in again”

Examples of parameters data when the success and repeat parameters are of function type

{
  // Wechat id of the user
  "CONTACTID": "wxid_nrsh4yc8yupm22".// The user name
  "CONTACTNAME": "isboyjc".// The total number of times the user clocked
  "CLOCKNUM": 170."CLOCKINFO": {
    // The user clocked in 2020
    "2020": 69.// The user clocked in 2019
    "2019": 101
  },
  // The user credits
  "INTEGRALNUM": 170
}
Copy the code

The sample

let options = {
  // This parameter is the default value. It can also be a string
  keyword: ["Sign in"."Clock"].// This parameter is the default value. It can also be a string
  success: (data) = > {
    let str = "\n Check in successful \n"
    Object.keys(data.CLOCKINFO).map(
      (v) = > (str += `${v}Annual accumulative check-in${data.CLOCKINFO[v]}Time \ n `))return str + 'Total accumulative sign-in${data.CLOCKNUM}Time \ n${data.INTEGRALNUM}Integral `
  },
  // This parameter is the default value. It can also be a string
  repeat: (data) = > 'Today has signed in, please do not sign in',
}

bot.use(WechatyRoomClock(options))
Copy the code

Use the following figure

Please click 👉 isboyjc/ wechaty-room-clock-Github portal for more details

TODO

See it you may find the program function is not much, yes, so the plugin ecological need time to develop, in this paper, several plug-ins are behind me, is all some simple widgets, because I demand is not complicated, but is still very hope to do the next or said that the plug-in, use some fun and if you have any ideas, Contrib /issues can be created in 👉 wechaty/wechaty-plugin-contrib/issues in the issuse of wechaty. Contrib /issues can be contrib/issues in wechaty/wechaty-plugin-contrib/issues

Behind want to do a few fun small plug-in, of course, just planning stage, because have to go to work, spare time is not much

  • The blacklist
    • Recently met some people in the group a large number of friends to sell courses, so thinking of doing a blacklist plug-in, through the recording of wechat ID to monitor the people into the group, verify whether in the blacklist, if it is directly removed, at the same time open a public blacklist list, we work together
  • Group data push
    • Every day there are new added “dedicated” shielding violations field group, someone back group, especially when refund group of imperceptibly, so every day to do a plug-in timed push group of data, the data may include days new group number, refund group of number, the number of people chat and chat, the most positive people chat, and qty, group members invite friends into the group number and so on
  • QA q&a
    • We’re going to have to ask questions in the tech groupGithubWarehouse, useissuseManage each question and answer, and each successfully solved question will be included and usedwebhookeachissuseWhen submitting, it will be monitored and stored in the list. In group chat, it will monitor messages as keywords, trigger the title keywords or similar words in the list, and return corresponding links or solutions
  • Visual Management Panel
    • At present, all the changes to the robot are directly in the code. I want to make a visual management system, manage the robot and have a visual data page, which is convenient for us to view the group data anytime and anywhere. It supports Web terminal and H5
    • Now there is a similar 👉 WebPanel, we can also experience, I want to develop a more simple and convenient, along with a few data statistics page, so put in TODO, have time to say again

The last

Welcome to pay attention to the public number “not serious front end”, is the front end, and not just the front end, so called not serious front end

You can also add the robot assistant “circle” to experience a wave of oh, at the same time can also join the technical communication group

We shouldn’t be coding just to work and make money, and finally, have fun outside of work