### Install wxauto Source: https://context7.com/cluic/wxauto/llms.txt Install the wxauto library using pip. This command installs the latest version of the library and its dependencies. ```bash pip install wxauto ``` -------------------------------- ### StartListening Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Starts the message listening service. This should be called after setting up any listeners. ```APIDOC ## StartListening ### Description Starts the message listening service. This should be called after setting up any listeners. ### Method `StartListening()` ### Endpoint N/A (Method Call) ### Parameters None ### Response None ### Request Example ```python wx.StartListening() ``` ``` -------------------------------- ### Getting Multiple Login Windows Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Demonstrates how to get a list of all WeChat login windows and how to close them. ```APIDOC ## Getting Multiple Login Windows ### Description Retrieves a list of all WeChat login windows and provides an example of how to close them. ### Method ```python from wxauto import get_wx_logins # Get all WeChat login windows login_windows = get_wx_logins() # Close all login windows for login_window in login_windows: login_window.close() # Close ``` ``` -------------------------------- ### Auto-Login Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Provides an example of how to use the LoginWnd class to automatically log in to WeChat. ```APIDOC ## Auto-Login ### Description Automates the WeChat login process using the LoginWnd class. ### Method ```python from wxauto import LoginWnd wxpath = "D:/path/to/WeChat.exe" # Create login window loginwnd = LoginWnd(wxpath) # Login to WeChat loginwnd.login() ``` ``` -------------------------------- ### Start Message Listening Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Begin the process of listening for incoming messages. This should be called after setting up any desired chat listeners. ```python wx.StartListening() ``` -------------------------------- ### Getting Multiple WeChat Clients Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Shows how to retrieve a list of all running WeChat client instances on the system. ```APIDOC ## Getting Multiple WeChat Clients ### Description Retrieves a list of all running WeChat client instances. ### Method ```python from wxauto import get_wx_clients # Get all WeChat clients clients = get_wx_clients() for client in clients: print(f"WeChat client: {client}") ``` ``` -------------------------------- ### Message Listening and Handling Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Shows how to set up a message listener that processes incoming messages using a callback function. It includes examples of logging messages, auto-downloading media, and auto-replying. ```APIDOC ## Listening for Messages ### Description Sets up a listener to process incoming messages with a callback function. Includes examples for logging, media download, and auto-reply. ### Method ```python from wxauto import WeChat from wxauto.msgs import FriendMessage import time wx = WeChat() # Message processing function def on_message(msg, chat): # Example 1: Log messages to a local file with open('msgs.txt', 'a', encoding='utf-8') as f: f.write(msg.content + '\n') # Example 2: Automatically download images and videos if msg.type in ('image', 'video'): print(msg.download()) # Example 3: Auto-reply to received messages if isinstance(msg, FriendMessage): msg.quote('Received') # ... other processing logic can be implemented using Message class methods ... # Add listener, messages received will be processed by on_message function wx.AddListenChat(nickname="Zhang San", callback=on_message) # Keep the program running wx.KeepRunning() ``` ### Removing a Listener ```python # ... After the program has been running for a while ... # Remove listener wx.RemoveListenChat(nickname="Zhang San") ``` ``` -------------------------------- ### Initialize WeChat and Get Moments Window Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md Initializes the WeChat client and obtains the Moments window object. Ensure Moments is enabled on your mobile device. ```python from wxauto import WeChat wx = WeChat() pyq = wx.Moments() # 打开朋友圈并获取朋友圈窗口对象(如果为None则说明你没开启朋友圈,需要在手机端设置) ``` -------------------------------- ### Get All Sub-Window Instances Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieve a list of all currently open chat window instances. This is useful for managing multiple chats. ```python chats = wx.GetAllSubWindow() ``` -------------------------------- ### Basic Message Handling Example Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Demonstrates how to check message attributes and reply to messages. It shows two ways to identify a friend's message: by checking the 'attr' property or by using isinstance with FriendMessage. ```python from wxauto.msgs import * ... # 省略获取消息对象的过程 # 假设你获取到了一个消息对象 msg = ... # 当消息为好友消息时,回复收到 # 方法一: if msg.attr == 'friend': msg.reply('收到') # 方法二: if isinstance(msg, FriendMessage): msg.reply('收到') ``` -------------------------------- ### Get Sub-Window Instance Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Obtain a specific chat window instance by its nickname. This allows for direct interaction with that chat. ```python chat = wx.GetSubWindow(nickname="张三") ``` -------------------------------- ### Get All Messages Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves all messages from the current chat window. ```APIDOC ### 获取当前聊天窗口的所有消息 GetAllMessage ```python messages = wx.GetAllMessage() ``` **返回值**: - 类型:List[[Message](#message-类方法)] - 描述:当前聊天窗口的所有消息 ``` -------------------------------- ### Getting Login QR Code Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Shows how to obtain the path to the login QR code image for WeChat authentication. ```APIDOC ## Getting Login QR Code ### Description Retrieves the path to the login QR code image for WeChat authentication. ### Method ```python from wxauto import LoginWnd wxpath = "D:/path/to/WeChat.exe" # Create login window loginwnd = LoginWnd(wxpath) # Get login QR code image path qrcode_path = loginwnd.get_qrcode() print(qrcode) ``` ``` -------------------------------- ### Get Chat Info Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves information about the current chat window. ```APIDOC ### 获取聊天窗口信息 ChatInfo ```python info = chat.ChatInfo() ``` **返回值**: - 类型:`dict` - 描述:聊天窗口信息 - 返回值示例: ```python # 好友 {'chat_type': 'friend', 'chat_name': '张三'} # 群聊 {'group_member_count': 500, 'chat_type': 'group', 'chat_name': '工作群'} # 客服 {'company': '@肯德基', 'chat_type': 'service', 'chat_name': '店长xxx'} # 公众号 {'chat_type': 'official', 'chat_name': '肯德基'} ``` ``` -------------------------------- ### Get Moment Details Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md Retrieves detailed information about a moment, including sender, content, time, images, comments, and likes. ```APIDOC ### 获取朋友圈内容 ```python # 获取朋友圈内容 info = moment.info # { # 'type': 'moment', # 类型,分为`朋友圈`和`广告` # 'id': '4236572776458165', # ID # 'sender': '天天鲜花2号客服', # 发送者 # 'content': '客订花束', # 内容,就是朋友圈的文字内容,如果没有文字内容则为空字符串 # 'time': '4分钟前', # 发送时间 # 'img_count': 3, # 图片数量 # 'comments': [], # 评论 # 'addr': '', # 发送位置 # 'likes': [] # 点赞 # } moment.sender # '天天鲜花2号客服' moment.content # '客订花束' moment.time # '4分钟前' # info中所有的键值对都可以通过对象的属性来获取,就不一一列举了 ... ``` ``` -------------------------------- ### Get and Operate Sub-Windows (Chat Windows) Source: https://context7.com/cluic/wxauto/llms.txt Retrieves and operates on popped-out independent chat sub-windows. Ensure the sub-window is opened first, e.g., by double-clicking a session. Use `GetSubWindow` for a specific chat or `GetAllSubWindow` for all open chats. ```python from wxauto import WeChat wx = WeChat() # 先通过 ChatWith + 双击 弹出子窗口 wx.ChatWith("张三") sessions = wx.GetSession() sessions[0].double_click() # 获取指定子窗口 chat = wx.GetSubWindow(nickname="张三") print(f"聊天对象: {chat.who}") print(f"聊天类型: {chat.chat_type}") # friend / group / service / official # 获取窗口信息 info = chat.ChatInfo() # 好友:{'chat_type': 'friend', 'chat_name': '张三'} # 群聊:{'group_member_count': 100, 'chat_type': 'group', 'chat_name': '项目群'} print(info) # 在子窗口发送消息 chat.SendMsg("你好!") # 获取所有子窗口 all_chats = wx.GetAllSubWindow() for c in all_chats: print(c.who, c.chat_type) ``` -------------------------------- ### Basic Usage: Sending Messages and Getting Chat History Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Demonstrates how to initialize a WeChat instance, send a message to a specific contact, and retrieve all messages from the current chat window. ```APIDOC ## Basic Usage ### Description Initializes a WeChat instance, sends a message to a specified contact, and retrieves all messages from the current chat window. ### Method ```python from wxauto import WeChat # Initialize WeChat instance wx = WeChat() # Send a message wx.SendMsg("Hello", who="Zhang San") # Get current chat window messages msgs = wx.GetAllMessage() for msg in msgs: print(f"Message content: {msg.content}, Message type: {msg.type}") ``` ``` -------------------------------- ### Get Multiple WeChat Clients Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Retrieve a list of all running WeChat client instances. Useful for managing multiple WeChat accounts or applications. ```python from wxauto import get_wx_clients # Get all WeChat clients clients = get_wx_clients() for client in clients: print(f"微信客户端: {client}") ``` -------------------------------- ### Get My Information Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves your own WeChat information, such as your WeChat ID. ```python wx.GetMyInfo() ``` -------------------------------- ### Get All Messages Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves all messages from the current chat window. The return type is a list of Message objects. ```python messages = wx.GetAllMessage() ``` -------------------------------- ### Get Sender Information Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Retrieve information about the sender of the message. Returns a dictionary of sender details. ```python msg.sender_info() ``` -------------------------------- ### Get Multiple WeChat Login Windows Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Retrieve all active WeChat login windows. Allows for programmatic closing or management of these windows. ```python from wxauto import get_wx_logins # Get all WeChat client instances login_windows = get_wx_logins() # Close all login windows for login_window in login_windows: login_window.close() # Close ``` -------------------------------- ### Get Current Session List Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieve a list of all current chat sessions. Each session object contains information about the chat. ```python sessions = wx.GetSession() for session in sessions: print(session.info) ``` -------------------------------- ### Get Moments Content Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md Retrieves moments content from the current page or the next page. Adjust scroll speeds for optimal performance. ```python # 获取当前页面的朋友圈内容 moments = pyq.GetMoments() # 通过`next_page`参数获取下一页的朋友圈内容 moments = pyq.GetMoments(next_page=True) ``` -------------------------------- ### Get Chat Information Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Fetches detailed information about the current chat window, including its type and name, and specific details like group member count or company for service accounts. ```python info = chat.ChatInfo() ``` -------------------------------- ### Get New Friend Requests Source: https://context7.com/cluic/wxauto/llms.txt Retrieves a list of pending friend requests. Allows for batch approval of requests and setting remarks and tags for new friends. ```python from wxauto import WeChat wx = WeChat() ``` -------------------------------- ### Get First 10 Friend Details Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves detailed information for the first 10 friends. Be aware that this operation can be time-consuming, approximately 0.5-1 second per friend. For large friend lists, consider setting a smaller 'n' value initially. Note that encountering offline enterprise WeChat friends may cause the client to freeze. ```python messages = wx.GetFriendDetails(n=10) ``` -------------------------------- ### Get All Recent Group Chat Names Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves a list of all recent group chat names. Returns a WxResponse object on failure or a list of strings (group names) on success. ```python groups = wx.GetAllRecentGroups() if groups: print(groups) else: print('获取失败') ``` -------------------------------- ### Get New Friend Requests Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Fetches a list of new friend requests. The 'acceptable' parameter can filter out already accepted requests. The returned list contains NewFriendElement objects, which can be used to accept requests with custom remarks and tags. ```python newfriends = wx.GetNewFriends(acceptable=True) ``` ```python newfriends = wx.GetNewFriends(acceptable=True) tags = ['标签1', '标签2'] for friend in newfriends: remark = f'备注{friend.name}' friend.accept(remark=remark, tags=tags) # 接受好友请求,并设置备注和标签 ``` -------------------------------- ### Get All Messages Source: https://context7.com/cluic/wxauto/llms.txt Retrieve all loaded chat messages from the current chat window. Returns a list of message objects. Supports downloading attachments like images and files, and converting voice messages to text if specified. ```python from wxauto import WeChat wx = WeChat() wx.ChatWith("Zhang San") # Get current chat history (attachments not automatically downloaded) msgs = wx.GetAllMessage() for msg in msgs: if msg.type == 'time': print(f"[Time] {msg.time}") elif msg.attr == 'friend': print(f"[Friend] {msg.sender}: {msg.content}") elif msg.attr == 'self': print(f"[Self]: {msg.content}") elif msg.type == 'system': print(f"[System] {msg.content}") # Automatically download images, files, and convert voice to text msgs = wx.GetAllMessage(savepic=True, savefile=True, savevoice=True) for msg in msgs: if msg.type == 'image': print(f"Image saved to: {msg.content}") ``` -------------------------------- ### Configure wxauto Parameters Source: https://context7.com/cluic/wxauto/llms.txt Set default save paths, enable/disable logging, and configure listener intervals and timeouts before initializing the WeChat client. ```python WxParam.DEFAULT_SAVE_PATH = 'D:/WeChatFiles' # 是否启用日志文件 WxParam.ENABLE_FILE_LOGGER = True # 监听轮询时间间隔(秒) WxParam.LISTEN_INTERVAL = 1 # 监听线程池大小 WxParam.LISTENER_EXCUTOR_WORKERS = 8 # 搜索联系人超时(秒) WxParam.SEARCH_CHAT_TIMEOUT = 5 # 是否启用消息 hash 值(辅助去重,会稍微影响性能) WxParam.MESSAGE_HASH = False # 初始化(参数已在上方配置) wx = WeChat() ``` -------------------------------- ### Get Group Members Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves a list of members currently in the chat group. ```python members = wx.GetGroupMembers() ``` -------------------------------- ### Initialize WeChat Instance Source: https://github.com/cluic/wxauto/blob/main/docs/README.md Instantiate the WeChat class to begin automating WeChat. Ensure WeChat is running. ```python from wxauto import WeChat # Initialize WeChat instance wx = WeChat() ``` -------------------------------- ### Show Window Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Displays the chat window. ```APIDOC ## Chat 类方法 ### 显示窗口 Show ```python chat.Show() ``` ``` -------------------------------- ### SendEmotion Source: https://context7.com/cluic/wxauto/llms.txt Sends an emoji that has been added to the WeChat custom emoji library, selected by index (starting from 0). ```APIDOC ## SendEmotion ### Description Sends an emoji that has been added to the WeChat custom emoji library, selected by index (starting from 0). ### Method ```python from wxauto import WeChat wx = WeChat() # Send the first custom emoji to a specified contact wx.SendEmotion(emotion_index=0, who="Zhang San") # Send the third emoji to the current chat window wx.SendEmotion(emotion_index=2) ``` ``` -------------------------------- ### GetAllSubWindow Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves a list of all currently open chat window instances. ```APIDOC ## GetAllSubWindow ### Description Retrieves a list of all currently open chat window instances. ### Method `GetAllSubWindow()` ### Endpoint N/A (Method Call) ### Parameters None ### Response #### Success Response - **chats** (List[[`Chat`](/docs/class/Chat)]) - A list of Chat class instances, one for each open chat window. ### Response Example ```python chats = wx.GetAllSubWindow() ``` ``` -------------------------------- ### Switch to Chat View Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Switches the current view to the chat interface. ```python wx.SwitchToChat() ``` -------------------------------- ### Initialize WeChat Instance Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Instantiate the WeChat class. The 'nickname' parameter can be used to target a specific WeChat window, and 'debug' enables debug mode. ```python from wxauto import WeChat wx = WeChat() ``` -------------------------------- ### WeChat Class Initialization Source: https://context7.com/cluic/wxauto/llms.txt Initializes the WeChat instance, automatically locating and activating the running WeChat main window. Global parameters can be modified before initialization. ```APIDOC ## WeChat Class Initialization ### Description Initializes the WeChat instance, automatically locating and activating the running WeChat main window. Global parameters can be modified before initialization. ### Method ```python from wxauto import WeChat, WxParam # Modify global parameters (set before initialization) WxParam.DEFAULT_SAVE_PATH = 'D:/WxFiles' # Default save directory for files/images WxParam.LISTEN_INTERVAL = 1 # Listening poll interval (seconds) WxParam.LISTENER_EXCUTOR_WORKERS = 4 # Listener thread pool size # Initialize (language can be 'cn' Simplified Chinese / 'cn_t' Traditional Chinese / 'en' English) wx = WeChat(language='cn', debug=False) # Example output: Initialization successful, obtained logged-in window: Zhang San print(wx.nickname) # Nickname of the currently logged-in account, e.g., 'Zhang San' ``` ``` -------------------------------- ### Creating Group Chats Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Shows how to add members to an existing chat to form a group and how to manage the group, such as renaming it. ```APIDOC ## Creating Group Chats ### Description Adds members to an existing chat to form a group and demonstrates how to manage the group, including renaming. ### Method ```python from wxauto import WeChat wx = WeChat() # Add members to a chat to form a group wx.AddGroupMembers(group='Zhang San', members=['Li Si']) # Simple wait time.sleep(3) # Rename the group wx.ManageGroup(name='New Group Name') ``` ``` -------------------------------- ### Open Chat Window Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Initiate a chat with a specific contact. The 'exact' parameter controls whether the friend search is an exact match. ```python wx.ChatWith(who="张三", exact=False) ``` -------------------------------- ### Get Chat Type Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves the type of the current chat window. Possible values include 'friend', 'group', 'service', and 'official'. ```python chat_type = chat.chat_type ``` -------------------------------- ### Add Chat Listening Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Set up a callback function to listen for messages from a specific chat. The callback receives message and chat objects. ```python def on_message(msg, chat): print(f"收到来自 {chat} 的消息: {msg.content}") wx.AddListenChat(nickname="张三", callback=on_message) ``` -------------------------------- ### MomentsWnd Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md The MomentsWnd object represents the WeChat Moments window, offering operations to get moments content, refresh, and close the window. ```APIDOC ## MomentsWnd **朋友圈窗口**对象,即的是朋友圈的窗口对象,提供对朋友圈窗口的各种操作,如获取朋友圈内容、刷新、关闭等功能。 ```python from wxauto import WeChat wx = WeChat() pyq = wx.Moments() # 打开朋友圈并获取朋友圈窗口对象(如果为None则说明你没开启朋友圈,需要在手机端设置) ``` ``` -------------------------------- ### Select Option from Message Context Menu Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Right-click a message to open its context menu and select a specific option, such as 'Copy'. ```python msg.select_option("复制") ``` -------------------------------- ### Initialize WeChat Instance Source: https://context7.com/cluic/wxauto/llms.txt Initialize the WeChat instance to interact with the WeChat client. Global parameters like default save path and listener interval can be modified before initialization. The language parameter can be set to 'cn', 'cn_t', or 'en'. ```python from wxauto import WeChat, WxParam # Modify global parameters (set before initialization) WxParam.DEFAULT_SAVE_PATH = 'D:/WxFiles' # Default save directory for files/images WxParam.LISTEN_INTERVAL = 1 # Listener polling interval (seconds) WxParam.LISTENER_EXCUTOR_WORKERS = 4 # Listener thread pool size # Initialize (language can be 'cn' simplified Chinese / 'cn_t' traditional Chinese / 'en' English) wx = WeChat(language='cn', debug=False) # Output example: Initialization successful, obtained logged-in window: Zhang San print(wx.nickname) # Nickname of the currently logged-in account, e.g., 'Zhang San' ``` -------------------------------- ### Get All Messages from Current Chat Source: https://github.com/cluic/wxauto/blob/main/docs/README.md Retrieve all messages from the currently active chat window. Each message object contains sender and content. ```python # Get current chat window messages msgs = wx.GetAllMessage() for msg in msgs: print('==' * 30) print(f"{msg.sender}: {msg.content}") ``` -------------------------------- ### Listen for and Process WeChat Messages Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Set up a listener to process incoming messages. Supports custom logic for logging, downloading media, and auto-replying. Requires a callback function to handle messages. ```python from wxauto import WeChat from wxauto.msgs import FriendMessage import time wx = WeChat() # Message processing function def on_message(msg, chat): # Example 1: Log messages to a local file with open('msgs.txt', 'a', encoding='utf-8') as f: f.write(msg.content + '\n') # Example 2: Automatically download images and videos if msg.type in ('image', 'video'): print(msg.download()) # Example 3: Auto-reply to received messages if isinstance(msg, FriendMessage): msg.quote('收到') ...# Other processing logic, combined with Message class methods, can achieve various functions # Add listener, messages received will be processed by on_message function wx.AddListenChat(nickname="张三", callback=on_message) # Keep the program running wx.KeepRunning() ``` ```python # ... After the program has been running for a while ... # Remove listener wx.RemoveListenChat(nickname="张三") ``` -------------------------------- ### Get Next New Message Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieve new messages that have arrived since the last check. Optionally filter out messages from 'do not disturb' chats. ```python messages = wx.GetNextNewMessage(filter_mute=False) ``` -------------------------------- ### GetSubWindow Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves a specific chat window instance by its nickname. ```APIDOC ## GetSubWindow ### Description Retrieves a specific chat window instance by its nickname. ### Method `GetSubWindow(nickname)` ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters - **nickname** (str) - Required - The nickname of the chat window to retrieve. ### Response #### Success Response - **chat** ([`Chat`](/docs/class/Chat)) - An instance of the Chat class representing the specified chat window. ### Response Example ```python chat = wx.GetSubWindow(nickname="张三") ``` ``` -------------------------------- ### Switch to Contacts View Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Switches the current view to the contacts interface. ```python wx.SwitchToContact() ``` -------------------------------- ### Get Next New Message Source: https://context7.com/cluic/wxauto/llms.txt Polls for the next new message from any session. Useful when not using callback listeners. The `filter_mute` parameter can be used to exclude muted chats. ```python from wxauto import WeChat import time wx = WeChat() # 轮询方式检测并处理新消息 while True: result = wx.GetNextNewMessage(filter_mute=False) if result: # result 示例: # { # 'chat_name': 'wxauto交流', # 'chat_type': 'group', # 'msg': [, , ...] # } chat_name = result['chat_name'] for msg in result['msg']: print(f"[{chat_name}] {msg.sender}: {msg.content}") time.sleep(1) ``` -------------------------------- ### Get Dialog Box Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves the current dialog box object. Can be used to interact with dialogs, such as clicking buttons. Includes an optional wait time for the dialog to appear. ```python if dialog := wx.GetDialog(): dialog.click_button("确定") ``` -------------------------------- ### ChatWith Source: https://context7.com/cluic/wxauto/llms.txt Switches the main window to the chat interface of a specified contact, useful for locating the window before sending messages. ```APIDOC ## ChatWith ### Description Switches the main window to the chat interface of a specified contact, useful for locating the window before sending messages. ### Method ```python from wxauto import WeChat wx = WeChat() # Switch to friend chat (fuzzy match) wx.ChatWith(who="Zhang San") # Switch and exact match (use for multiple similar names) wx.ChatWith(who="Zhang San (Company)", exact=True) # Get the name of the current chat object current = wx.CurrentChat() print(f"Current chat object: {current}") # Output: Zhang San ``` ``` -------------------------------- ### Create and Manage Group Chats Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Create a new group chat by adding members to an existing contact's chat or manage existing groups by renaming them. Requires specifying group name and members. ```python from wxauto import WeChat wx = WeChat() # Add '李四' to '张三's chat to form a group chat wx.AddGroupMembers(group='张三', members=['李四']) # Simple wait time.sleep(3) # Modify group name wx.ManageGroup(name='这是新群名') ``` -------------------------------- ### Get WeChat Login QR Code Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Generate and retrieve the path to the QR code image for WeChat login. Useful for integrating QR code scanning into automated workflows. ```python from wxauto import LoginWnd wxpath = "D:/path/to/WeChat.exe" # Create login window loginwnd = LoginWnd(wxpath) # Get login QR code image path qrcode_path = loginwnd.get_qrcode() print(qrcode) ``` -------------------------------- ### Download Media Messages (Image, Video, File, Voice) Source: https://context7.com/cluic/wxauto/llms.txt Media message objects offer a `download()` method to save content locally. For voice messages, `to_text()` can convert speech to text. Specify `dir_path` for the download location and optionally `timeout`. ```python from wxauto import WeChat from wxauto.msgs import FriendImageMessage, FriendVideoMessage, FriendFileMessage, FriendVoiceMessage wx = WeChat() def handle_message(msg, chat): # 下载图片 if isinstance(msg, FriendImageMessage): path = msg.download(dir_path="D:/images", timeout=15) print(f"图片已保存:{path}") # 下载视频 elif isinstance(msg, FriendVideoMessage): path = msg.download(dir_path="D:/videos") print(f"视频已保存:{path}") # 下载文件 elif isinstance(msg, FriendFileMessage): path = msg.download(dir_path="D:/downloads", force_click=False, timeout=30) print(f"文件已保存:{path}") # 语音转文字 elif isinstance(msg, FriendVoiceMessage): text = msg.to_text() print(f"语音内容:{text}") wx.AddListenChat(nickname="张三", callback=handle_message) wx.KeepRunning() ``` -------------------------------- ### GetSubWindow / GetAllSubWindow Source: https://context7.com/cluic/wxauto/llms.txt Retrieves and operates on popped-up independent chat sub-windows (Chat objects). GetSubWindow retrieves a specific window by nickname, while GetAllSubWindow retrieves all currently open sub-windows. ```APIDOC ## GetSubWindow / GetAllSubWindow ### Description Retrieves and operates on popped-up independent chat sub-windows (Chat objects). GetSubWindow retrieves a specific window by nickname, while GetAllSubWindow retrieves all currently open sub-windows. ### Method `wx.GetSubWindow(nickname: str)` `wx.GetAllSubWindow()` ### Parameters - **nickname** (str) - Required - The nickname of the chat window to retrieve. ### Response - **chat** (Chat object): Represents a chat sub-window with methods like `ChatInfo()`, `SendMsg()`, etc. - **all_chats** (list): A list of Chat objects for all open sub-windows. ### Chat Object Methods - **ChatInfo()**: Returns a dictionary with chat information (e.g., `chat_type`, `chat_name`, `group_member_count`). - **SendMsg(message: str)**: Sends a message to the chat window. ### Request Example ```python from wxauto import WeChat wx = WeChat() wx.ChatWith("张三") sessions = wx.GetSession() sessions[0].double_click() # Pop up the sub-window # Get a specific sub-window chat = wx.GetSubWindow(nickname="张三") print(f"聊天对象: {chat.who}") print(f"聊天类型: {chat.chat_type}") info = chat.ChatInfo() print(info) chat.SendMsg("你好!") # Get all sub-windows all_chats = wx.GetAllSubWindow() for c in all_chats: print(c.who, c.chat_type) ``` ``` -------------------------------- ### Automatic WeChat Login Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Automate the WeChat login process by specifying the WeChat executable path. Requires the path to the WeChat.exe file. ```python from wxauto import LoginWnd wxpath = "D:/path/to/WeChat.exe" # Create login window loginwnd = LoginWnd(wxpath) # Login to WeChat loginwnd.login() ``` -------------------------------- ### Get All Text Content from Message Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Extracts all text content from a message object. The returned value is a list of strings, useful for processing messages that might contain multiple text segments. ```python text_list = msg.get_all_text() ``` -------------------------------- ### Listen for New Messages Source: https://context7.com/cluic/wxauto/llms.txt Add a chat to be monitored in a separate pop-up window, triggering a callback function for each new message. This is the recommended way to receive messages. Use RemoveListenChat() to stop monitoring a specific chat or StopListening() to stop all monitoring. ```python from wxauto import WeChat from wxauto.msgs import FriendMessage, FriendImageMessage wx = WeChat() # Define message callback (msg: Message object, chat: Chat sub-window object) def on_message(msg, chat): print(f"[{chat.who}] {msg.attr} | {msg.type}: {msg.content}") # Process text messages, automatically quote reply if isinstance(msg, FriendMessage) and msg.type == 'text': msg.quote("Received!") # Download image messages if isinstance(msg, FriendImageMessage): path = msg.download() print(f"Image saved to: {path}") # Add listener (automatically pops up a separate chat window) wx.AddListenChat(nickname="Zhang San", callback=on_message) wx.AddListenChat(nickname="Project Group", callback=on_message) # Keep the main thread running (listeners are daemon threads, they stop when the main thread exits) wx.KeepRunning() # --- OR, remove listener after running for a while --- # wx.RemoveListenChat(nickname="Zhang San") # wx.StopListening() # Stop all listeners ``` -------------------------------- ### Send Custom Emotion Source: https://context7.com/cluic/wxauto/llms.txt Send custom emoticons that have been added to the WeChat custom emotion library. Emoticons are selected by their index, starting from 0. Use the 'who' parameter to specify the recipient. ```python from wxauto import WeChat wx = WeChat() # Send the first custom emotion to a specific contact wx.SendEmotion(emotion_index=0, who="Zhang San") # Send the third emotion to the current chat window wx.SendEmotion(emotion_index=2) ``` -------------------------------- ### SendFiles Source: https://context7.com/cluic/wxauto/llms.txt Sends single or multiple local files to a specified contact. Paths must be absolute. ```APIDOC ## SendFiles ### Description Sends single or multiple local files to a specified contact. Paths must be absolute. ### Method ```python from wxauto import WeChat wx = WeChat() # Send a single file result = wx.SendFiles(filepath="C:/reports/monthly_report.xlsx", who="Boss") if result: print("File sent successfully") # Batch send multiple files files = [ "C:/docs/requirements.docx", "C:/docs/prototype.png", "C:/docs/test_report.pdf" ] wx.SendFiles(filepath=files, who="Project Group") ``` ``` -------------------------------- ### Get Contact Group List Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves the list of group chats from your contacts. Adjust 'speed' and 'interval' parameters based on your actual situation, as incorrect values may lead to missed groups. ```python wx.GetContactGroups() ``` -------------------------------- ### ChatWith Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Opens a chat window with a specified contact. Allows for exact or fuzzy matching of the contact name. ```APIDOC ## ChatWith ### Description Opens a chat window with a specified contact. Allows for exact or fuzzy matching of the contact name. ### Method `ChatWith(who, exact=False)` ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters - **who** (str) - Required - The name of the contact to chat with. - **exact** (bool) - Optional - If True, performs an exact match for the contact name. Defaults to False. ### Request Example ```python wx.ChatWith(who="张三", exact=False) ``` ### Response #### Success Response No specific return value mentioned, implies void or success confirmation. ``` -------------------------------- ### Get WeChat Session List Source: https://context7.com/cluic/wxauto/llms.txt Retrieves all currently visible sessions from the left-hand chat list. Includes session name, time, content, and new message status. Use `session.click()` to switch to a session. ```python from wxauto import WeChat wx = WeChat() sessions = wx.GetSession() for session in sessions: info = session.info print(f"会话名: {info['name']}") print(f"最新消息: {info['content']}") print(f"时间: {info['time']}") print(f"是否有新消息: {info['isnew']}") print(f"新消息数: {info['new_count']}") print(f"是否免打扰: {info['ismute']}") print("---") # 点击切换到该会话 session.click() # 双击弹出独立窗口 # session.double_click() ``` -------------------------------- ### Get Chat Information Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Retrieves information about the chat window associated with the message. This method returns a dictionary containing details about the chat type and name, which can vary for friends, groups, services, or official accounts. ```python chat_info = msg.chat_info() ``` -------------------------------- ### WeChat Initialization Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Initializes the WeChat class. You can specify a nickname to target a specific WeChat window or enable debug mode. ```APIDOC ## WeChat Initialization ### Description Initializes the WeChat class. You can specify a nickname to target a specific WeChat window or enable debug mode. ### Parameters #### Path Parameters - **nickname** (str) - Optional - The WeChat nickname, used to locate a specific WeChat window. - **debug** (bool) - Optional - Whether to enable debug mode. ### Request Example ```python from wxauto import WeChat wx = WeChat() # or with parameters: # wx = WeChat(nickname='WeChatName', debug=True) ``` ``` -------------------------------- ### Show Chat Window Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Displays the independent chat window associated with the Chat object. ```python chat.Show() ``` -------------------------------- ### Basic WeChat Operations Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Initialize a WeChat instance, send messages to a contact, and retrieve messages from the current chat window. Useful for automating basic chat interactions. ```python from wxauto import WeChat # Initialize WeChat instance wx = WeChat() # Send message wx.SendMsg("你好", who="张三") # Get current chat window messages msgs = wx.GetAllMessage() for msg in msgs: print(f"消息内容: {msg.content}, 消息类型: {msg.type}") ``` -------------------------------- ### Download Sender's Head Image Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Download the head image of the message sender. Returns a Path object upon success. ```python msg.download_head_image() ``` -------------------------------- ### roll_into_view() Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Scrolls the message into the visible view. ```APIDOC ### roll_into_view 将消息滚动到视野内 ```python msg.roll_into_view() ``` ``` -------------------------------- ### Like Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md Likes or unlikes a moment. ```APIDOC ## Like **点赞朋友圈** ### Parameters | 参数 | 类型 | 默认值 | 说明 | | :--: | :--: | :----: | :--: | | like | bool | True | True点赞,False取消赞 | ```python # 点赞 moment.Like() # 取消赞 moment.Like(False) ``` ### Return Value 无 ``` -------------------------------- ### Open Chat Window Source: https://context7.com/cluic/wxauto/llms.txt Switch the main WeChat window to the chat interface of a specified contact. This is useful for locating the chat window before sending messages. Use 'exact=True' for precise matching if names are similar. ```python from wxauto import WeChat wx = WeChat() # Switch to friend's chat (fuzzy match) wx.ChatWith(who="Zhang San") # Switch and match exactly (use when multiple similar names exist) wx.ChatWith(who="Zhang San (Company)", exact=True) # Get the name of the current chat object current = wx.CurrentChat() print(f"Current chat object: {current}") # Output: Zhang San ``` -------------------------------- ### Save Moment Images Source: https://github.com/cluic/wxauto/blob/main/docs/class/Moment.md Saves images from a moment to a specified path or the default directory. Supports saving specific images by index. ```python # 获取朋友圈图片 images = moment.SaveImages() # [ # 'D:/Images/微信图片_xxxxxx1.jpg', # 'D:/Images/微信图片_xxxxxx2.jpg', # 'D:/Images/微信图片_xxxxxx3.jpg', # ... # ] ``` -------------------------------- ### Download Image Message Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Download an image message. You can specify the save directory and a timeout. Returns a Path object on success or a WxResponse object on failure. ```python msg.download() ``` -------------------------------- ### ImageMessage Methods Source: https://github.com/cluic/wxauto/blob/main/docs/class/Message.md Provides methods for interacting with image messages, specifically for downloading images. ```APIDOC ## ImageMessage ### download Download the image and return the image path. ```python msg.download() ``` **Parameters**: | Parameter | Type | Default | Description | |---|---|---|---| | dir_path | Union[str, Path] | None | Directory to download the image to, defaults to [WxParam.DEFAULT_SAVE_PATH](#wxparam-class) if not specified | | timeout | int | 10 | Download timeout | **Returns**: - Path: Image path, returns this type on success - [`WxResponse`](/docs/class/other/#wxresponse): Download result, returns this type on failure ``` -------------------------------- ### Sending Messages with Typing Text Mode Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Demonstrates how to send messages using the typing text mode, including plain text, messages with mentions (@), and messages with newlines. ```APIDOC ## Sending Messages with Typing Text Mode ### Description Sends messages using the typing text mode, supporting plain text, mentions, and newlines. ### Method ```python from wxauto import WeChat wx = WeChat() # Send plain text message wx.SendTypingText("Hello, this is a test message", who="Zhang San") # Use @ mentions and newlines wx.SendTypingText("Hello everyone:\n{@Zhang San} please be responsible for the front-end part\n{@Li Si} please be responsible for the back-end part", who="Project Group") ``` ``` -------------------------------- ### GetDialog Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Retrieves the dialog box object, allowing interaction with it. Returns None if no dialog exists. ```APIDOC ## GetDialog ### Description Retrieves the dialog box object, allowing interaction with it. Returns None if no dialog exists. ### Method `wx.GetDialog` ### Parameters #### Path Parameters - **wait** (int) - Optional - The implicit waiting time. Defaults to 3. ``` -------------------------------- ### IsOnline Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Checks if the WeChat client is currently online. ```APIDOC ## IsOnline ### Description Checks if the WeChat client is currently online. ### Method `wx.IsOnline()` ### Response #### Success Response - **Type**: bool - **Description**: Returns `True` if online, `False` otherwise. ``` -------------------------------- ### Processing Friend Requests Source: https://github.com/cluic/wxauto/blob/main/docs/example.md Illustrates how to retrieve new friend requests and automatically accept them, setting remarks and tags for the new contacts. ```APIDOC ## Processing Friend Requests ### Description Retrieves new friend requests and automatically accepts them, allowing for the setting of remarks and tags. ### Method ```python from wxauto import WeChat wx = WeChat() # Get new friend requests newfriends = wx.GetNewFriends(acceptable=True) # Process friend requests tags = ['Colleague', 'Tech Group'] for friend in newfriends: remark = f'Remark_{friend.name}' friend.accept(remark=remark, tags=tags) # Accept friend request, set remark and tags ``` ``` -------------------------------- ### @All Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Sends a message to @all members in a group. ```APIDOC ### @所有人 AtAll ```python group = '工作群' content = """ 通知: 下午xxxx xxxx """ wx.AtAll(content, group) ``` msg (str): 发送的消息 ​ who (str, optional): 发送给谁. Defaults to None. ​ exact (bool, optional): 是否精确匹配. Defaults to False. **参数**: | 参数 | 类型 | 默认值 | 描述 | | ----- | ------ | ------ | ------------------------------------------------------------ | | msg | str | None | 发送的消息 | | who | str | None | 发送给谁 | | exact | bool | False | 是否精确匹配 | **返回值**: - 类型:[`WxResponse`](/docs/class/other/#wxresponse) - 描述:是否发送成功 ``` -------------------------------- ### SwitchToContact Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Switches the current view to the contacts interface. ```APIDOC ## SwitchToContact ### Description Switches the current view to the contacts interface. ### Method `wx.SwitchToContact()` ### Response #### Success Response - **Description**: No return value. ``` -------------------------------- ### Send Files Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Sends one or more files to a specified recipient or the current chat. Note: 'who' and 'exact' parameters are invalid for sub-windows. ```python wx.SendFiles(filepath="C:/文件.txt", who="张三", exact=False) ``` -------------------------------- ### Send Files Source: https://context7.com/cluic/wxauto/llms.txt Send single or multiple local files to a specified contact. File paths must be absolute. The 'filepath' parameter can be a string for a single file or a list of strings for multiple files. ```python from wxauto import WeChat wx = WeChat() # Send a single file result = wx.SendFiles(filepath="C:/reports/monthly_report.xlsx", who="Boss") if result: print("File sent successfully") # Batch send multiple files files = [ "C:/docs/requirements.docx", "C:/docs/prototype.png", "C:/docs/test_report.pdf" ] wx.SendFiles(filepath=files, who="Project Group") ``` -------------------------------- ### Load More Message History Source: https://github.com/cluic/wxauto/blob/main/docs/class/Chat.md Loads more chat history for the current window. Returns a WxResponse indicating success or failure. ```python wx.LoadMoreMessage() ``` -------------------------------- ### GetSession Source: https://github.com/cluic/wxauto/blob/main/docs/class/WeChat.md Retrieves a list of all current chat sessions. ```APIDOC ## GetSession ### Description Retrieves a list of all current chat sessions. ### Method `GetSession()` ### Endpoint N/A (Method Call) ### Parameters None ### Response #### Success Response - **sessions** (List[[SessionElement](/docs/class/other/#sessionelement)]) - A list of SessionElement objects representing the current chat sessions. ### Response Example ```python sessions = wx.GetSession() for session in sessions: print(session.info) ``` ```