node+微信+chatgpt 机器人集成

javascript 复制代码
const { WechatyBuilder, ScanStatus, log } = require('wechaty')
const qrTerminal = require('qrcode-terminal')

const defaultMessage = async ({ msg, bot }) => {
  const contact = msg.talker() 
  //const receiver = msg.to() 
  let content = msg.text() 
  const room = msg.room() 
  //const roomName = (await room?.topic()) || null // 
  const alias = (await contact.alias()) || (await contact.name()) 
  const remarkName = await contact.alias() 
  const name = await contact.name() 
  const isText = msg.type() === bot.Message.Type.Text
  const isRoom = true // roomWhiteList.includes(roomName) || roomName?.includes('gpt')
  // const isAlias =
  //   aliasWhiteList.includes(remarkName) ||
  //   aliasWhiteList.includes(name) ||
  //   remarkName.includes('gpt')
  const isAlias = true
  console.log('remarkName', remarkName)
  console.log('name', name)
  console.log('alias', alias)
  console.log('isAlias', isAlias)
  console.log(JSON.stringify(msg))

  if (isText) {
    content = content.trim()
    if (content.length > 4) {
      let startContent = content.slice(0, 4)
      startContent = startContent.toLowerCase()
      let message = ''
      let gptVersion = ''
      if (
        startContent === 'gpt,' ||
        startContent === 'gpt,' ||
        startContent === 'gpt ' ||
        startContent === 'gpt:' ||
        startContent === 'gpt:'
      ) {
        message = content.slice(4)
        gptVersion = '3.5'
      }

      let startContent2 = content.slice(0, 5)
      startContent = startContent.toLowerCase()
      if (
        startContent2 === 'gpt4,' ||
        startContent2 === 'gpt4,' ||
        startContent2 === 'gpt4 ' ||
        startContent2 === 'gpt4:' ||
        startContent2 === 'gpt4:'
      ) {
        message = content.slice(5)
        gptVersion = '4'
      }

      try {
        if (isRoom && room && message && gptVersion) {
          let result = await new Promise((resolve) => {
            chatAdd(
              {
                body: {
                  alias,
                  message,
                  gptVersion,
                  isRoom: true,
                  apiKeyValue: apiKey,
                },
                headers: {
                  version: 'wx',
                  platformos: 'wx',
                },
              },
              {
                send: (res) => {
                  resolve(res)
                },
              }
            )
          })
          if (result.code === 200) {
            await room.say(result.data.robotMessage)
          } else {
            await room.say(result.message)
          }
        } else if (isAlias && !room && message && gptVersion) {
          let result = await new Promise((resolve) => {
            chatAdd(
              {
                body: {
                  alias,
                  message,
                  gptVersion,
                  isRoom: false,
                  apiKeyValue: apiKey,
                },
                headers: {
                  version: 'wx',
                  platformos: 'wx',
                },
              },
              {
                send: (res) => {
                  resolve(res)
                },
              }
            )
          })
          if (result.code === 200) {
            let day = moment(Date.now()).format('YYYY-MM-DD')
            let wxUserObjKey = alias + day
            if (result.data.isBindWX) {
              await contact.say(`${result.data.robotMessage}`)
            } else if ( result.data.isBindWX === false && wxUserObj && wxUserObj[wxUserObjKey] <= 3) {
              await contact.say(`${result.data.robotMessage}`)
            } else {
              await contact.say(`${result.data.robotMessage}

### 温馨提示        
`)
            }
          } else {
            await contact.say(result.message)
          }
        } else {
          console.log('提问错误1')
        }
      } catch (e) {
        console.error(e)
      }
    } else {
      console.log('长短太短')
    }
  } else {
    console.log('不是文本')
  }
}

const chatWx = async (req, res) => {
  try {
    // 扫码
    const onScan = (qrcode, status) => {
      let qrcodeImageUrl
      if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
        qrTerminal.generate(qrcode, { small: true })
        qrcodeImageUrl = [
          'https://api.qrserver.com/v1/create-qr-code/?data=',
          encodeURIComponent(qrcode),
        ].join('')
        console.log('onScan:', qrcodeImageUrl, ScanStatus[status], status)
      } else {
        log.info('onScan: %s(%s)', ScanStatus[status], status)
      }

      console.log(
        `Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(
          qrcode
        )}`
      )
      console.log(qrcode)
      res.send({
        code: 200,
        data: {
          qrcode1: `https://wechaty.js.org/qrcode/${encodeURIComponent(
            qrcode
          )}`,
          qrcode,
          qrcodeImageUrl,
        },
        message: '成功',
      })
      return
    }

    // 登录
    const onLogin = (user) => {
      console.log(`${user} has logged in`)
      const date = new Date()
      console.log(`Current time:${date}`)
      console.log(`Automatic robot chat mode has been activated`)
    }

    // 登出
    const onLogout = (user) => {
      console.log(`${user} has logged out`)
    }

    // 收到好友请求
    const onFriendShip = async (friendship) => {
      const frienddShipRe = /chatgpt|chat/
      if (friendship.type() === 2) {
        if (frienddShipRe.test(friendship.hello())) {
          await friendship.accept()
        }
      }
    }
    const onMessage = async (msg) => {
      await defaultMessage({ msg, bot })
    }

    let bot
    // eslint-disable-next-line
    if (global.isLocal && false) {
      const CHROME_BIN = process.env.CHROME_BIN
        ? { endpoint: process.env.CHROME_BIN }
        : {}
      bot = WechatyBuilder.build({
        name: 'WechatEveryDay',
        puppet: 'wechaty-puppet-wechat4u', 
        //puppet: 'wechaty-puppet-wechat', 
        puppetOptions: {
          uos: true,
          ...CHROME_BIN,
        },
      })
    } else {
      bot = WechatyBuilder.build()
    }
    // 扫码
    bot.on('scan', onScan)
    // 登录
    bot.on('login', onLogin)
    // 登出
    bot.on('logout', onLogout)
    // 收到消息
    bot.on('message', onMessage)
    // 添加好友
    bot.on('friendship', onFriendShip)
    bot
      .start()
      .then(() => console.log('Start to log in wechat...'))
      .catch((e) => console.error(e))
  } catch (error) {
    console.log(error)
  }
}
相关推荐
喵叔哟17 分钟前
重构代码之取消临时字段
java·前端·重构
还是大剑师兰特1 小时前
D3的竞品有哪些,D3的优势,D3和echarts的对比
前端·javascript·echarts
王解1 小时前
【深度解析】CSS工程化全攻略(1)
前端·css
一只小白菜~1 小时前
web浏览器环境下使用window.open()打开PDF文件不是预览,而是下载文件?
前端·javascript·pdf·windowopen预览pdf
方才coding1 小时前
1小时构建Vue3知识体系之vue的生命周期函数
前端·javascript·vue.js
man20171 小时前
【2024最新】基于springboot+vue的闲一品交易平台lw+ppt
vue.js·spring boot·后端
阿征学IT1 小时前
vue过滤器初步使用
前端·javascript·vue.js
王哲晓1 小时前
第四十五章 Vue之Vuex模块化创建(module)
前端·javascript·vue.js
丶21361 小时前
【WEB】深入理解 CORS(跨域资源共享):原理、配置与常见问题
前端·架构·web
发现你走远了1 小时前
『VUE』25. 组件事件与v-model(详细图文注释)
前端·javascript·vue.js