node + 微信 + chatgpt(在微信里使用chatgpt)

1、微信群里按照【gpt,xxx】这个格式可以向gpt3.5提问
2、加机器人好友使用【gpt4,xxx】这个格式可以向gpt4提问,按照【gpt,xxx】这个格式可以向gpt3.5提问
 

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}

### 温馨提示        
#### 请按照下面的步骤绑定微信
1. 登录网站
2. 点击【我的】
3. 点击【昵称】
4. 在绑定微信文本框输入:${alias}
5. 点击【提交】
#### 绑定微信的好处
1. 提问支持上下文
2. 提问次数增多
3. 不会再出现这段提示
备注:如果遇到问题,请联系管理员`)
            }
          } 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', // 如果有token,记得更换对应的puppet
        //puppet: 'wechaty-puppet-wechat', // 如果 wechaty-puppet-wechat 存在问题,也可以尝试使用上面的 wechaty-puppet-wechat4u ,记得安装 wechaty-puppet-wechat4u
        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)
  }
}

参考链接:

https://chat.xutongbao.top/

https://github.com/wangrongding/wechat-bot

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