19 - FastGPT AI 机器人接入微信和企业微信

视频教程BV1Tp4y1n72T

视频链接BV1Tp4y1n72T
发布日期:2024-02-20
视频时长:16:35
播放量:8.1万
所属合集:FastGPT 教程系列

视频概要

完整演示将FastGPT机器人同时接入个人微信和企业微信。使用wechaty框架连接个人微信,通过企业微信API接入企业微信。覆盖两种接入方式的完整流程。


知识点清单

A. 个人微信接入(Wechaty)

知识点说明重要程度
Wechaty聊天机器人SDK,支持多平台★★★★★
PuppetWechaty的底层协议实现★★★★★
PadlocaliPad协议的Puppet,稳定可靠★★★★
TokenWechaty cloud服务的认证令牌★★★★
# 1. 安装Wechaty
npm install wechaty
npm install wechaty-puppet-padlocal

# 2. 创建机器人脚本

// wechat-bot.js
const { WechatyBuilder } = require('wechaty');
const { PuppetPadlocal } = require('wechaty-puppet-padlocal');
const axios = require('axios');

const FASTGPT_API = 'http://your-server:3000/api/v1/chat/completions';
const FASTGPT_TOKEN = 'Bearer fastgpt-xxx';

const bot = WechatyBuilder.build({
    name: 'AI-Bot',
    puppet: new PuppetPadlocal({
        token: 'your-padlocal-token'
    })
});

// 监听消息事件
bot.on('message', async (message) => {
    // 只处理文本消息,忽略自己发的
    if (message.text().length > 0 && !message.self()) {
        const reply = await askFastGPT(message.text(), message.talker().id);
        await message.say(reply);
    }
});

// 调用FastGPT API
async function askFastGPT(question, userId) {
    try {
        const res = await axios.post(FASTGPT_API, {
            chatId: userId,
            stream: false,
            messages: [{ role: 'user', content: question }]
        }, {
            headers: { 'Authorization': FASTGPT_TOKEN }
        });
        return res.data.choices[0].message.content;
    } catch (e) {
        return '抱歉,AI暂时无法回复,请稍后再试。';
    }
}

bot.start();
console.log('微信机器人已启动');

B. 企业微信接入

接入流程概览:
1. 企业微信管理后台创建应用
2. 获取企业ID、AgentId、Secret
3. 配置FastGPT外部接入
4. 设置消息回调URL
5. 测试对话

(详细步骤见第12集)

C. FastGPT API 对接

# API调用示例
curl -X POST http://your-server:3000/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer fastgpt-xxx" \
  -d '{
    "chatId": "user-001",
    "stream": false,
    "messages": [
      {
        "role": "user",
        "content": "你好,请介绍一下自己"
      }
    ]
  }'

D. 对比两种接入方式

维度个人微信(Wechaty)企业微信
稳定性有封号风险官方支持,稳定
部署难度需要额外Token服务直接配置API
成本Padlocal Token收费免费
适用场景个人/小团队企业正式使用
消息限制较少有配额限制
推荐度测试/个人用生产环境推荐

常见问题

问题解答
Wechaty Token怎么获取?在 pad-local.com 注册购买
个人微信会被封吗?有风险,建议用小号测试,不要频繁发消息
两种方式能同时用?可以,分别配置即可
消息回复太慢?检查网络延迟,考虑使用流式响应
群聊怎么接入?Wechaty监听room事件,企业微信配置群机器人

学习建议

  • 生产环境强烈推荐使用企业微信接入
  • Wechaty接入仅供测试学习,注意封号风险
  • API对接是最灵活的方式,适合有编程基础的用户
  • 建议先看完FastGPT基础教程再看本集
返回首页