There are many wechat robots, for example, the previous ItChat was based on the web version, but now the wechat web version has been blocked, many accounts can not be used. Wechaty has an implementation based on the iPad protocol, which is described below.

Wechaty-puppet-padplus is used for this project. Click here to view the official documentation.

Method of use

Time – telling robots send time – telling messages in the group on the hour. Specific time notification content can be set by group friends.

Basic functions:

  • It automatically strikes the hour every hour

  • Send “timer” to tell the time immediately

  • By sending “Modify template New template”, you can modify the content of the timer, where \h stands for the current hour, \m stands for the current minute, \s stands for the current second. Similar to the escape character in other languages, \\ represents the character \. For example, if it is 11:45:14 now, \\\h:\mm will be interpreted as \11:45m.

In order to highlight the framework, this project did not add too many complicated functions. Based on this, the following functions involving file operation such as group friends reporting time statistics and ranking list can be realized.

The environment

CentOS 7

start

Just initialize something from the official documentation.

First check the Node version

node --version
Copy the code

If v10.16.0 or lower, you need to update the Node first.

Create a folder. My folder is called wechatBot:

mkdir wechatbot
cd wechatbot
npm init -y
npm install ts-node typescript -g
tsc --init --target ES6
touch bot.ts
Copy the code

We created a new file named bot.ts, which is the main application. We added the official sample code to this file. Don’t forget to change the token and name to your own:

// bot.ts
import { Contact, Message, Wechaty } from 'wechaty'
import { ScanStatus } from 'wechaty-puppet'
import { PuppetPadplus } from 'wechaty-puppet-padplus'
import QrcodeTerminal from 'qrcode-terminal'
import { FileBox }  from 'wechaty'

const token = your_token

const puppet = new PuppetPadplus({
  token,
})

const name  = your_name

const bot = new Wechaty({
  name,
  puppet, // generate xxxx.memory-card.json and save login data for the next login
})

var baoshi: RegExp = new RegExp('the time. *')   // Regular expression. The group name starts with "telling time"

// The timer is triggered on the hour
async function hourReport() {
    // The current time
    var time = new Date(a);/ / hour
    var hours = time.getHours();
    / / minute
    var mins = time.getMinutes();
    / / second
    var secs = time.getSeconds();
    // Next time interval
    var next = ((60 - mins) * 60 - secs) * 1000;
    // Set the next startup time
    setTimeout(hourReport, next);
    // Count the minutes (mins may not be 0 for the first time)
    const room = await bot.Room.find({topic:baoshi})
    
    var request = require('request')
    request.get({url:'http://127.0.0.1:5000/clock'}, function (error, response, body) {  
        if (error) {
            console.log('Error :', error)
            return
        }
        console.log(' Body :', body)
        if(body.length > 0){ room? .say(body) } }) } bot.on('scan'.(qrcode, status) = > {
    if (status === ScanStatus.Waiting) {
      QrcodeTerminal.generate(qrcode, {
        small: true
      })
    }
  })
bot.on('login'.async (user: Contact) => {
    console.log(`login success, user: ${user}`)
    // Start the timer
    hourReport();
  })
bot.on('message'.async (msg: Message) => {
    console.log(`msg : ${msg}`)
    var room = msg.room()
    var topic = ' '
    if(room){
      topic = await room.topic()
    }
    var contact = msg.from()

    // Push directly to Python and we get the reply
    var request = require('request')
    var formData = {
      text: msg.text(),
      roomtopic: topic,
      date: JSON.stringify(msg.date()),
      contactid: contact? .id, }try{
      // Everything is pushed to the back end and processed in Python
      request.post({url:'http://127.0.0.1:5000/message'.formData: formData}, function (error, response, body) {  
          if (error) {
              console.log('Error :', error)
              return
          }
          console.log(' Body :', body)
          var response = JSON.parse(body)
          if(body.length > 0) {const type: string = response['type']
            if(type= ='image') {const path: string = response['content']
              const filebox: FileBox = FileBox.fromFile(path)
              if(room){
                console.log('Ready to go! ')
                room.say(filebox)
              }else{ contact? .say(filebox) } }else if(type= ='text') {const text: string = response['content']
              if(room){
                room.say(text)
              }else{ contact? .say(text) } }else{
              // Do nothing}}})}catch(e){
      console.log(e)
    }
  })
Copy the code

Install wechaty and Qrcode-Terminal

npm install wechaty@latest
npm install wechaty-puppet-padplus@latest
npm install qrcode-terminal
Copy the code

For some inexplicable reason, the connection quality of foreign websites is not good, we need to use proxy:

npm config set registry https://registry.npm.taobao.org
Copy the code

Then the installation is done.

The back-end code

# backend.py
from flask import Flask
from flask import request
import json
import datetime

app = Flask(__name__)


# global variables
name = 'the time'
model = R 'dubious! It's already \h \m! Did you study today? '

Get the content that tells the time
def gettext() :
    response_text = ' '
    status = False
    for c in model:
        if not status:
            if c == chr(92):
                status = True
            else:
                response_text += c 
        else:
            status = False
            if c == chr(92):
                response_text += c
            elif c == 'h':
                response_text += str(datetime.datetime.now().hour)
            elif c == 'm':
                response_text += str(datetime.datetime.now().minute)
            elif c == 's':
                response_text += str(datetime.datetime.now().second)
            else:
                pass
    return response_text

def handle(data) :
    global model
    text = data['text']
    if len(text) >= 6 and text[:4] = ='Modify template':
        model = text[5:]
        return json.dumps({'type': 'text'.'content': 'Great success! The current template is: \n'+model})
    elif text == 'the time':
        return json.dumps({'type': 'text'.'content': gettext()})
    else:
        return json.dumps({'type': 'null'})


@app.route('/message', methods=['GET'.'POST'])
def message() :
    if request.method == 'POST':
        data = request.form
        print(data)
        roomtopic = data['roomtopic']
        if roomtopic:     # is a group of
            if len(roomtopic) >= 2 and roomtopic[0:2] == name:
                return handle(data)                
    return json.dumps({'type':'null'})


# return the current timepiece
@app.route('/clock', methods=['GET'])
def clock() :
    return gettext()

if __name__ == '__main__':
    app.run()

Copy the code

Start the service (you can run two programs simultaneously using Screen) :

ts-node bot.ts
python3 backend.py
Copy the code

And you’re done!