Skip to content

多开管理

WeixinManager 提供统一管理多个微信客户端的能力,所有操作通过 PID 路由到对应实例。

基本用法

python
from pywxauto import WeixinManager, Event

wx = WeixinManager(background=True)

# 自动连接所有已登录的微信
# (构造时自动调用 connect_all)
print(wx.pids)  # [12345, 67890]

启动新客户端

python
# 启动并连接新微信实例
pid = wx.open()

# 指定安装路径
pid = wx.open(install_path="D:\\Weixin")

# 带登录回调
def my_login(login):
    login.enter()

pid = wx.open(on_login=my_login)

连接已有客户端

python
# 连接指定 PID 的微信
pid = wx.connect(12345)

# 连接所有已运行的微信
pids = wx.connect_all()

操作指定客户端

所有 Weixin 上的方法都可以通过 WeixinManager 调用,第一个参数为 PID:

python
# 发送消息
wx.send_text(pid1, "张三", "来自账号1")
wx.send_text(pid2, "李四", "来自账号2")

# 获取联系人资料
profile = wx.get_contact_profile(pid1, "张三")

# 设置群信息
wx.set_room_name(pid1, "工作群", "新群名")

获取 Weixin 实例

python
# 获取指定 PID 的 Weixin 实例
weixin = wx.get_weixin(pid1)
# 或使用索引语法
weixin = wx[pid1]

# 检查 PID 是否已连接
if pid1 in wx:
    print("已连接")

# 所有实例
print(wx.instances)  # {pid: Weixin, ...}

统一消息监听

python
from pywxauto import WeixinManager, Event

wx = WeixinManager(background=True)

@wx.on(Event.TEXT)
def on_text(weixin, chat, message):
    pid = message.pid
    print(f"[PID={pid}] {message.sender}: {message.content}")
    chat.send_text("自动回复")

# 为不同客户端注册不同的监听会话
wx.add_chat_listen(pid1, ["张三", "工作群A"])
wx.add_chat_listen(pid2, ["李四", "工作群B"])

# 统一运行
wx.run()

自动发现所有窗口

python
# 自动注册所有已打开的独立聊天窗口
wx.add_all_chat_listen()  # 对所有客户端
wx.add_all_chat_listen(pid1)  # 仅指定客户端

断开与关闭

python
# 断开连接(不关闭微信)
wx.disconnect(pid1)

# 关闭微信并断开
wx.close(pid1)

# 断开所有
wx.disconnect_all()

停止监听

python
# 从其他线程停止
wx.stop()

完整示例

python
from pywxauto import WeixinManager, Event

wx = WeixinManager(background=True, offscreen=True)

print(f"已连接 {len(wx)} 个微信客户端: {wx.pids}")

@wx.on(Event.ALL)
def on_message(weixin, chat, message):
    print(f"[{weixin.pid}] [{chat.chat_name}] "
          f"{message.type_label}: {message.sender} - {message.content}")

# 所有客户端自动监听已打开的独立窗口
wx.add_all_chat_listen()

wx.run(auto_scan=True)