- macOS Accessibility API 详解 - WeChat-MCP 项目分析 - macOS 微信自动化代码示例 - Windows/macOS 双平台对比 - 混合架构推荐方案 - 微信版本兼容性说明
微信 macOS 端自动化
核心技术:macOS Accessibility API
macOS 原生的无障碍 API,类似于 Windows 的 UIAutomation,是苹果官方提供的 UI 自动化接口。
macOS Accessibility API
↓
读取微信窗口的 UI 树
↓
提取:联系人列表、聊天内容、输入框
↓
操作:点击、输入、发送
工作原理
微信 macOS 窗口
├── 左侧联系人列表 (Outline)
│ └── 联系人项 (Row)
│ ├── 头像 (Image)
│ ├── 名称 (StaticText)
│ └── 最新消息 (StaticText)
├── 右侧聊天区域
│ ├── 消息列表 (ScrollArea → Table)
│ │ ├── 对方消息气泡
│ │ └── 我的消息气泡
│ ├── 输入框 (TextField)
│ └── 发送按钮 (Button)
现有开源项目
1. WeChat-MCP ⭐ 133
链接: https://github.com/Open-organization/WeChat-MCP
技术栈: Python + pyobjc + AXUIElement API
功能:
- 导航到任意聊天
- 读取当前可见消息
- 发送文本消息
- MCP 协议集成
核心代码:
# 通过 pyobjc 调用 AXUIElement API
from AppKit import AXUIElement
# 获取微信应用
wechat = AXUIElementCreateApplication(pid)
# 遍历控件树
def get_children(element):
children = []
AXUIElementCopyAttributeValue(element, kAXChildrenAttribute, children)
return children
# 读取消息列表
def get_messages():
# 找到消息表格
table = find_element(wechat, "消息列表")
rows = get_children(table)
messages = []
for row in rows:
text = get_element_value(row, kAXValueAttribute)
messages.append(text)
return messages
2. macos-wechat-cli
链接: https://github.com/ginqi7/macos-wechat-cli
技术栈: Swift + Accessibility API
功能:
- CLI 命令行操作微信
- 查找联系人
- 发送消息
- Emacs 集成
命令示例:
# 查找联系人
wechat-cli search "张三"
# 发送消息
wechat-cli send "张三" "你好"
# 获取当前聊天消息
wechat-cli messages
技术实现详解
1. 环境准备
# 确保微信已开启辅助功能权限
# 系统设置 → 隐私与安全性 → 辅助功能 → 启用微信
2. 获取微信窗口
from ApplicationServices import AXUIElementCreateApplication
import psutil
# 获取微信 PID
def get_wechat_pid():
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == 'WeChat':
return proc.info['pid']
return None
pid = get_wechat_pid()
wechat = AXUIElementCreateApplication(pid)
3. 遍历 UI 树
# macOS 的 AXUIElement 属性
kAXRoleAttribute # 元素角色 (Button, TextField, etc.)
kAXTitleAttribute # 元素标题
kAXValueAttribute # 元素值(文本内容)
kAXPositionAttribute # 元素位置
kAXSizeAttribute # 元素大小
kAXChildrenAttribute # 子元素列表
# 递归遍历
def print_tree(element, depth=0):
role = get_attr(element, kAXRoleAttribute)
title = get_attr(element, kAXTitleAttribute)
value = get_attr(element, kAXValueAttribute)
print(" " * depth + f"{role}: {title or value}")
children = get_children(element)
for child in children:
print_tree(child, depth + 1)
4. 发送消息
# 方法1: 设置输入框文本
input_box = find_element(wechat, "input")
AXUIElementSetAttributeValue(input_box, kAXValueAttribute, "Hello!")
# 方法2: 模拟键盘输入
from Quartz import CGEventCreateKeyboardEvent, CGEventPost
# 生成回车键事件
enter_key = 36 # CGKeyCode for Return
event = CGEventCreateKeyboardEvent(None, enter_key, True)
CGEventPost(kCGHIDEventTap, event)
5. 查找并进入聊天
# 找到搜索框
search_box = find_element(wechat, "搜索")
AXUIElementSetAttributeValue(search_box, kAXValueAttribute, "张三")
# 等待搜索结果出现
time.sleep(0.5)
# 点击第一个搜索结果
result = find_element(wechat, "搜索结果项")
AXUIElementPerformAction(result, kAXPressAction)
两种方案对比
| 方案 | 消息获取 | 消息发送 | 稳定性 | 难度 |
|---|---|---|---|---|
| Accessibility API | ✅ 直接读文本 | ✅ 点击/输入 | 高 | 中 |
| 数据库直解密 | ✅ 全量历史 | ❌ 需配合API | 高 | 高 |
| 截图 + OCR | ⚠️ 慢/不准 | ❌ | 低 | 低 |
推荐架构:混合方案
┌─────────────────────────────────────────┐
│ macOS 微信自动化 │
├─────────────────────────────────────────┤
│ │
│ 消息接收: chatlog-bot (数据库Webhook) │
│ ↓ │
│ 收到新消息 → AI处理 │
│ ↓ │
│ 消息发送: WeChat-MCP / Accessibility │
│ │
└─────────────────────────────────────────┘
优势
- 消息读取准确:数据库解密获取全量历史,不依赖 UI 状态
- 发送实时灵活:Accessibility API 直接操作界面
- 风险低:不需要 Hook,接近零封号风险
项目集成
WeChat-MCP + AI Agent
# WeChat-MCP 支持 MCP 协议
# 可以直接对接 LangChain / CrewAI 等 Agent 框架
from langchain.agents import Agent
from mcp import WeChatMCPClient
wechat = WeChatMCPClient()
agent = Agent(
tools=[wechat.search_contact, wechat.send_message, wechat.get_messages],
prompt="你是微信助手,帮我回复客户消息"
)
# 自动执行
agent.run("帮我给张三发一条消息:你好")
⚠️ 注意事项
1. 微信版本适配
- 3.8.x: 兼容性最好
- 4.0+: UI 结构变化大,Accessibility 操作受限
- 建议锁定微信版本,避免自动更新破坏功能
2. SIP 限制
- 某些高级功能需要关闭 SIP (System Integrity Protection)
- 普通 Accessibility 功能不需要
3. 权限配置
# 必须在系统设置中开启
# 系统设置 → 隐私与安全性 → 辅助功能 → 微信 ✓
4. 稳定性
- 微信升级后 UI 可能变化,需要适配
- 建议监控微信版本,升级时及时测试
参考项目
| 项目 | 语言 | Stars | 方案 |
|---|---|---|---|
| WeChat-MCP | Python | 133 | Accessibility API + MCP |
| macos-wechat-cli | Swift | - | Accessibility API |
| chatlog-bot | Python | 22 | 数据库 + Webhook |
与 Windows UIAutomation 对比
| 维度 | macOS | Windows |
|---|---|---|
| API | AXUIElement | UIAutomation |
| 语言 | Swift / Python | Python / C# |
| 消息读取 | 数据库方案成熟 | UIA 直读 |
| 发送 | AXUIElement | UIA 直操作 |
| 生态工具 | WeChat-MCP | pywinauto |