### Install Dependencies for Local Development Source: https://github.com/hello-mr-crab/pywechat/blob/main/QuickStart.md Install all necessary dependencies for local development and testing of pywechat. Ensure you have the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Missing Dependencies for pyweixin-rpa Source: https://github.com/hello-mr-crab/pywechat/blob/main/Skill/OpenClaw/pyweixin-rpa/SKILL.md If dependencies are missing, execute this command in the repository root to install them using pip. ```bash pip install -r scripts/requirements.txt ``` -------------------------------- ### Install pywechat Globally Source: https://github.com/hello-mr-crab/pywechat/blob/main/QuickStart.md Install the latest version of pywechat from PyPI for global use. This is the recommended method for most users. ```bash pip install pywechat127 ``` -------------------------------- ### Basic pywechat Usage Source: https://github.com/hello-mr-crab/pywechat/blob/main/README.md Demonstrates the minimal code required to get started with pywechat automation. ```python from pyweixin import xxx xxx.yy ``` -------------------------------- ### Install pywechat in Local Development Mode Source: https://github.com/hello-mr-crab/pywechat/blob/main/QuickStart.md Install pywechat locally from the source code for development and testing. This allows for direct modifications and debugging. ```bash cd src pip install -e . ``` -------------------------------- ### Independent Window Monitoring Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/monitor.md This example demonstrates how to use `listen_on_chat` within an independent chat window, with options to minimize the window and close it after listening. ```APIDOC ## Independent Window Monitoring ```python from pyweixin import Navigator, Monitor dialog_window = Navigator.open_seperate_dialog_window( friend='小王', window_minimize=True # 最小化窗口 ) result = Monitor.listen_on_chat( dialog_window, duration='5min', close_dialog_window=True # 完成后关闭 ) ``` **Parameters**: - **dialog_window**: The handle to the independent chat window. - **duration** (str): The duration to listen. - **close_dialog_window** (bool, optional): Whether to close the dialog window after listening. Defaults to False. ``` -------------------------------- ### Time Parameter Format Example Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/configuration.md Demonstrates the usage of time duration strings with 's', 'min', and 'h' suffixes for methods like message monitoring. ```python from pyweixin import Monitor, Navigator dialog_window = Navigator.open_seperate_dialog_window(friend='好友') # 监听 5 分钟 result = Monitor.listen_on_chat(dialog_window, duration='5min') ``` -------------------------------- ### Check Requirements for pyweixin-rpa Source: https://github.com/hello-mr-crab/pywechat/blob/main/Skill/OpenClaw/pyweixin-rpa/SKILL.md Run this command once in the root directory of the repository to check and install dependencies. It outputs a JSON object indicating missing packages. ```bash python scripts/check_requirements.py ``` -------------------------------- ### Pywinauto WeChat Automation Setup Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Initializes pywinauto for UI automation and defines custom exceptions for WeChat automation. Ensure WeChat is running and logged in before using these functions. ```python #pywinauto ui控件的文本和值 import win32gui,win32con,win32api,win32com.client from pywinauto import Desktop,WindowSpecification desktop=Desktop(backend='uia')#pywinauto的桌面实例 #自定义异常 class NotStartError(Exception): def __init__(self, Error='微信未启动,请先启动并登录微信后再使用pyweixin!'): super().__init__(Error) class NotLoginError(Exception): def __init__(self, Error='微信未登录,请先点击登录后再使用pyweixin!'): super().__init__(Error) class NetWorkError(Exception): def __init__(self, Error='当前网络不可用,无法进行UI自动化!'): super().__init__(Error) class NotFoundError(Exception): def __init__(self,Error='无法识别定位到微信主界面,请在微信登录前运行无障碍服务(讲述人)后再尝试!'): super().__init__(Error) ``` -------------------------------- ### Connect to Application using Process ID, Handle, or Path Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Demonstrates connecting to a running application (WeChat) using pywinauto's Application class. It shows how to connect via process ID, window handle, or the executable path. It also illustrates how to get the main window using its handle or other UI properties. ```python #Application连接窗口 from pywinauto import Application ''' pywinauto Application类可以用来连接到正在运行的应用: 使用connect方法时有四个可选参数,分别是: path:应用程序.exe路径 handle:窗口句柄(inspect中可查看) pid:应用的process id(可在任务管理器中右键查看详细信息中看到) timeout:连接超时时间 ... ... 以及其他定位参数:比如title,control_type,auto_id,class_name ''' pid=22736 handle=0x309A2 path=r"D:\Weixin\Weixin.exe" wechat_app1=Application(backend='uia').connect(process=pid) wechat_app2=Application(backend='uia').connect(handle=handle) wechat_app3=Application(backend='uia').connect(path=path) #不建议使用定位ui控件的方式连接 #wechat_app4=Application(backend='uia').connect(title='微信',class_name='mmui::MainWindow') '''在连接到应用后便可以使用.window方法来连接当前应用程序的主窗口了 连接窗口时和我们定位ui控件一样,传入的参数有title,control_type,auto_id,class_name 等当前窗口的ui属性,当然还支持直接传入handle(最稳定),这里建议能够获取到窗口句柄就尽量用窗口句柄 特别是对于4.1版本微信,使用常规的title,control_type,auto_id,class_name等ui属性无法直接定位到窗口 ''' main_window=wechat_app3.window(handle=handle) #main_window=wechat_app3.window(title='微信',class_name='mmui::MainWindow') if main_window.exists(timeout=1): main_window.restore() ``` -------------------------------- ### Install pyweixin-rpa Skill with OpenClaw Source: https://github.com/hello-mr-crab/pywechat/blob/main/QuickStart.md Install the pyweixin-rpa skill using the OpenClaw package manager. This is for integrating WeChat automation with OpenClaw. ```bash openclaw skills install pyweixin-rpa ``` -------------------------------- ### Automatic File and Media Saving Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/monitor.md This example demonstrates how to configure `listen_on_chat` to automatically save received files and media to a specified folder, organized by date. ```APIDOC ## Automatic File and Media Saving ```python from pyweixin import Monitor, Navigator import os from datetime import datetime dialog_window = Navigator.open_seperate_dialog_window(friend='小王') # 以日期为名称创建文件夹 date_folder = datetime.now().strftime('%Y%m%d') target_folder = os.path.join(os.getcwd(), 'records', date_folder) result = Monitor.listen_on_chat( dialog_window, duration='1h', save_file=True, save_media=True, target_folder=target_folder ) print(f"保存统计:") print(f"- 文件: {result['文件数量']} 个") print(f"- 图片: {result['图片数量']} 张") print(f"- 视频: {result['视频数量']} 个") ``` **Parameters**: - **dialog_window**: The handle to the chat window. - **duration** (str): The duration to listen. - **save_file** (bool): Enable saving of received files. - **save_media** (bool): Enable saving of received media. - **target_folder** (str): The directory where files and media will be saved. ``` -------------------------------- ### Automate Notepad with pywinauto (win32 backend) Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb This snippet demonstrates how to automate Notepad using pywinauto with the 'win32' backend. It starts Notepad, connects to its window, and sets text in the RichEdit control. Ensure Notepad is available on your system. ```python #pywinatuo backend为win32 自动操作记事本 from pywinauto.application import Application app=Application(backend="win32").start("notepad.exe") app=app.connect(class_name='Notepad',timeout=5) main_window=app.window(class_name='Notepad') main_window.child_window(class_name="RichEditD2DPT").set_text('pywinauto自动化操作记事本') ``` -------------------------------- ### Example ReplyCallback Function Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/types.md An example implementation of a ReplyCallback function. This function checks for a specific phrase in the new message and returns a predefined reply or None. ```python def my_callback(new_message: str, contexts: list[str]) -> str | None: if '你好' in new_message: return '你好!' return None ``` -------------------------------- ### Module Imports Source: https://github.com/hello-mr-crab/pywechat/blob/main/Skill/OtherPlatforms/pyweixin-rpa/references/api_reference.md Instructions and examples for importing necessary modules from the pyweixin library. It's recommended to add the 'scripts' directory to sys.path to avoid conflicts with pip packages. ```APIDOC ## Module Imports > ⚠️ **Custom Script Essentials** > > 1. Before importing, `sys.path.insert(0, 'scripts')` (to avoid pip package conflicts) > 2. `dump_chat_history` returns `list[dict]`, **do not unpack into two variables** (not `tuple[list, list]`) > 3. Return values are based on this API Reference, **do not run probes first**—the documentation has extracted the accurate return type and structure for each method from the source code > 4. **Do not re-fetch data that has already been pulled**: Pass the `list[dict]` to downstream functions for processing, do not call `dump_chat_history` again > 5. **Scheduled tasks use external schedulers, do not write any scheduling logic within the script**: System scheduled tasks, CI cron, or AI assistant scheduling capabilities can execute the script at the specified time. ```python import sys sys.path.insert(0, 'scripts') from pyweixin import Messages, Files, Contacts from pyweixin import FriendSettings, AutoReply, Monitor, Collections, Call from pyweixin import Moments, Settings from pyweixin import Tools, Navigator from pyweixin import SystemSettings from pyweixin.Config import GlobalConfig ``` ``` -------------------------------- ### Concurrent Monitoring of Multiple Friends Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/monitor.md This example shows how to use `ThreadPoolExecutor` to concurrently monitor multiple friends' chats. ```APIDOC ## Concurrent Monitoring of Multiple Friends ```python from concurrent.futures import ThreadPoolExecutor from pyweixin import Navigator, Monitor friends = ['好友1', '好友2', '好友3'] # 打开所有聊天窗口 windows = [ Navigator.open_seperate_dialog_window(friend=f) for f in friends ] # 并发监听 with ThreadPoolExecutor(max_workers=3) as pool: results = list(pool.map( lambda w: Monitor.listen_on_chat(w, '5min'), windows )) # 处理结果 for friend, result in zip(friends, results): print(f"{friend}: {result['新消息总数']} 条新消息") ``` **Note**: This example utilizes `ThreadPoolExecutor` for concurrency and assumes the existence of `Navigator.open_seperate_dialog_window` and `Monitor.listen_on_chat` functions. ``` -------------------------------- ### Automatic File and Media Saving during Monitoring with pyweixin Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/monitor.md Configure monitoring to automatically save received files and media. This example shows how to create a date-based folder structure for saving records and media. Requires pyweixin, os, and datetime libraries. ```python from pyweixin import Monitor, Navigator import os from datetime import datetime dialog_window = Navigator.open_seperate_dialog_window(friend='小王') # 以日期为名称创建文件夹 date_folder = datetime.now().strftime('%Y%m%d') target_folder = os.path.join(os.getcwd(), 'records', date_folder) result = Monitor.listen_on_chat( dialog_window, duration='1h', save_file=True, save_media=True, target_folder=target_folder ) print(f"保存统计:") print(f"- 文件: {result['文件数量']} 个") print(f"- 图片: {result['图片数量']} 张") print(f"- 视频: {result['视频数量']} 个") ``` -------------------------------- ### Simulate Mouse Scrolling with Pywinauto Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb This example demonstrates how to simulate mouse wheel scrolling at a given screen coordinate using pywinauto. A negative `wheel_dist` scrolls down, while a positive value scrolls up. ```python #pywinauto鼠标相关操作 from pywinauto import mouse '''mouse.scroll参数: coords:屏幕坐标(x,y),注意x,y均为正整数 wheel_dist:鼠标滚动幅度,需要是整数,为负时鼠标滑论向后滚动,页面向下滚动,为正时相反 ''' mouse.scroll(wheel_dist=-20,coords=(1000,500))#在指定位置滚动 ``` -------------------------------- ### Access ListenResult Data Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/types.md Demonstrates how to access the data within a ListenResult dictionary. This example shows retrieving the total message count, text message count, and the list of text messages. ```python from pyweixin import Monitor, Navigator dialog_window = Navigator.open_seperate_dialog_window(friend='小王') result = Monitor.listen_on_chat(dialog_window, '5min') # 访问结果 total_messages = result['新消息总数'] text_count = result['文本数量'] texts = result['文本内容'] ``` -------------------------------- ### Start Smart Auto Reply with Initial Context Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/autoreply.md Initiates an automated reply session with an awareness of past conversation history. It retrieves the chat history to establish an initial context for the callback function. ```python from pyweixin import AutoReply, Navigator, Messages def smart_reply(new_message: str, contexts: list[str]) -> str: """根据消息内容和上下文进行智能回复""" # 检查是否是重复话题 for context in contexts: if '已经' in context and new_message in context: return '我们刚才已经讨论过这个问题了' # 关键词回复 keywords = { '会议': '今天 3 点在会议室开会,请准时参加', '报告': '报告已经发送到你的邮箱,请查收', '进度': '项目进度按计划推进,预计下周完成', } for keyword, reply in keywords.items(): if keyword in new_message: return reply # 默认回复 return '感谢你的消息,我会尽快回复!' dialog_window = Navigator.open_seperate_dialog_window(friend='小王') # 获取初始上下文 history = Messages.dump_chat_history(friend='小王', number=20) contexts = [record['content'] for record in history if record['type'] == '文本'] result = AutoReply.auto_reply_to_friend( dialog_window=dialog_window, duration='30min', callback=smart_reply, contexts=contexts ) ``` -------------------------------- ### Locate and Click WeChat Moments Button Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Demonstrates how to locate UI elements within the WeChat main window using pywinauto's `window()` method with keyword arguments. This example specifically targets and clicks the 'Moments' button. ```python main_window=open_weixin() #pywinauto定位控件的方法参数都是kwargs,我们可以预先将控件的信息写成字典形式,然后使用**解包传入 #可以看做POM(PageObjectModel)封装 Toolbar={'title':'导航','control_type':'ToolBar'}#主界面左侧的侧边栏 Moments={'title':'朋友圈','control_type':'Button','class_name':"mmui::XTabBarItem"}#主界面左侧的朋友圈按钮 main_window=open_weixin(is_maximize=False) ''' .window与.child_window相比,没有什么区别,window()方法已被标记为弃用,它是child_window()方法的别名 ''' #先定位到左侧工具栏 toolbar=main_window.window(**Toolbar) # #然后再左侧工具栏中定位朋友圈按钮 moments_button=toolbar.window(**Moments) '''亦可省去中间变量,直接链式查找''' #main_window.window(**Toolbar).window(**Moments).click_input() '''或者直接在main_window内查找''' #moments_button=main_window.window(**Moments) moments_button.click_input()#最后点击朋友圈按钮 ``` -------------------------------- ### Simulate Mouse Clicks with Pywinauto Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb This snippet shows how to perform left or right mouse clicks at specific screen coordinates using pywinauto's mouse module. It also includes an example of how to perform multiple clicks in a loop. ```python #pywinauto鼠标相关操作 from pywinauto import mouse '''click参数: button:'left'或'right',点击的是鼠标左键还是右键 coords:屏幕坐标(x,y),注意x,y均为正整数 ''' mouse.click(button='left',coords=(200,200))#运行后点击指定的位置 #当然,理论上还可以使用for循环实现连点操作 for _ in range(2): mouse.click(button='left',coords=(200,200)) ``` -------------------------------- ### Get WeChat Main Window Properties (Python) Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb This snippet demonstrates how to retrieve various basic properties of the WeChat main window using pywinauto after it has been opened. These properties include the window text, class name, automation ID, control ID, handle, process ID, bounding rectangle, parent, and children. ```python main_window=open_weixin() ''' 基本属性:可以直接通过.访问到的属性,大致有以下这些 ''' print(f'微信主窗口的名字是:{main_window.window_text()}') print(f'微信主窗口的类名是:{main_window.class_name()}') print(f'微信主窗口的AutomationId是:{main_window.automation_id()}') print(f'微信主窗口的控件ID是:{main_window.control_id()}') print(f'微信主窗口的窗口句柄是:{main_window.handle}') print(f'微信主窗口的进程ID是:{main_window.process_id()}') print(f'微信主窗口的BoundingRectangle是:{main_window.rectangle()}') print(f'微信主窗口的父控件是:{main_window.parent()}') print(f'微信主窗口的子控件是:{main_window.children()}') ``` -------------------------------- ### Batch Get Friend Info and Cache Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/contacts.md Fetches all friend names and then retrieves detailed information for each friend in batches. It includes error handling for individual friend lookups and returns a dictionary of friend names to their info. Consider caching the results to avoid repeated calls, as fetching all friend info can be time-consuming. ```python from pywechat import Contacts def cache_friends_info(): """获取所有好友信息并缓存""" friends = Contacts.get_friends_name() # 批量获取信息 infos = {} for friend_name in friends: try: info = Contacts.get_friend_info(friend=friend_name) infos[friend_name] = info except Exception as e: print(f"获取 {friend_name} 信息失败: {e}") return infos friends_info = cache_friends_info() ``` -------------------------------- ### Get WeChat Basic Information Source: https://github.com/hello-mr-crab/pywechat/blob/main/README.md Prints basic information about the WeChat client. No specific setup is mentioned beyond importing the Tools module. ```python from pyweixin import Tools print(Tools.about_weixin()) ``` -------------------------------- ### Connect to Application using Desktop Class Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Shows how to connect to an application's main window using pywinauto's Desktop class. It highlights the use of window handle for stable connection and also demonstrates connecting using title and class name. ```python #Desktop连接窗口 from pywinauto import Desktop desktop=Desktop(backend='uia') '''直接使用desktop.window方法来连接当前应用程序的主窗口 连接窗口时和我们定位ui控件一样,传入的参数有title,control_type,auto_id,class_name 等当前窗口的ui属性,当然还支持直接传入handle(最稳定),这里建议能够获取到窗口句柄就尽量用窗口句柄 特别是对于4.1版本微信,使用常规的title,control_type,auto_id,class_name等ui属性无法直接定位到窗口 ''' handle=0x309A2#微信窗口句柄 # main_window=desktop.window(handle=handle) main_window=desktop.window(title='微信',class_name='mmui::MainWindow') if main_window.exists(timeout=1): main_window.restore() ``` -------------------------------- ### Initialize Desktop and Custom Exceptions for Pywinauto Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Initializes the `Desktop` object with the 'uia' backend and defines custom exceptions for common WeChat automation scenarios like not running, not logged in, network errors, or failure to find the main window. ```python #print_control_identifiers() from pywinauto.timings import TimeoutError import win32gui,win32con,win32api,win32com.client from pywinauto import Desktop,WindowSpecification desktop=Desktop(backend='uia')#pywinauto的桌面实例 #自定义异常 class NotStartError(Exception): def __init__(self, Error='微信未启动,请先启动并登录微信后再使用pyweixin!'): super().__init__(Error) class NotLoginError(Exception): def __init__(self, Error='微信未登录,请先点击登录后再使用pyweixin!'): super().__init__(Error) class NetWorkError(Exception): def __init__(self, Error='当前网络不可用,无法进行UI自动化!'): super().__init__(Error) class NotFoundError(Exception): def __init__(self,Error='无法识别定位到微信主界面,请在微信登录前运行无障碍服务(讲述人)后再尝试!'): super().__init__(Error) ``` -------------------------------- ### Wait for Control and Interact with Search Bar (Python) Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Demonstrates using `wait` for a control to become ready and `descendants` to locate it if `child_window` fails. Includes error handling for `TimeoutError` and basic interaction like clicking and setting text. ```python ''' wait方法用来等待控件出现,超时后会引发TimeoutError,这个时候需要异常处理, 一般不建议用,如果只是单纯的判断是否存在建议使用exists 参数: wait_for:等待控件出现的条件,包括: 'exists' means that the window is a valid handle 'visible' means that the window is not hidden 'enabled' means that the window is not disabled 'ready' means that the window is visible and enabled 'active' means that the window is active timeout:超时时间,超过这个时间不再判断直接返回False retry_interval:timeout范围内每次重试的间隔,timeout为1,retry_interval为0.1,就是1s内重试10次 ''' #pywinauto定位控件的方法参数都是kwargs,我们可以预先将控件的信息写成字典形式,然后使用**解包传入 #可以看做是POM(PageObjectModel)封装 search={'title':'搜索','control_type':'Edit','class_name':"mmui::XValidatorTextEdit"} search_bar2=main_window.descendants(**search) try: search_bar1=main_window.child_window(**search).wait(timeout=1,wait_for='ready')#微信顶部的搜索栏使用child_window方法还定位不到,只能使用descendants,而且使用dump_tree也看不到 except TimeoutError:#超时会引起 print(f'已超时捕获TimeoutError异常,该控件可能不存在,使用descendants方法尝试!') if search_bar2: search_bar2[0].click_input() search_bar2[0].set_text(f'文件传输助手') time.sleep(1) search_bar2[0].type_keys('{ENTER}') ``` -------------------------------- ### Get All Friend Names Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/contacts.md Retrieves the nicknames and remarks for all contacts. This function can be used to get a list of all your friends' names. ```python from pywechat import Contacts friends_names = Contacts.get_friends_name() for name in friends_names: print(name) ``` -------------------------------- ### Import pyweixin Class and Method Source: https://github.com/hello-mr-crab/pywechat/blob/main/README.md Demonstrates the basic structure for importing and calling methods from the pyweixin module. Ensure the correct class and method names are used. ```python from pyweixin import xx(class) xx(class).yy(method) ``` -------------------------------- ### Get Friend Info Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/00-START-HERE.md Retrieve detailed information about a specific friend, including their nickname, region, and WeChat ID. ```APIDOC ## Get Friend Info ### Description Fetch detailed information for a specified friend. ### Method `Contacts.get_friend_info` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **friend** (string) - Required - The name of the friend. ### Request Example ```python from pywechat import Contacts info = Contacts.get_friend_info(friend='小王') print(info['昵称'], info['地区'], info['微信号']) ``` ### Response #### Success Response - **昵称** (string) - The friend's nickname. - **地区** (string) - The friend's region. - **微信号** (string) - The friend's WeChat ID. ``` -------------------------------- ### Get Contact Information with PyWeChat Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/00-START-HERE.md Use Contacts.get_friend_info to retrieve detailed information about a friend, including their nickname, region, and WeChat ID. ```python from pywechat import Contacts info = Contacts.get_friend_info(friend='小王') print(info['昵称'], info['地区'], info['微信号']) ``` -------------------------------- ### Get Official Account Article URLs Source: https://github.com/hello-mr-crab/pywechat/blob/main/README.md Retrieves URLs of articles from a specified official account. Note: This method may be unstable. ```python #注意,该方法不稳定 from pyweixin import Collections Collections.collect_offAcc_articles(name='新华社',number=10) urls=Collections.cardLink_to_url(number=10) for url,text in urls.items(): print(f'{text} {url}') ``` -------------------------------- ### Get Group Chat Information Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/contacts.md Fetches detailed information about a specific group chat. You need to provide the group name to retrieve its details. ```python from pywechat import Contacts group_info = Contacts.get_group_info(group='开发小组') print(f"群聊名称: {group_info['群聊名称']}") print(f"群聊人数: {group_info['群聊人数']}") print(f"群主: {group_info['群主']}") print(f"群聊简介: {group_info['群聊简介']}") ``` -------------------------------- ### Open and Configure WeChat Window (Python) Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Opens the WeChat application, checks for login status, and configures the window size and position. Raises custom exceptions if WeChat is not running, not logged in, or the main window cannot be found. ```python def open_weixin(is_maximize:bool=False,window_size:tuple=(1000,1000))->(WindowSpecification|None): ''' 打开微信(微信需要提前登录) Args: is_maximize:微信界面是否全屏,默认不全屏 window_size:微信主界面大小,默认(1000,100),可GlobalConfig.window_size=(width,height)全局控制 ''' if not is_weixin_running(): raise NotStartError hwnd=win32gui.FindWindow('Qt51514QWindowIcon','微信') if hwnd==0: hwnd=win32gui.FindWindow('Qt51514QWindowIcon','Weixin') main_window=desktop.window(handle=hwnd) if main_window.class_name()=='mmui::LoginWindow': raise NotLoginError if main_window.class_name()=='mmui::MainWindow': main_window.restore() win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST, 0, 0,window_size[0],window_size[1],win32con.SWP_NOMOVE) window_width,window_height=window_size[0],window_size[1] screen_width,screen_height=win32api.GetSystemMetrics(win32con.SM_CXSCREEN),win32api.GetSystemMetrics(win32con.SM_CYSCREEN) new_left=(screen_width-window_width)//2 new_top=(screen_height-window_height)//2 if screen_width!=window_width: #移动窗口到屏幕中央 win32gui.MoveWindow(hwnd,new_left,new_top,window_width,window_height,True) ############################### if is_maximize: #需要使用win32gui.SendMessage全屏,main_window.maximize不管用 win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_MAXIMIZE,0) if not is_maximize: win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE,0) else: raise NotFoundError return main_window main_window=open_weixin() ``` -------------------------------- ### Configure Global Settings in pyweixin Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/configuration.md Set global configuration parameters for pyweixin, including language and audio length, and print current settings. ```python from pyweixin import GlobalConfig, Navigator, Messages # 全局设置配置参数 GlobalConfig.language = 'English' GlobalConfig.load_delay = 2.5 GlobalConfig.is_maximize = True GlobalConfig.close_weixin = False GlobalConfig.audio_length = 120 # 查看当前配置 print(GlobalConfig.Version) # 输出:4.1.9.30 print(GlobalConfig.language) # 输出:English # 之后所有方法调用都会使用这些全局设置 Navigator.search_channels(search_content='微信4.0') Navigator.search_miniprogram(name='问卷星') ``` -------------------------------- ### Catch WeChatNotStartError Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/errors.md Catch this error when attempting to use messaging functions before WeChat has started. Ensure WeChat is running before calling related methods. ```python from pywechat import Messages from pywechat.Errors import WeChatNotStartError try: Messages.send_messages_to_friend(friend='好友', messages=['你好']) except WeChatNotStartError: print("请先启动微信") ``` -------------------------------- ### Open and Configure WeChat Window with Pywinauto Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Opens the WeChat application, checks if it's running and logged in, and configures its window size and position. It supports maximizing the window and raising it to the top. Raises custom exceptions if WeChat is not running, not logged in, or the main window cannot be found. ```python def open_weixin(is_maximize:bool=False,window_size:tuple=(1000,1000))->(WindowSpecification|None): ''' 打开微信(微信需要提前登录) Args: is_maximize:微信界面是否全屏,默认不全屏 window_size:微信主界面大小,默认(1000,100),可GlobalConfig.window_size=(width,height)全局控制 ''' if not is_weixin_running(): raise NotStartError hwnd=win32gui.FindWindow('Qt51514QWindowIcon','微信') if hwnd==0: hwnd=win32gui.FindWindow('Qt51514QWindowIcon','Weixin') main_window=desktop.window(handle=hwnd) if main_window.class_name()=='mmui::LoginWindow': raise NotLoginError if main_window.class_name()=='mmui::MainWindow': main_window.restore() win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST, 0, 0,window_size[0],window_size[1],win32con.SWP_NOMOVE) window_width,window_height=window_size[0],window_size[1] screen_width,screen_height=win32api.GetSystemMetrics(win32con.SM_CXSCREEN),win32api.GetSystemMetrics(win32con.SM_CYSCREEN) new_left=(screen_width-window_width)//2 new_top=(screen_height-window_height)//2 if screen_width!=window_width: #移动窗口到屏幕中央 win32gui.MoveWindow(hwnd,new_left,new_top,window_width,window_height,True) ############################### if is_maximize: #需要使用win32gui.SendMessage全屏,main_window.maximize不管用 win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_MAXIMIZE,0) if not is_maximize: win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE,0) else: raise NotFoundError return main_window main_window=open_weixin() ``` -------------------------------- ### Open and Control WeChat Window with Pywinauto Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb This snippet demonstrates how to open WeChat, check if it's running, and interact with its main window. It includes custom exceptions for error handling and functions to manage the WeChat window's state (restoring, resizing, maximizing). ```python # pywinauto对控件通用的输入操作 import time from pywinauto.timings import TimeoutError import win32gui,win32con,win32api,win32com.client from pywinauto import Desktop,WindowSpecification desktop=Desktop(backend='uia')#pywinauto的桌面实例 #自定义异常 class NotStartError(Exception): def __init__(self, Error='微信未启动,请先启动并登录微信后再使用pyweixin!'): super().__init__(Error) class NotLoginError(Exception): def __init__(self, Error='微信未登录,请先点击登录后再使用pyweixin!'): super().__init__(Error) class NetWorkError(Exception): def __init__(self, Error='当前网络不可用,无法进行UI自动化!'): super().__init__(Error) class NotFoundError(Exception): def __init__(self,Error='无法识别定位到微信主界面,请在微信登录前运行无障碍服务(讲述人)后再尝试!'): super().__init__(Error) def is_weixin_running()->bool: ''' 该方法通过检测当前windows系统的进程中 是否有Weixin.exe该项进程来判断微信是否在运行 ''' wmi=win32com.client.GetObject('winmgmts:') processes=wmi.InstancesOf('Win32_Process') for process in processes: if process.Name.lower()=='Weixin.exe'.lower(): return True return False def open_weixin(is_maximize:bool=False,window_size:tuple=(1000,1000))->(WindowSpecification|None): ''' 打开微信(微信需要提前登录) Args: is_maximize:微信界面是否全屏,默认不全屏 window_size:微信主界面大小,默认(1000,100),可GlobalConfig.window_size=(width,height)全局控制 ''' if not is_weixin_running(): raise NotStartError hwnd=win32gui.FindWindow('Qt51514QWindowIcon','微信') if hwnd==0: hwnd=win32gui.FindWindow('Qt51514QWindowIcon','Weixin') main_window=desktop.window(handle=hwnd) if main_window.class_name()=='mmui::LoginWindow': raise NotLoginError if main_window.class_name()=='mmui::MainWindow': main_window.restore() win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST, 0, 0,window_size[0],window_size[1],win32con.SWP_NOMOVE) window_width,window_height=window_size[0],window_size[1] screen_width,screen_height=win32api.GetSystemMetrics(win32con.SM_CXSCREEN),win32api.GetSystemMetrics(win32con.SM_CYSCREEN) new_left=(screen_width-window_width)//2 new_top=(screen_height-window_height)//2 if screen_width!=window_width: #移动窗口到屏幕中央 win32gui.MoveWindow(hwnd,new_left,new_top,window_width,window_height,True) ############################### if is_maximize: #需要使用win32gui.SendMessage全屏,main_window.maximize不管用 win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_MAXIMIZE,0) if not is_maximize: win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE,0) else: raise NotFoundError return main_window main_window=open_weixin() from pywinauto.controls import uia_controls#ctrl+鼠标单击跳转即可看到下列方法的源代码 CurrentChatEdit={'control_type':'Edit','auto_id':'chat_input_field'}#微信主界面下当前的聊天窗口 edit_area=main_window.child_window(**CurrentChatEdit) '''pywinauto中,直接作用在控件上的点击操作主要包含以下两种: edit_area.type_keys("text",with_spaces=True): 打字的方式向编辑框内输入文本 edit_area.type_keys("{ENTER}"):按下键盘上的Enter键 edit_area.set_text("text"):直接设置编辑框的文本(会清除掉先前的内容) ''' edit_area.type_keys("你 好,文 件 传 输 助 手!",with_spaces=True) edit_area.type_keys("{ENTER}")#按下回车 edit_area.set_text("你 好,文 件 传 输 助 手!")#直接设置文本,不打字 edit_area.type_keys("{ENTER}")#按下回车 ``` -------------------------------- ### Get Multiple Friends Info - pywechat Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/contacts.md Fetches detailed information for multiple WeChat friends by providing a list of their remarks or nicknames. Requires the 'pywechat' library. ```python from pywechat import Contacts friends = ['小王', '小李', '小张'] infos = Contacts.get_friends_info(friends=friends) for info in infos: print(f"{info['昵称']} ({info['备注']}): {info['地区']}") ``` -------------------------------- ### Navigator.search_miniprogram Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/wechattools.md Searches for and opens a specified mini-program. Allows configuration of load delay, window maximization, and WeChat closure. ```APIDOC ## Navigator.search_miniprogram ### Description Searches for and opens a specified mini-program. Allows configuration of load delay, window maximization, and WeChat closure. ### Method Signature ```python @staticmethod def search_miniprogram( name: str, load_delay: float = None, is_maximize: bool = None, close_wechat: bool = None ) -> WindowSpecification ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Default Value | Description | |---|---|---|---| | name | str | — | Mini-program name | | load_delay | float | GlobalConfig.load_delay | Delay for mini-program loading (seconds) | | is_maximize | bool | GlobalConfig.is_maximize | Whether to display in full screen | | close_wechat | bool | GlobalConfig.close_wechat | Whether to close WeChat after the task is completed | ### Returns WindowSpecification object for the mini-program window. ### Usage Example ```python from pywechat import Navigator miniapp_window = Navigator.search_miniprogram( name='问卷星', load_delay=5 ) ``` ``` -------------------------------- ### Get Single Friend Info - pywechat Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/api-reference/contacts.md Retrieves detailed information for a single WeChat friend using their remark or nickname. Ensure the 'pywechat' library is imported. ```python from pywechat import Contacts info = Contacts.get_friend_info(friend='小王') print(f"昵称: {info['昵称']}") print(f"备注: {info['备注']}") print(f"地区: {info['地区']}") print(f"个性签名: {info['个性签名']}") print(f"微信号: {info['微信号']}") ``` -------------------------------- ### Get Friend Information with pywechat Source: https://github.com/hello-mr-crab/pywechat/blob/main/_autodocs/README.md Retrieve information about a friend using the Contacts module. The friend's name is required as an argument. The retrieved info is then printed. ```python from pywechat import Contacts info = Contacts.get_friend_info(friend='小王') print(info) ``` -------------------------------- ### Configure Global Settings for pyweixin-rpa Source: https://github.com/hello-mr-crab/pywechat/blob/main/Skill/OpenClaw/pyweixin-rpa/references/api_reference.md Set global parameters like language, load delay, and maximize window to avoid repetitive configuration in each method. These settings affect subsequent operations. ```python from pyweixin.Config import GlobalConfig ``` ```python # 示例:全局配置 GlobalConfig.language = 'English' GlobalConfig.load_delay = 3.5 GlobalConfig.is_maximize = True GlobalConfig.close_weixin = False Navigator.search_channels(search_content='微信4.0') ``` -------------------------------- ### Define Custom Exceptions for WeChat Automation Source: https://github.com/hello-mr-crab/pywechat/blob/main/pywinauto使用方法.ipynb Custom exceptions are defined to handle specific error conditions during WeChat automation, such as the application not being started or the user not being logged in. ```python #pywinauto访问底层元素信息 from pywinauto.timings import TimeoutError import win32gui,win32con,win32api,win32com.client from pywinauto import Desktop,WindowSpecification desktop=Desktop(backend='uia')#pywinauto的桌面实例 #自定义异常 class NotStartError(Exception): def __init__(self, Error='微信未启动,请先启动并登录微信后再使用pyweixin!'): super().__init__(Error) class NotLoginError(Exception): def __init__(self, Error='微信未登录,请先点击登录后再使用pyweixin!'): super().__init__(Error) class NetWorkError(Exception): def __init__(self, Error='当前网络不可用,无法进行UI自动化!'): super().__init__(Error) class NotFoundError(Exception): def __init__(self,Error='无法识别定位到微信主界面,请在微信登录前运行无障碍服务(讲述人)后再尝试!'): super().__init__(Error) ``` -------------------------------- ### GlobalConfig Source: https://github.com/hello-mr-crab/pywechat/blob/main/Skill/OtherPlatforms/pyweixin-rpa/references/api_reference.md GlobalConfig allows setting global parameters to avoid repetitive input in each method. It includes settings for window behavior, delays, search pages, and language. ```APIDOC ## GlobalConfig `GlobalConfig` can be used to set global parameters, saving you from repeatedly passing the same parameters in each method. | Attribute | Type | Default Value | Description | |---|---|---|---| | `is_maximize` | `bool` | `False` | WeChat main interface fullscreen | | `close_weixin` | `bool` | `False` | Close WeChat after task ends | | `load_delay` | `float` | `3.5` | Loading wait time for opening mini programs/video accounts/official accounts | | `search_pages` | `int` | `5` | Number of pages for searching in the chat list | | `window_maximize` | `bool` | `False` | Independent window fullscreen | | `send_delay` | `float` | `0.2` | Delay between sending messages | | `audio_length` | `int` | `60` | Voice message length (seconds), available in WeChat 4.1.9+ | | `clear` | `bool` | `True` | Whether to clear the input box before sending | | `window_size` | `tuple` | `(1000, 1000)` | Main interface size | | `language` | `str` | Auto-detect | WeChat language: `简体中文` / `English` / `繁體中文` | | `Version` | `str` | Auto-get | WeChat version number | ```python # Example: Global configuration GlobalConfig.language = 'English' GlobalConfig.load_delay = 3.5 GlobalConfig.is_maximize = True GlobalConfig.close_weixin = False ``` ```