在做微信私域运营或数据分析时,经常需要获取完整的通讯录信息。本文分享如何通过WTAPI云端接口,一键获取好友列表、群聊列表和公众号列表,并提供完整的Python实战代码。
一、业务场景分析
在实际项目中,我们经常需要这些通讯录数据:
- 好友管理:统计好友数量、分析好友增长趋势、批量打标签
- 群聊运营:获取管理的群列表、监控群成员变化、自动化群管理
- 数据备份:定期备份通讯录,防止重要联系人丢失
- 私域分析:分析好友分布、活跃度,指导运营策略
传统的微信网页版或本地Hook方案要么功能受限,要么稳定性差。WTAPI云端方案通过iPad/Mac协议,提供了完整且稳定的通讯录获取能力。
二、WTAPI通讯录接口详解
接口说明
WTAPI提供的通讯录接口非常简单,登录成功后只需一个HTTP请求:
GET /finder/v2/api/contacts/getContactList
Headers:
X-finder-TOKEN: your_token
X-finder-AppId: your_app_id
参数说明:
X-finder-TOKEN:在WTAPI控制台生成的身份凭证X-finder-AppId:登录成功后返回的设备ID,标识云端iPad/Mac实例
返回数据结构
{
"ret": 200,
"msg": "操作成功",
"data": {
"friends": [
"wxid_910acevfm2nb21",
"wxid_9299552988412",
"wxid_6bfguz79h8n122"
],
"chatrooms": [
"2180313478@chatroom",
"14358945067@chatroom"
],
"ghs": [
"gh_7aac992b0363",
"gh_d7293b5f14f4"
]
}
}
字段解析:
| 字段 | 说明 | 示例 |
|---|---|---|
friends | 好友列表(wxid格式) | wxid_xxxx |
chatrooms | 群聊列表(@chatroom结尾) | 数字@chatroom |
ghs | 公众号列表(gh_开头) | gh_xxxx |
三、Python实战代码
基础版:获取通讯录列表
import requests
class WTAPIClient:
def __init__(self, token, app_id, base_url="https://api.example.com"):
self.token = token
self.app_id = app_id
self.base_url = base_url
self.headers = {
"X-finder-TOKEN": token,
"X-finder-AppId": app_id
}
def get_contact_list(self):
"""获取通讯录列表(好友、群聊、公众号)"""
url = f"{self.base_url}/finder/v2/api/contacts/getContactList"
resp = requests.get(url, headers=self.headers).json()
if resp.get("ret") == 200:
data = resp["data"]
friends = data.get("friends", [])
chatrooms = data.get("chatrooms", [])
ghs = data.get("ghs", [])
print(f"✅ 通讯录获取成功")
print(f"👤 好友数量: {len(friends)}")
print(f"👥 群聊数量: {len(chatrooms)}")
print(f"📰 公众号数量: {len(ghs)}")
return {
"friends": friends,
"chatrooms": chatrooms,
"ghs": ghs
}
else:
print(f"❌ 获取失败: {resp.get('msg')}")
return None
# 使用示例
# 1. 先通过登录接口获取 app_id
# 2. 使用 token 和 app_id 初始化客户端
api = WTAPIClient(
token="your_wtapi_token",
app_id="wx_wR_U4zPj2M_OTS3BCyoE4"
)
contacts = api.get_contact_list()
进阶版:通讯录数据分析与导出
import json
import csv
from datetime import datetime
class WTAPIContactManager(WTAPIClient):
def export_to_csv(self, contacts, filename=None):
"""导出通讯录到CSV文件"""
if not filename:
filename = f"contacts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['类型', 'ID', '备注'])
# 写入好友
for wxid in contacts.get('friends', []):
writer.writerow(['好友', wxid, ''])
# 写入群聊
for room_id in contacts.get('chatrooms', []):
writer.writerow(['群聊', room_id, ''])
# 写入公众号
for gh_id in contacts.get('ghs', []):
writer.writerow(['公众号', gh_id, ''])
print(f"📁 通讯录已导出到: {filename}")
return filename
def analyze_contacts(self, contacts):
"""分析通讯录数据"""
friends = contacts.get('friends', [])
chatrooms = contacts.get('chatrooms', [])
ghs = contacts.get('ghs', [])
# 过滤系统账号
system_accounts = ['weixin', 'qqmail', 'qqsafe', 'medianote',
'tmessage', 'qmessage', 'exmail_tool']
real_friends = [f for f in friends if f not in system_accounts]
analysis = {
"统计时间": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"好友总数": len(friends),
"真实好友数": len(real_friends),
"系统账号数": len(friends) - len(real_friends),
"群聊数量": len(chatrooms),
"公众号数量": len(ghs),
"总联系人": len(friends) + len(chatrooms) + len(ghs)
}
print("\n📊 通讯录分析报告:")
print("-" * 30)
for key, value in analysis.items():
print(f"{key}: {value}")
return analysis
def get_chatroom_details(self, chatroom_id):
"""获取群聊详细信息(成员列表等)"""
url = f"{self.base_url}/finder/v2/api/chatroom/getChatroomInfo"
data = {"chatroomId": chatroom_id}
resp = requests.post(url, json=data, headers=self.headers).json()
return resp
# 使用示例
manager = WTAPIContactManager(
token="your_wtapi_token",
app_id="wx_wR_U4zPj2M_OTS3BCyoE4"
)
# 获取通讯录
contacts = manager.get_contact_list()
if contacts:
# 数据分析
manager.analyze_contacts(contacts)
# 导出CSV
manager.export_to_csv(contacts, "my_wechat_contacts.csv")
四、实战场景:私域数据看板
import time
import schedule
class PrivateDomainDashboard:
"""私域数据监控看板"""
def __init__(self, wtapi_client):
self.api = wtapi_client
self.history_data = []
def daily_snapshot(self):
"""每日数据快照"""
print(f"\n🕐 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 执行数据快照")
contacts = self.api.get_contact_list()
if contacts:
snapshot = {
"date": datetime.now().strftime('%Y-%m-%d'),
"friends_count": len(contacts['friends']),
"chatrooms_count": len(contacts['chatrooms']),
"timestamp": time.time()
}
self.history_data.append(snapshot)
# 计算增长
if len(self.history_data) >= 2:
yesterday = self.history_data[-2]
friend_growth = snapshot['friends_count'] - yesterday['friends_count']
print(f"📈 好友增长: {friend_growth:+d}")
# 保存数据
with open('private_domain_data.json', 'w', encoding='utf-8') as f:
json.dump(self.history_data, f, ensure_ascii=False, indent=2)
def run_scheduler(self):
"""定时任务:每天9点执行快照"""
schedule.every().day.at("09:00").do(self.daily_snapshot)
print("📅 定时任务已启动,每天9:00执行数据快照")
while True:
schedule.run_pending()
time.sleep(60)
# 启动监控
# dashboard = PrivateDomainDashboard(manager)
# dashboard.daily_snapshot() # 立即执行一次
# dashboard.run_scheduler() # 启动定时任务
五、避坑指南
1. 数据量大时的处理
- 如果好友数量超过5000,建议分页获取(如接口支持)
- 频繁调用可能触发限流,建议加缓存机制
2. wxid的使用
wxid_开头的是个人微信号原始ID- 部分老账号可能是QQ号或其他格式
- 调用其他接口时需要使用这些ID作为参数
3. 群聊ID特点
- 群聊ID格式为
数字@chatroom - 退出群聊后,该ID会失效
- 可通过群ID调用接口获取群成员列表
4. 数据安全
- 通讯录数据涉及隐私,务必做好加密存储
- 建议本地保存,不要上传到不安全的服务器
- 遵守相关法律法规,合法使用数据
六、扩展应用
基于通讯录接口,可以扩展实现:
- 好友去重:对比多个账号的通讯录,找出共同好友
- 群聊管理:批量获取群成员,分析群活跃度
- 标签系统:结合备注接口,实现好友分组管理
- 数据同步:定期备份通讯录到本地数据库
七、总结
WTAPI的通讯录接口设计简洁,返回数据结构化清晰,非常适合做私域数据管理和分析。配合定时任务,可以轻松搭建个人或企业的微信数据看板。
相比传统的本地Hook方案,WTAPI云端方案的优势在于:
- ✅ 无需维护本地环境,调用简单
- ✅ 云端iPad/Mac实例稳定在线
- ✅ 接口标准化,多语言支持
- ✅ 专注业务开发,无需关心协议层
八、相关资源
- 📖 WTAPI完整文档:weiti.apifox.cn
- 🔗 登录接口文档:获取
appId的完整流程 - 💬 技术支持:提供API对接咨询服务
WTAPI提供完整的微信云端API解决方案,包括登录、消息、通讯录、群聊等全套接口,助力开发者快速构建微信自动化应用。
本文仅作技术交流,请遵守微信相关使用规范,合法合规使用API服务。