sailor0913

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

从0到1系列---微信机器人之TS-Wechaty

前言

目标

项目介绍

前置条件(重要,以下条件缺一不可)

正式开始

说明

TS版本因为是原生支持,所以仅需要一个token即可,不需要像python-wechaty那样启动docker服务

编写package.json代码

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

{
  "name": "wechaty-puppet-padlocal-demo",
  "version": "0.1.2",
  "description": "Demo for wechaty-puppet-padlocal",
  "author": "haoda",
  "license": "Apache-2.0",
  "dependencies": {
    "qrcode-terminal": "^0.12.0",
    "wechaty": "^1.19.10",
    "wechaty-puppet": "^1.19.6",
    "wechaty-puppet-padlocal": "^1.11.18"
  },
  "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 {
  config,
  log,
  Message,
  ScanStatus,
  Wechaty,
  WechatyBuilder
} from 'wechaty'

import { PuppetPadlocal } from 'wechaty-puppet-padlocal'

// 这里填写申请的token
const puppet = new PuppetPadlocal({
  token: 'puppet_padlocal_8ef8ef4g2fec4d8a1220da132554a940'
})

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: 'PadLocalDemo',
  puppet,
})
  .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即代表成功。