五、使用示例 - chatautox
五、使用示例
使用前请先完成 环境配置和安装,并保证 微信 PC 客户端已登录、主窗口可见(不要最小化到托盘后直接跑脚本)。
下面每个示例都可以单独复制成 .py 文件运行。把示例里的会话名、路径、备注等改成你自己的即可。
通用约定:
1. 基本使用
做什么: 打开指定会话 → 查看当前窗口信息 → 发送一条文本 → 打印当前聊天里已有消息。
适用: 第一次跑通库、确认能控微信。
demo.py
from chatautox import WeChat
# 初始化微信实例(需微信已登录)
wx = WeChat()
# 切换到目标会话(先用「文件传输助手」最安全)
target = "文件传输助手"
wx.ChatWith(target)
# 查看当前窗口信息(聊天名、类型等)
chatinfo = wx.ChatInfo()
print(f"当前窗口信息:{chatinfo}")
# 发送消息:先确认当前会话确实是目标,避免发错人
if chatinfo.get('chat_name') == target:
wx.SendMsg("你好")
# 获取当前聊天窗口已加载的消息列表
msgs = wx.GetAllMessage()
for msg in msgs:
print(f"消息内容: {msg.content}, 消息类型: {msg.type}")
2. 监听消息
做什么: 弹出指定好友的独立聊天窗口,并持续监听新消息;对方发来文本时可自动回复。
适用: 需要长期挂机、按会话监听。
注意: AddListenChat 会打开独立聊天子窗口;程序结束前可用 RemoveListenChat 取消。KeepRunning() 会阻塞主线程保持运行。
from chatautox import WeChat
from chatautox.msgs import FriendMessage
wx = WeChat()
# 消息处理函数:每来一条消息都会调用
def on_message(msg, chat):
"""msg:消息对象;chat:该会话对应的 Chat 对象"""
print(f'收到来自 {chat} 的消息: {msg.content}', flush=True)
# 仅自动回复「对方发来」的消息(FriendMessage),避免自己回自己
if isinstance(msg, FriendMessage):
chat.SendMsg('收到')
# 添加监听:把「好友昵称」改成真实备注/昵称
wx.AddListenChat('好友昵称', on_message)
# 保持进程运行(阻塞)
wx.KeepRunning()
运行一段时间后取消监听:
# 按昵称移除监听
wx.RemoveListenChat(nickname="张三")
3. ✨处理好友申请
做什么: 读取通讯录里「可接受」的新的好友申请,并批量接受,同时设置备注、标签、权限。
适用: 需要自动通过好友请求。
注意: accept(...) 会真实添加好友并改资料,请先打印确认再调用。
accept_new_friend.py
from chatautox import WeChat
wx = WeChat()
# acceptable=True:只取当前可点击「接受」的申请
newfriends = wx.GetNewFriends(acceptable=True)
for friend in newfriends:
print(f'名字:{friend.name} 验证消息:{friend.msg}')
# 接受好友请求,并设置备注、标签、权限
friend.accept(remark='好友123', tags=['分组名'], permission='仅聊天')
4. ✨发送朋友圈
⚠️ 请谨慎使用,不建议频繁发送朋友圈,此行为可能会被认定过度营销而触发帐号风控!
做什么: 发布一条带文字与图片的朋友圈,并可设置可见范围(公开 / 白名单 / 黑名单)。
send_moment.py
from chatautox import WeChat
wx = WeChat()
text = '''oh
今天天气真好
适合出去走走
嘿嘿~
'''
# 本地图片绝对路径(文件必须存在)
media_files = [
r"D:\Images\Pictures\1.png",
r"D:\Images\Pictures\2.png",
r"D:\Images\Pictures\3.png",
]
privacy_config = {
'privacy': '白名单', # 也可用 '黑名单';公开则用空配置
'tags': ['家人', '朋友'] # 白名单:仅这些标签可见;黑名单:屏蔽这些标签
}
# privacy_config = {} # 公开发布,不限制可见范围
wx.PublishMoment(text, media_files, privacy_config)
5. 登录与基本信息
做什么: 检查登录窗口是否存在、当前是否在线、读取本机微信号基本资料,并切回聊天页。
说明: 扫码登录相关能力在 LoginWnd 上,不在 WeChat 上。已登录时通常直接用 WeChat() 即可。
login_info.py
from chatautox import WeChat
from chatautox.wx import LoginWnd
wx = WeChat()
# LoginWnd:登录/二维码窗口(未登录时才有用)
login_wnd = LoginWnd()
print('LoginWnd.exists:', login_wnd.exists(wait=3))
print('IsOnline:', wx.IsOnline()) # 是否已登录在线
print('GetMyInfo:', wx.GetMyInfo()) # 本机账号信息(昵称等)
# 如需保存登录二维码,取消注释并修改路径
# result = login_wnd.get_qrcode(path='qrcode.png')
# print('get_qrcode:', result)
wx.SwitchToChat() # 切到主界面「聊天」页
6. 会话与联系人
做什么: 读取左侧会话列表;可选读取最近群聊、联系人分组、好友详情。
注意: GetFriendDetails 可能较慢,建议先用较小的 n 试跑。
session_contact.py
from chatautox import WeChat
wx = WeChat()
# 获取会话列表(左侧聊天列表)
sessions = wx.GetSession()
print(f'会话数: {len(sessions or [])}')
for i, s in enumerate((sessions or [])[:20], 1):
print(f' [{i}] {s!r}')
# 可选(按需取消注释)
# groups = wx.GetAllRecentGroups() # 最近群聊
# contact_groups = wx.GetContactGroups() # 通讯录分组
# details = wx.GetFriendDetails(n=5, timeout=120) # 前 n 个好友详情
wx.SwitchToChat()
7. 发送消息 / 文件
做什么: 切入指定会话,发送文本;可选发送本地文件。
注意: 发文件前请确认路径存在;exact=False 表示搜索会话时允许模糊匹配。
send_msg_file.py
from chatautox import WeChat
wx = WeChat()
who = '文件传输助手'
# 先切换会话,再发送(也可以在 SendMsg 里直接传 who)
wx.ChatWith(who)
wx.SendMsg(msg='你好', who=who)
# 发送文件(按需修改为真实路径后取消注释)
# wx.SendFiles(filepath=r'C:\ces.txt', who=who, exact=False)
8. 好友与链接卡片
做什么: 查看好友申请列表;可选主动添加好友、发送链接卡片。
⚠️ AddNewFriend / SendUrlCard 会真实操作账号,示例默认注释。确认 keywords、friends 无误后再启用。
friend_url_card.py
from chatautox import WeChat
wx = WeChat()
# 获取可接受的好友申请(只读预览)
new_friends = wx.GetNewFriends(acceptable=True)
for friend in (new_friends or [])[:20]:
print(friend)
# 添加好友(危险操作,确认目标后再开)
# wx.AddNewFriend(
# keywords='张三', # 搜索关键字(微信号/手机号/昵称等)
# addmsg='你好,我是自动化测试', # 验证申请语
# remark='自动化测试', # 备注
# tags=['测试'], # 标签
# permission='仅聊天', # 权限
# timeout=8, # 超时秒数
# )
# 发送链接卡片(危险操作,确认目标后再开)
# wx.SendUrlCard(
# url='https://example.com', # 链接地址
# friends='文件传输助手', # 接收人(备注/昵称)
# message='这是一条链接卡片测试', # 附加留言(若界面支持)
# timeout=10,
# )
wx.SwitchToChat()
9. 创建笔记
做什么: 在收藏中创建一条笔记,并可选择转发给指定联系人。
说明: wx.create_note(content, forward_to) 不依赖聊天里已有笔记消息。forward_to 为空则只创建、不转发。更完整参数见 NoteMessage.create_note。
create_note.py
from chatautox import WeChat
wx = WeChat()
# 参数1:笔记正文;参数2:转发对象(备注/昵称)。只创建不转发可只传正文:
# result = wx.create_note('测试')
result = wx.create_note('测试', '123')
if result:
print('create_note 成功')
else:
print(f'create_note 失败: {result.get("message", result)}')
10. ✨轮询新消息(GetNextNewMessage)
做什么: 在主窗口循环调用 GetNextNewMessage,每来一条新消息立刻进入 callback,按 msg.type 分别处理(文本、引用、语音、图片、笔记、小程序等)。
为什么推荐: 不必为每个好友单独开监听窗口;适合统一处理主窗口未读。
关键字段:
笔记 / 小程序返回值说明: get_content(wait=...) 成功时返回有序列表:文本是 str,图片/视频/文件是 Path。wait 为窗口打开后的额外等待秒数,内容多时建议 3~10。
get_next_new_message.py
from chatautox import WeChat
from chatautox.param import WxResponse
from pathlib import Path
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
log = logging.info
wx = WeChat()
def _print_fail(label, result):
# 失败时库常返回 WxResponse,而不是空列表
if isinstance(result, WxResponse):
print(f'[{label}] 失败: {result.get("message", result)}')
return True
return False
def _print_note_items(items):
"""笔记/小程序 get_content:str 文本 + Path 文件路径。"""
for content in (items or []):
if isinstance(content, str):
print(content)
elif isinstance(content, Path):
print('文件路径:', content)
def on_message(msg):
"""每条消息在 GetNextNewMessage 交付时立即处理。"""
log(f'收到消息 type:{msg.type} 归属:{msg.attr} 发送者:{msg.sender} 内容: {msg.content}')
mtype = getattr(msg, 'type', None)
if mtype == 'text':
print(f'[文本] {msg.content}')
elif mtype == 'quote':
print(f'[引用] 正文: {msg.content}')
qc = getattr(msg, 'quote_content', None) # 被引用的内容
qn = getattr(msg, 'quote_nickname', None) # 被引用方昵称
if qc or qn:
print(f' 被引用: {qn or ""} — {qc or ""}')
# 被引用为图片/视频时可下载:
# path = msg.download_quote_image(timeout=20)
elif mtype == 'voice':
print(f'[语音] {msg.content}')
if hasattr(msg, 'to_text'):
text = msg.to_text()
log(f'语音转文字:{text}')
elif mtype in ('image', 'video', 'file'):
label = {'image': '图片', 'video': '视频', 'file': '文件'}.get(mtype, mtype)
# timeout:下载超时秒数;大文件可加大
path = msg.download(timeout=90 if mtype == 'file' else 25)
log(f'{label}下载:{path}')
elif mtype == 'link':
print(f'[链接] {msg.content}')
if hasattr(msg, 'get_url'):
detail = msg.get_url(timeout=15, with_content=True)
log(f'链接详情:{detail}')
elif mtype == 'merge':
result = msg.get_messages()
print('[合并]', result)
elif mtype == 'note':
# wait:笔记窗口打开后等待加载完成(内容较多可加大,如 wait=10)
result = msg.get_content(wait=3)
if not _print_fail('笔记', result):
_print_note_items(result)
elif mtype == 'miniapp':
# 先识别是否为内置可解析的小程序
if not getattr(msg, 'identify_kind', lambda: None)():
print(f'[MiniApp] 未内置支持: {msg.content}')
else:
result = msg.get_content(wait=3)
if not _print_fail('小程序', result):
_print_note_items(result)
else:
print(f'[其他 {mtype}] {getattr(msg, "content", "")}')
while True:
batch = wx.GetNextNewMessage(
filter_mute=False, # False:含免打扰会话;True:跳过免打扰
fetch_sender=False, # True:群聊补全发送者(更慢)
callback=on_message, # 每条消息立即回调
)
msgs = batch.get('msg') or []
if msgs:
log(f'本轮共收到 {len(msgs)} 条,来自 {batch.get("chat_name")} ({batch.get("chat_type")})')
time.sleep(1) # 轮询间隔,可按需要调整
更多类型说明见 消息处理指南。
11. 引用消息 / 笔记 / 合并消息
做什么: 同一轮询里演示三件常用事:
- 文本以
@ 开头时,调用 msg.quote(...) 引用回复
type == 'note' 时用 get_content(wait=...) 解析笔记(str / Path)
type == 'merge' 时用 get_messages() 解析合并转发
quote_note_merge.py
from chatautox import WeChat
from chatautox.param import WxResponse
from pathlib import Path
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
log = logging.info
wx = WeChat()
chat = None
def on_message(msg):
global chat
log(f'收到消息 发送者:{msg.sender} 内容: {msg.content}')
# 1) 引用回复:这里用「以 @ 开头」作为演示条件,可按业务改成别的判断
if msg.type == 'text' and (msg.content or '').startswith('@'):
msg.quote(msg.content) # 引用当前消息并发送内容
# 2) 解析笔记
# wait:笔记窗口打开后额外等待,确保图文加载完再复制
# 返回值:list,元素为 str(文本)或 Path(本地文件路径)
if msg.type == 'note':
note_content_list = msg.get_content(wait=3)
if isinstance(note_content_list, WxResponse):
print('笔记失败:', note_content_list.get('message'))
else:
print('收到笔记消息,解析:')
for content in note_content_list:
if isinstance(content, str):
# 文本内容
print(content)
elif isinstance(content, Path):
# 文件、视频、图片等本地路径
print('文件路径:', content)
# 3) 解析合并转发
if msg.type == 'merge':
items = msg.get_messages()
print('收到合并消息,解析:')
for item in (items or []):
print(item)
while True:
batch = wx.GetNextNewMessage(
filter_mute=False,
fetch_sender=True, # 需要发送者信息时打开
callback=on_message,
)
chat = batch.get('chat_name')
msgs = batch.get('msg')
if msgs:
log(f'本轮共收到 {len(msgs)} 条,来自 {chat} ({batch.get("chat_type")})')
time.sleep(1)