node+微信+chatgpt 机器人集成

 

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)
  }
}

posted @ 2023-12-18 09:32  徐同保  阅读(7)  评论(0编辑  收藏  举报  来源