The functionality to be implemented

  • Automatic chat, you can throw it in the group with everyoneTalk about SAOchat
  • Daily briefing, regular headlines for colleagues and family members
  • Daily weather report for your wifeThe programmer doesn’t have a wifeBe caring and attentive

Basic architecture

The project is based on Wechaty, an open source library that encapsulates basic wechat events, such as onLogin, onMessage, and onLogout. See the project documentation for more details. We can easily develop some common functions based on Node.js.

In this project, the Node version must be greater than or equal to 10. You can install NVM to switch the Node version.

The project code weike-boy

coded

A profound

Start by creating a new project and creating a package.json to import the library to use

"devDependencies": {
    "babel-cli": "^ 6.26.0"."babel-preset-es2015": "^ 6.24.1"// write es6 to es5"node-schedule": "^ 1.3.2." "// Scheduled task"qrcode-terminal": "^ 0.12.0", // Print the login qr code"rimraf": "^ 2.6.3." "// Terminal command tool"wechaty": "^ 0.22.6"// Wechaty base library"moment": "2.24.0"// Date processing},"dependencies": {
    "axios": "^ 0.18.0." "// network request}Copy the code

Then execute NPM install or YARN, and write a simple demo in index.js.

import QrTerm from 'qrcode-terminal';

  Wechaty.instance({ name: 'wechat-boy' })
  .on('scan', qrcode => {
    console.log(`onScan: ${qrcode}`);
    QrTerm.generate(qrcode);
  })
  .on('login', user => {
    console.log(`onLogin: ${user.name()}`);
  })
  .on('message', msg => {
    console.log(`from ${msg.from().name()} message: ${msg.text()}`)
  })
  .on('logout', usr => {
    console.log(`user ${user.name()} logout`)})Copy the code

Use proxifier global proxy. If you want to use proxifier global proxy, you can use proxifier global proxy. If you want to use proxifier global proxy, you can use proxifier global proxy

The login QR code will be printed after successful startup

Scan code login, you can listen for message events

Access Turing robot to achieve chat function

Now that the callback listening event test from the previous step is ok, we are ready to do some real work, implementing the automatic chat function only needs to operate inside the Message callback.

Edit the message callback method

on('message', async (msg) => {
  if (msg.self()) return;
  const room = msg.room();
  const content = msg.text();
  const contact = msg.from();
  let reply;
  if(room) {// represents group message}else{// personal message reply = await service.reply (content); console.log(`tuling reply:${reply}`)
    await contact.say(reply)
  }
})

// Service.reply
static async reply(content) {
    let response;
    try {
      const data = await this.get('http://www.tuling123.com/openapi/api', {params: {// key: TULING_API_KEY, info: content,}});if (data.code === 100000) {
        response = data.text;
      } else {
        throw new Error(TULING_ERROR_MESSAGE);
      }
    } catch (e) {
      response = e.message;
    }
    return response;
}

// axios get
static async get(url, params) {
    let response;
    try {
      response = await axios.get(url, params);
      console.log('------------success-----------');
      console.log(`${response.status}\n${response.statusText}\n${JSON.stringify(response.data, null, 2)}\n`)
    } catch (e) {
      console.log('------------error-------------');
      console.error(e);
      throw e
    }
    return response.data;

}
Copy the code

Add this logic and your account will now automatically chat

Access daily briefing, weather functions

Here we use the Node-Schedule library to perform the timing function in the login callback

import Schedule from 'node-schedule'

const boy = Wechaty.instance({ name: 'wechat-boy' });
boy
.on('login', (usr) => {// Set the scheduled task to be triggered at 8am every day, // the 30th second of every minute:'30 * * * * *'// 1 minute 30 seconds per hour:30 1 * * * *// 1:1:30 every day:'30 1 1 * * *// 1st day of every month 1:1:30:'30 1 1 1 * *'// 1 minute, 1 minute and 30 seconds per week:1 1 * * 1// See the node_schedule document schedule.scheduleJob ('0 0 8 * * *', async () => {// Find the note name is${alias}Const contact = await boy.contact.find ({alias: `${alias}` })
    await contact.say(await Service.getNews());
    await contact.say(await Service.getWeather());
  })
})

// Service.getNews
static async getNews() {
    let msg;
    let response;
    try {
      response = await this.get('http://v.juhe.cn/toutiao/index', {params: {/ / need to go to https://www.juhe.cn/ to apply for the key: NEWS_KEY,},}); msg = Util.handleNewsData(response); } catch (e) { console.error(e); msg ='Failed to get news';
    }
    return msg;
}

// Service.getWeather
static async getWeather() {
    let msg;
    letresponse; Try {response = await this.get(TIANQI_URL, {params: {cityname: TIANQI_CITY, // go to https://www.juhe.cn/ for key: TIANQI_KEY }, }); msg = Util.handleWeatherData(response); } catch (e) { console.error(e); msg ='Failed to get weather';
    }
    return msg;
  }

Copy the code

A simple, daily broadcast, automatic chat wechat robot to achieve.

Complete code, Video-boy