微信接入中国移动 AI 助手的智能机器人实现方案

Java和Python两种语言的实现方式。

方案一:基于微信公众号的Java实现

这个方案使用Java语言,通过微信公众号的开发者模式接入AI机器人。

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import okhttp3.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@XStreamAlias("xml")
public class TextMessage {
    @XStreamAlias("ToUserName")
    private String toUserName;
    @XStreamAlias("FromUserName")
    private String fromUserName;
    @XStreamAlias("CreateTime")
    private String createTime;
    @XStreamAlias("MsgType")
    private String msgType;
    @XStreamAlias("Content")
    private String content;

    public TextMessage(Map<String, String> requestMap, String content) {
        this.toUserName = requestMap.get("FromUserName");
        this.fromUserName = requestMap.get("ToUserName");
        this.createTime = System.currentTimeMillis() / 1000 + "";
        this.msgType = "text";
        this.content = content;
    }
}

public class WeChatServlet extends HttpServlet {
    private static final String AI_API_URL = " http://api.ai.10086.cn/v1/chat "; // 中国移动AI助手API地址
    private static final String API_KEY = "your_api_key"; // 替换为你的中国移动AI助手API密钥

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 解析微信发送的XML数据
        Map<String, String> requestMap = parseRequest(request.getInputStream());
        
        // 获取用户发送的消息内容
        String userMessage = requestMap.get("Content");
        
        // 调用中国移动AI助手API获取回复
        String aiReply = getAIResponse(userMessage);
        
        // 构建返回给微信的XML消息
        TextMessage textMessage = new TextMessage(requestMap, aiReply);
        XStream xstream = new XStream();
        xstream.processAnnotations(TextMessage.class);
        String xml = xstream.toXML(textMessage);
        
        // 返回响应
        response.setContentType("application/xml;charset=UTF-8");
        response.getWriter().write(xml);
    }

    private Map<String, String> parseRequest(InputStream is) throws Exception {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getStringValue());
        }
        return map;
    }

    private String getAIResponse(String message) {
        try {
            OkHttpClient client = new OkHttpClient();
            
            // 构建请求体
            MediaType mediaType = MediaType.parse("application/json");
            String requestBody = "{\"question\":\"" + message + "\",\"apikey\":\"" + API_KEY + "\"}";
            RequestBody body = RequestBody.create(mediaType, requestBody);
            
            // 构建请求
            Request request = new Request.Builder()
                    .url(AI_API_URL)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            
            // 解析响应,获取AI回复内容
            // 假设返回格式为 {"code":0,"data":{"answer":"回复内容"}}
            Map<String, Object> result = JSON.parseObject(responseBody, Map.class);
            if (result.get("code").equals(0)) {
                Map<String, String> data = (Map<String, String>) result.get("data");
                return data.get("answer");
            }
            return "抱歉,AI助手暂时无法回答您的问题";
        } catch (Exception e) {
            e.printStackTrace();
            return "系统繁忙,请稍后再试";
        }
    }
}

实现说明

  1. 这个方案使用了微信公众号的开发者模式,需要在微信公众平台配置服务器地址

  2. 核心是通过解析微信发送的XML消息,调用中国移动AI助手API获取回复,再构建XML格式的响应返回给微信

  3. 需要添加以下依赖:

    • dom4j: 解析微信发送的XML数据

    • xstream: 构建返回的XML

    • okhttp: 发送HTTP请求调用AI API

    • fastjson: 处理JSON数据

方案二:基于Python的自动化实现

这个方案使用Python语言,通过模拟用户操作实现微信AI机器人。

import requests
import json
import time
import random
from uiautomation import WindowControl

# 中国移动AI助手API配置
AI_API_URL = " http://api.ai.10086.cn/v1/chat "
API_KEY = "your_api_key"  # 替换为你的中国移动AI助手API密钥

# 绑定微信主窗口
wx = WindowControl(Name='微信', searchDepth=1)
wx.SwitchToThisWindow()

# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')

# 定义需要监听的联系人或群列表
listen_list = ["张三", "李四", "工作群"]

# 给每一个列表联系人添加监听设置
for contact in listen_list:
    wx.AddListenChat(who=contact)

# 存储不同用户的上下文
user_contexts = {}

while True:
    # 从查找未读消息
    we = hw.TextControl(searchDepth=4)
    
    # 等待消息
    while not we.Exists():
        time.sleep(1)
    
    # 存在未读消息
    if we.Name:
        # 点击未读消息
        we.Click(simulateMove=False)
        
        # 读取最后一条消息
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        print("收到消息:", last_msg)
        
        # 获取发送者名称
        sender = wx.TextControl(searchDepth=3).Name
        
        # 调用中国移动AI助手API
        try:
            headers = {'Content-Type': 'application/json'}
            data = {
                'question': last_msg,
                'apikey': API_KEY
            }
            
            # 添加随机延迟,避免频繁操作
            time.sleep(random.uniform(1, 3))
            
            response = requests.post(AI_API_URL, headers=headers, data=json.dumps(data))
            response_data = response.json()
            
            if response_data.get('code') == 0:
                ai_reply = response_data['data']['answer']
            else:
                ai_reply = "抱歉,AI助手暂时无法回答您的问题"
                
            print("AI回复:", ai_reply)
            
            # 发送消息前加上延时
            time.sleep(2)
            
            # 发送回复
            wx.SendKeys(ai_reply, waitTime=1)
            wx.SendKeys('{Enter}', waitTime=1)
            
        except Exception as e:
            print("调用AI API出错:", str(e))
            wx.SendKeys("系统繁忙,请稍后再试", waitTime=1)
            wx.SendKeys('{Enter}', waitTime=1)

实现说明

  1. 这个方案使用uiautomation库模拟用户操作微信客户端

  2. 可以监听指定的联系人或群聊,当有新消息时自动调用AI接口并回复

  3. 添加了随机延迟和错误处理,避免操作过于频繁导致微信限制

  4. 可以实现简单的上下文记忆功能

方案三:基于企业微信的智能客服实现

如果需要为企业微信接入中国移动AI助手,可以参考以下步骤:

  1. 在企业微信后台开通机器人客服功能

  2. 在管理中心配置"微信"渠道使用机器人

  3. 绑定企业微信与AI服务接口

  4. 配置机器人接待策略和转人工功能

企业微信的API接入方式与微信公众号类似,可以参考方案一的代码结构,但需要使用企业微信的API接口。

注意事项

  1. 微信官方对自动化操作有限制,频繁操作可能导致账号受限

  2. 中国移动AI助手的API需要申请合法的API Key

  3. 对于生产环境使用,建议通过微信官方对话开放平台接入

  4. 如果要处理图片、语音等多模态消息,需要更复杂的实现

进阶功能

如果需要更高级的功能,如多模态处理、上下文记忆等,可以参考以下建议:

  1. 使用微信对话开放平台提供的完整解决方案

  2. 实现类似DeepSeek R1的多模态处理能力

  3. 添加更完善的上下文管理机制

  4. 考虑使用微信官方的智能对话API


微信接入中国移动 AI 助手的智能机器人实现方案
https://uniomo.com/archives/wei-xin-jie-ru-zhong-guo-yi-dong-ai-zhu-shou-de-zhi-neng-ji-qi-ren-shi-xian-fang-an
作者
雨落秋垣
发布于
2025年10月07日
许可协议