WeChatAPI Labs

ChatGPT 接入微信:搭建 AI 微信机器人

用个人微信 API 或企业微信 API 搭建 AI 客服和智能助手:架构、示例代码和上线建议。

更新时间: 2026-11-26

一句话答案:ChatGPT 接入微信的做法是:订阅消息回调,把用户消息和上下文交给大模型生成回复,再调用发送接口发回微信。整个链路通常在 1–3 秒内完成。

架构

  1. 托管账号收到消息,推送 message.received 到你的回调地址。
  2. 你的服务校验签名,判断是否需要回复(私聊,或群里 @ 了机器人)。
  3. 读取该用户最近几轮对话和知识库内容,调用 ChatGPT 等大模型 API 生成回复。
  4. 调用 send_text 发回原会话;需要人工时转给客服并打标签。

示例代码(Python)

import hmac, hashlib, requests
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = b"YOUR_CALLBACK_SECRET"
HEADERS = {"Authorization": "Bearer YOUR_API_KEY"}

def ask_llm(user_text, history):
    # 换成你使用的大模型 API,传入系统提示词、知识库片段和历史对话
    return "这是 AI 的回复"

@app.post("/callback")
def callback():
    sig = hmac.new(SECRET, request.data, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sig, request.headers.get("X-Signature", "")):
        abort(401)
    evt = request.get_json()
    d = evt.get("data", {})
    if evt["event"] == "message.received" and d.get("type") == "text":
        if d.get("room_id") and not d.get("at_me"):
            return {"ok": True}               # 群里没 @ 机器人就不回复
        reply = ask_llm(d["content"], history=[])
        requests.post("https://api.wechatapilabs.com/v1/message/send_text", headers=HEADERS, json={
            "account_id": evt["account_id"],
            "to": d.get("room_id") or d["from"],
            "content": reply,
        }, timeout=10)
    return {"ok": True}

上线建议

  • 回调要在 5 秒内返回,大模型调用放到异步队列里处理。
  • 微信机器人回复前加 1–3 秒随机延迟,更像真人,也能降低风控概率。
  • 设置转人工关键词,例如“人工”“投诉”,命中后停止自动回复。
  • 为每个会话保存最近若干轮对话作为上下文,并设置过期时间。

官方接口满足不了你的需求?看看个人微信与企业微信 API。

相关阅读: 微信 API 有哪些?公众号、小程序、支付、开放平台与企业微信全景指南 · 企业微信机器人 Webhook 发送消息教程 · 个人微信能调用 API 吗?官方边界与可选方案