sailor0913

须知少时凌云志,曾许人间第一流

从0到1系列_微信机器人之TS_UOS

前言

目标

项目介绍

前置条件

正式开始

编写package.json代码

在根目录下建立main.ts, package.json, package.json代码如下

{
  "name": "wechaty-puppet-uos-demo",
  "version": "0.1.2",
  "description": "Demo for wechaty-puppet-uos",
  "author": "haoda",
  "license": "Apache-2.0",
  "dependencies": {
    "qrcode-terminal": "^0.12.0",
    "wechaty": "^1.19.10",
    "wechaty-puppet": "^1.19.6",
    "wechaty-puppet-wechat": "^1.18.4"
  },
  "devDependencies": {
    "cross-env": "^7.0.3",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.4"
  },
  "scripts": {
    "init": "npx ts-node main.ts",
    "demo-esm": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" node main.ts"
  },
  "engines": {
    "node": ">= 16",
    "npm": ">=7"
  }
}

在根目录下运行npm i安装相关依赖(如果之前没有用过npm的同学可能会因为网络环境的问题安装失败,可以换成国内源尝试)

编写main.ts代码

main.ts代码如下

// main.ts
import {
  log,
  Message,
  ScanStatus,
  WechatyBuilder
} from 'wechaty'

async function onMessage(message: Message) {
  try {
    const room = message.room()
    const sender = message.talker()
    const content = message.text()

    if (message.self()) {
      return
    }

    if (content === 'ding') {
      await message.say('dong')
    }
  }
  catch (e) {
    console.error(e)
  }
}

const bot = WechatyBuilder.build({
  name: 'UosDemo',
  puppetOptions: {
    uos: true // 重要,开启uos协议
  },
  puppet: 'wechaty-puppet-wechat',
})
  .on('scan', (qrcode, status) => {
    if (status === ScanStatus.Waiting && qrcode) {
      const qrcodeImageUrl = [
        'https://wechaty.js.org/qrcode/',
        encodeURIComponent(qrcode),
      ].join('')

      log.info(`onScan: ${ScanStatus[status]}(${status}) - ${qrcodeImageUrl}`)

      require('qrcode-terminal').generate(qrcode, { small: true }) // show qrcode on console
    }
    else {
      log.info(`onScan: ${ScanStatus[status]}(${status})`)
    }
  })

  .on('login', (user) => {
    log.info(`${user} login`)
  })

  .on('logout', (user, reason) => {
    log.info(`${user} logout, reason: ${reason}`)
  })

  .on('message', onMessage)

bot.start().then(() => {
  log.info('started.')
})

测试

之后运行npm run init,一切正常的情况下会在终端出现一个二维码,使用做微信机器人的微信号扫码登陆,之后使用别的微信向此微信发送ding,微信机器人回复dong即代表成功。