### Go Language Code Block Example Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Provides an example of a Go language code block with syntax highlighting, demonstrating a simple 'Hello World' program using `fmt.Println`. ```go func main() { fmt.Println("Hello World") } ``` -------------------------------- ### Initialize WeChat Instance with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/start/index.html This snippet demonstrates how to import the `WeChat` class from the `wxauto` library and initialize an instance of it. This is the first step to interact with WeChat using `wxauto` for automation tasks. ```Python from wxauto import WeChat # Initialize WeChat instance wx = WeChat() ``` -------------------------------- ### Basic WeChat Automation with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This example demonstrates the fundamental usage of the `wxauto` library to initialize a WeChat instance, send a message to a specific contact, and retrieve all messages from the current chat window, printing their content and type. ```Python from wxautox import WeChat # 初始化微信实例 wx = WeChat() # 发送消息 wx.SendMsg("你好", who="张三") # 获取当前聊天窗口消息 msgs = wx.GetAllMessage() for msg in msgs: print(f"消息内容: {msg.content}, 消息类型: {msg.type}") ``` -------------------------------- ### Markdown Link Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Shows how to create inline links in Markdown using the `[link text](url)` syntax, with an example linking to the Hugo website. ```markdown [Hugo](https://gohugo.io) ``` -------------------------------- ### Install wxauto Python library Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/_index.md This command installs the `wxauto` Python library using pip, making it available for use in Python projects for WeChat automation. ```bash pip install wxauto ``` -------------------------------- ### Listen for and process incoming WeChat messages with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This example illustrates how to set up a listener for incoming messages from a specific chat using `wxauto`. It defines a callback function to handle messages, demonstrating logging to a file, automatic media download, and an auto-reply mechanism for friend messages. The snippet also shows how to keep the program running and later remove the listener. ```python from wxautox import WeChat from wxautox.msgs import FriendMessage import time wx = WeChat() # 消息处理函数 def on_message(msg, chat): # 示例1:将消息记录到本地文件 with open('msgs.txt', 'a', encoding='utf-8') as f: f.write(msg.content + '\n') # 示例2:自动下载图片和视频 if msg.type in ('image', 'video'): print(msg.download()) # 示例3:自动回复收到 if isinstance(msg, FriendMessage): time.sleep(len(msg.content)) msg.quote('收到') ...# 其他处理逻辑,配合Message类的各种方法,可以实现各种功能 # 添加监听,监听到的消息用on_message函数进行处理 wx.AddListenChat(nickname="张三", callback=on_message) # 保持程序运行 wx.KeepRunning() # ... 程序运行一段时间后 ... # 移除监听 wx.RemoveListenChat(nickname="张三") ``` -------------------------------- ### Retrieving Multiple WeChat Client Instances Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This example shows how to use `wxauto` to obtain a list of all currently running WeChat client instances. It iterates through the retrieved clients and prints their details, useful for managing multiple WeChat accounts. ```Python from wxautox import get_wx_clients # 获取所有微信客户端 clients = get_wx_clients() for client in clients: print(f"微信客户端: {client}") ``` -------------------------------- ### Markdown Table Syntax Example Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/blog/markdown/index.html Demonstrates the basic syntax for creating tables in Markdown, including header and data rows, separated by hyphens. ```Markdown | Syntax | Description | | --------- | ----------- | | Header | Title | | Paragraph | Text | ``` -------------------------------- ### Retrieve All Messages from Current Chat Window with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/start/index.html This snippet illustrates how to fetch all messages from the currently active chat window using the `GetAllMessage` method of the `wxauto` WeChat instance. It then iterates through the retrieved messages and prints the sender and content of each message to the console. ```Python # Get messages from current chat window msgs = wx.GetAllMessage() for msg in msgs: print('==' * 30) print(f"{msg.sender}: {msg.content}") ``` -------------------------------- ### Get Multiple WeChat Clients using wxautox Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This snippet demonstrates how to retrieve all active WeChat client instances using the `get_wx_clients` function from the `wxautox` library. It then iterates through the returned clients and prints their information, useful for managing multiple WeChat accounts. ```Python from wxautox import get_wx_clients # 获取所有微信客户端 clients = get_wx_clients() for client in clients: print(f"微信客户端: {client}") ``` -------------------------------- ### Python SessionElement Access Example Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/other/index.html This example demonstrates how to retrieve and access `SessionElement` objects from a `WeChat` instance. It shows how to get a list of sessions and access the first one. ```Python from wxauto import WeChat wx = WeChat() sessions = wx.GetSession() session = sessions[0] # 获取第一个会话 ``` -------------------------------- ### Install wxautox Python Library Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/install/index.html Instructions for installing the wxautox Python library using pip, including options for specific Python versions. This library requires Python 3.9 to 3.12. ```Shell pip install wxautox py -3.12 -m pip install wxautox ``` -------------------------------- ### Markdown Image Embedding Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Explains how to embed images in Markdown documents using the `![alt text](url)` syntax, providing an example with a GitHub logo. ```markdown ![GitHub Logo](https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png) ``` -------------------------------- ### Get New Friend Requests (wxauto) Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/wechat/index.html Retrieves a list of new friend requests, with an option to filter out already accepted requests. Includes an example of how to accept requests, set remarks, and add 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) # 接受好友请求,并设置备注和标签 ``` ```APIDOC wx.GetNewFriends(acceptable: bool = True) - Description: Retrieves a list of new friend requests. - Parameters: - acceptable (bool, default: True): Whether to filter out already accepted friend requests. - Returns: List[NewFriendElement] - List of new friend requests. ``` -------------------------------- ### Markdown Table Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Shows how to create tables in Markdown using pipes (`|`) to separate columns and hyphens (`-`) to define header separators. ```markdown | Syntax | Description | | --------- | ----------- | | Header | Title | | Paragraph | Text | ``` -------------------------------- ### Processing WeChat Friend Requests Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This example illustrates how to retrieve and accept new friend requests using `wxauto`. It iterates through acceptable new friends, accepts each request, and sets a custom remark and tags for the new contact. ```Python from wxautox import WeChat wx = WeChat() # 获取新的好友申请 newfriends = wx.GetNewFriends(acceptable=True) # 处理好友申请 tags = ['同学', '技术群'] for friend in newfriends: remark = f'备注_{friend.name}' friend.Accept(remark=remark, tags=tags) # 接受好友请求,并设置备注和标签 ``` -------------------------------- ### Manage Dark/Light Theme Switching in JavaScript Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/tags/example/index.html This JavaScript snippet handles dynamic theme switching for a webpage. It checks local storage for a saved theme preference ('dark' or 'light') and falls back to a default theme or system preference if none is found. It applies the appropriate CSS class ('dark') to the document's root element and updates the `colorScheme` property to reflect the chosen theme. ```javascript const defaultTheme = 'system'; const setDarkTheme = () => { document.documentElement.classList.add("dark"); document.documentElement.style.colorScheme = "dark"; } const setLightTheme = () => { document.documentElement.classList.remove("dark"); document.documentElement.style.colorScheme = "light"; } if ("color-theme" in localStorage) { localStorage.getItem("color-theme") === "dark" ? setDarkTheme() : setLightTheme(); } else { defaultTheme === "dark" ? setDarkTheme() : setLightTheme(); if (defaultTheme === "system") { window.matchMedia("(prefers-color-scheme: dark)").matches ? setDarkTheme() : setLightTheme(); } } ``` -------------------------------- ### Send and Receive WeChat Messages with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/install/index.html Demonstrates how to initialize the WeChat instance using the wxauto library, send a message to a specific contact, and retrieve all messages from the current chat window. This example showcases basic automation capabilities. ```Python from wxauto import WeChat # 开源版 # from wxautox import WeChat # ✨Plus版 # 初始化微信实例 wx = WeChat() # 发送消息 wx.SendMsg("你好", who="文件传输助手") # 获取当前聊天窗口消息 msgs = wx.GetAllMessage() for msg in msgs: print('==' * 30) print(f"{msg.sender}: {msg.content}") ``` -------------------------------- ### Merge and Forward WeChat Messages with wxautox Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This example demonstrates how to merge and forward multiple WeChat messages to specified targets. It uses the `WeChat` class to interact with a chat window, retrieves messages, multi-selects the last five human messages, and then forwards them to a list of recipients. ```Python from wxautox import WeChat from wxautox.msgs import HumanMessage wx = WeChat() # 打开指定聊天窗口 wx.ChatWith("工作群") # 获取消息列表 msgs = wx.GetAllMessage() # 多选最后五条消息 n = 0 for msg in msgs[::-1]: if n >= 5: break if isinstance(msg, HumanMessage): n += 1 msg.multi_select() # 执行合并转发 targets = [ '张三', '李四' ] wx.MergeForward(targets) ``` -------------------------------- ### Listening for Incoming WeChat Messages Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This snippet shows how to set up a message listener using `wxauto`. It defines a callback function `on_message` to process incoming messages, including saving them to a file, downloading media, and quoting replies. It also demonstrates adding and removing listeners for specific chat contacts. ```Python from wxautox import WeChat from wxautox.msgs import FriendMessage import time wx = WeChat() # 消息处理函数 def on_message(msg, chatname): text = f'[{msg.type} {msg.attr}]{chatname} - {msg.content}' print(text) with open('msgs.txt', 'a', encoding='utf-8') as f: f.write(text + '\n') if msg.type in ('image', 'video'): print(msg.download()) if isinstance(msg, FriendMessage): time.sleep(len(msg.content)) msg.quote('收到') ...# 其他处理逻辑,配合Message类的各种方法,可以实现各种功能 # 添加监听,监听到的消息用on_message函数进行处理 wx.AddListenChat(nickname="张三", callback=on_message) # ... 程序运行一段时间后 ... # 移除监听 wx.RemoveListenChat(nickname="张三") ``` -------------------------------- ### Markdown Headings Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Demonstrates the syntax for creating headings of different levels in Markdown, from H1 to H6, using hash symbols. ```text # Heading 1 ## Heading 2 ### Heading 3 #### Heading 4 ##### Heading 5 ###### Heading 6 ``` -------------------------------- ### Perform Automatic WeChat Login with wxautox Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This code illustrates how to initiate an automatic login process for WeChat using the `LoginWnd` class from `wxautox`. It requires the path to the WeChat executable and is effective only for WeChat instances configured for automatic login. ```Python from wxautox import LoginWnd wxpath = "D:/path/to/WeChat.exe" # 创建登录窗口 loginwnd = LoginWnd(wxpath) # 登录微信 loginwnd.login() ``` -------------------------------- ### Send and retrieve messages using wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This snippet demonstrates the fundamental usage of the `wxauto` library. It initializes a WeChat instance, sends a text message to a specified contact, and then retrieves and prints all messages from the current chat window, showing their content and type. ```python from wxautox import WeChat # 初始化微信实例 wx = WeChat() # 发送消息 wx.SendMsg("你好", who="张三") # 获取当前聊天窗口消息 msgs = wx.GetAllMessage() for msg in msgs: print(f"消息内容: {msg.content}, 消息类型: {msg.type}") ``` -------------------------------- ### Initialize Page Theme from Local Storage or System Preference Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/tags/guide/index.html This JavaScript snippet initializes the web page's color theme based on user preference stored in `localStorage` or the system's preferred color scheme. It defines functions to apply dark or light themes by manipulating CSS classes and `colorScheme`. If no preference is found, it defaults to 'system' and checks `prefers-color-scheme`. ```javascript const defaultTheme = 'system'; const setDarkTheme = () => { document.documentElement.classList.add("dark"); document.documentElement.style.colorScheme = "dark"; } const setLightTheme = () => { document.documentElement.classList.remove("dark"); document.documentElement.style.colorScheme = "light"; } if ("color-theme" in localStorage) { localStorage.getItem("color-theme") === "dark" ? setDarkTheme() : setLightTheme(); } else { defaultTheme === "dark" ? setDarkTheme() : setLightTheme(); if (defaultTheme === "system") { window.matchMedia("(prefers-color-scheme: dark)").matches ? setDarkTheme() : setLightTheme(); } } ``` -------------------------------- ### Markdown Unordered List Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Shows how to create unordered lists and nested list items in Markdown using asterisks as bullet points. ```text * Item 1 * Item 2 * Item 2a * Item 2b ``` -------------------------------- ### Giscus Comment System and Theme Toggle Initialization Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This JavaScript code initializes the Giscus comment system on the webpage and sets up event listeners for theme toggles. It dynamically creates and appends the Giscus script, ensuring the comment section's theme matches the site's current theme settings. ```JavaScript function getHugoTheme(){return localStorage.getItem("color-theme")}function getGiscusTheme(){let e="light";return getHugoTheme()=="light"?e.replace("dark","light"):e.replace("light","dark")}function setGiscusTheme(){function e(e){const t=document.querySelector("iframe.giscus-frame");if(!t)return;t.contentWindow.postMessage({giscus:e},"https://giscus.app")}e({setConfig:{theme:getGiscusTheme()}})}document.addEventListener("DOMContentLoaded",function(){const n={src:"https://giscus.app/client.js","data-repo":"cluic/wxauto_doc_web","data-repo-id":"R_kgDONhkCTQ","data-category":"General","data-category-id":"DIC_kwDONhkCTc4Cqx3W","data-mapping":"pathname","data-strict":"0","data-reactions-enabled":"1","data-emit-metadata":"0","data-input-position":"top","data-theme":getGiscusTheme(),"data-lang":"zh-CN",crossorigin:"anonymous",async:""},e=document.createElement("script");Object.entries(n).forEach(([t,n])=>e.setAttribute(t,n)),document.getElementById("giscus").appendChild(e);const t=document.querySelectorAll(".theme-toggle");t&&t.forEach(e=>e.addEventListener("click",setGiscusTheme))}) ``` -------------------------------- ### Markdown Ordered List Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Demonstrates the syntax for creating ordered lists and nested ordered list items in Markdown using numbers followed by periods. ```text 1. Item 1 2. Item 2 3. Item 3 1. Item 3a 2. Item 3b ``` -------------------------------- ### Send messages with typing simulation in wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This example shows how to send messages using a 'typing machine' effect, which simulates a user typing the message character by character. It covers sending simple text messages and more complex messages that include newlines and '@' mentions for specific contacts in a group chat. ```python from wxautox import WeChat wx = WeChat() # 普通文本发送 wx.SendTypingText("你好,这是一条测试消息", who="张三") # 使用@功能和换行 wx.SendTypingText("各位好:\n{@张三} 请负责前端部分\n{@李四} 请负责后端部分", who="项目群") ``` -------------------------------- ### Integrate Giscus Comments and Sync Theme in JavaScript Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/tags/example/index.html This JavaScript code integrates the Giscus comment system into a webpage and ensures its theme synchronizes with the page's current light/dark mode. It dynamically creates and appends the Giscus script tag with necessary configuration attributes. It also sets up an event listener on theme toggles to send a message to the Giscus iframe, updating its theme to match the page's theme. ```javascript function getHugoTheme() { return localStorage.getItem("color-theme"); } function getGiscusTheme() { let giscusTheme = "light"; if(getHugoTheme() == 'light') { return giscusTheme.replace('dark', 'light'); } else { return giscusTheme.replace('light', 'dark'); } } function setGiscusTheme() { function sendMessage(message) { const iframe = document.querySelector('iframe.giscus-frame'); if (!iframe) return; iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app'); } sendMessage({ setConfig: { theme: getGiscusTheme(), }, }); } document.addEventListener('DOMContentLoaded', function () { const giscusAttributes = { "src": "https://giscus.app/client.js", "data-repo": "cluic\\/wxauto_doc_web", "data-repo-id": "R_kgDONhkCTQ", "data-category": "General", "data-category-id": "DIC_kwDONhkCTc4Cqx3W", "data-mapping": "pathname", "data-strict": "0", "data-reactions-enabled": "1", "data-emit-metadata": "0", "data-input-position": "top", "data-theme": getGiscusTheme(), "data-lang": "zh-CN", "crossorigin": "anonymous", "async": "", }; const giscusScript = document.createElement("script"); Object.entries(giscusAttributes).forEach(([key, value]) => giscusScript.setAttribute(key, value)); document.getElementById('giscus').appendChild(giscusScript); const toggles = document.querySelectorAll(".theme-toggle"); if (toggles) { toggles.forEach(toggle => toggle.addEventListener('click', setGiscusTheme)); } }); ``` -------------------------------- ### Automate accepting new WeChat friend requests using wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This snippet demonstrates how to programmatically handle new friend requests with `wxauto`. It retrieves a list of acceptable friend requests and then iterates through them, accepting each one while setting a custom remark and assigning predefined tags. ```python from wxautox import WeChat wx = WeChat() # 获取新的好友申请 newfriends = wx.GetNewFriends(acceptable=True) # 处理好友申请 tags = ['同学', '技术群'] for friend in newfriends: remark = f'备注_{friend.name}' friend.accept(remark=remark, tags=tags) # 接受好友请求,并设置备注和标签 ``` -------------------------------- ### Markdown Emphasis Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Illustrates the Markdown syntax for italic and bold text using asterisks and underscores, including how to combine them for both italic and bold formatting. ```text *This text will be italic* _This will also be italic_ **This text will be bold** __This will also be bold__ _You **can** combine them_ ``` -------------------------------- ### JavaScript Theme Switching Logic Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This JavaScript snippet implements a theme switching mechanism (light/dark mode) based on local storage preferences or system settings. It modifies CSS classes and color scheme properties on the document's root element to apply the selected theme. ```JavaScript const defaultTheme="system",setDarkTheme=()=>{document.documentElement.classList.add("dark"),document.documentElement.style.colorScheme="dark"},setLightTheme=()=>{document.documentElement.classList.remove("dark"),document.documentElement.style.colorScheme="light"};"color-theme"in localStorage?localStorage.getItem("color-theme")==="dark"?setDarkTheme():setLightTheme():(defaultTheme==="dark"?setDarkTheme():setLightTheme(),defaultTheme==="system"&&(window.matchMedia("(prefers-color-scheme: dark)").matches?setDarkTheme():setLightTheme())) ``` -------------------------------- ### WeChat Login and QR Code Operations with LoginWnd Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/other/index.html The `LoginWnd` class facilitates WeChat login, QR code retrieval, and application management. It provides methods to start, reopen, and log into the WeChat client. ```Python from wxautox import LoginWnd wxlogin = LoginWnd(app_path="...") ``` ```APIDOC LoginWnd(app_path: str = None) - Class for WeChat login and QR code operations. app_path: str - The path to the WeChat client executable. login(timeout: int = 10) -> WxResponse - Logs into WeChat. timeout: int - The login timeout in seconds. get_qrcode(path: str = None) -> str path: str - The save path for the QR code image. If None, it saves to the local 'wxauto_qrcode' folder. reopen() - Reopens the WeChat application. - Suggestion: Call this method before 'login' or 'get_qrcode' to avoid interference from pop-up windows. open() - Starts the WeChat application. - Suggestion: It is recommended to pass the 'app_path' parameter during initialization to prevent startup failures. ``` -------------------------------- ### Manage Chat Window Properties and Actions (chat object) Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/chat/index.html This section details the properties and methods available on the `chat` object for interacting with the current chat window, including retrieving its type, displaying it, and getting comprehensive information. ```APIDOC chat.chat_type - Description: Retrieves the type of the current chat window. - Returns: string, one of 'friend', 'group', 'service', 'official'. - Example: chat_type = chat.chat_type chat.Show() - Description: Displays the current chat window. chat.ChatInfo() - Description: Retrieves detailed information about the current chat window. - Returns: dict, containing chat_type, chat_name, and optionally group_member_count or company. - Return Examples: # Friend {'chat_type': 'friend', 'chat_name': '张三'} # Group {'group_member_count': 500, 'chat_type': 'group', 'chat_name': '工作群'} # Service {'company': '@肯德基', 'chat_type': 'service', 'chat_name': '店长xxx'} # Official Account {'chat_type': 'official', 'chat_name': '肯德基'} ``` -------------------------------- ### Get Dialog Box in Python Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/Chat.md Illustrates how to retrieve an active dialog box using `wx.GetDialog()` and interact with it, such as clicking a button. It includes an implicit wait time for the dialog to appear. ```python if dialog := wx.GetDialog(): dialog.click_button("确定") ``` -------------------------------- ### Python WxParam Class Configuration Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/other/index.html This example illustrates how to modify default parameters of the `wxauto` library using the `WxParam` class before initializing the `WeChat` instance. It specifically shows how to set the `LISTENER_EXCUTOR_WORKERS` attribute. ```Python from wxautox import WxParam # 设置8个监听线程 WxParam.LISTENER_EXCUTOR_WORKERS = 8 ... ``` -------------------------------- ### Manage WeChat Login and QR Code with LoginWnd Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/Other.md Introduces the `LoginWnd` class, designed for WeChat login operations and QR code retrieval. It details the class constructor, which allows specifying the WeChat client path, and provides methods for logging in, getting QR codes, reopening, and opening the WeChat client. ```python from wxautox import LoginWnd wxlogin = LoginWnd(app_path="...") ``` ```APIDOC LoginWnd Class Constructor: __init__(app_path: str = None): Description: Initializes the LoginWnd class. Parameters: app_path (str, default: None): Path to the WeChat client application. LoginWnd Methods: login(timeout: int = 10): Description: Logs into WeChat. Parameters: timeout (int, default: 10): Login timeout in seconds. Returns: WxResponse get_qrcode(path: str = None): Description: Gets the QR code for login. Parameters: path (str, default: None): Save path for the QR code image. If None, it saves to the wxauto_qrcode folder in the local directory. Returns: str (path to the QR code image) reopen(): Description: Reopens WeChat. It is recommended to call this method before executing login or get_qrcode to avoid interference from various pop-up windows. Parameters: None Returns: None open(): Description: Starts WeChat. It is recommended to pass the app_path parameter during initialization, otherwise, it may fail to start. Parameters: None Returns: None ``` -------------------------------- ### Send Message to a Specific Recipient using wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/start/index.html This example shows how to send a text message to a specific recipient using the `SendMsg` method of the `wxauto` WeChat instance. It sends '你好' (Hello) to '文件传输助手' (File Transfer Assistant), demonstrating basic message sending functionality. ```Python # Send message wx.SendMsg("你好", who="文件传输助手") ``` -------------------------------- ### Retrieve WeChat Login QR Code using wxautox Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/index.html This snippet shows how to obtain the path to the WeChat login QR code image. It utilizes the `LoginWnd` class and its `get_qrcode` method to save the QR code image, which can then be displayed for manual scanning and login. ```Python from wxautox import LoginWnd wxpath = "D:/path/to/WeChat.exe" # 创建登录窗口 loginwnd = LoginWnd(wxpath) # 获取登录二维码图片路径 qrcode_path = loginwnd.get_qrcode() print(qrcode) ``` -------------------------------- ### Python WxResponse Class Usage Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/other/index.html This example demonstrates how to use the `WxResponse` class to handle return values from `wxauto` methods. It shows how to check for success and access data or error messages based on the `WxResponse` object. ```Python # 这里假设result为某个方法的WxResponse类型返回值 result: WxResponse = ... # 判断是否成功 if result: data = result['data'] # 成功,获取返回数据,大多数情况下为None else: print(result['message']) # 该方法调用失败,打印错误信息 ``` -------------------------------- ### Giscus Comment System Initialization and Theme Synchronization Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/deploy/index.html This JavaScript snippet handles the dynamic loading of the Giscus comment system script and ensures its theme synchronizes with the website's current color theme. It defines functions to get the current Hugo theme from local storage, derive the corresponding Giscus theme, and post messages to the Giscus iframe to update its theme. The main script dynamically creates and appends the Giscus script tag to the DOM and attaches event listeners to theme toggle buttons. ```javascript function getHugoTheme(){return localStorage.getItem("color-theme")}function getGiscusTheme(){let e="light";return getHugoTheme()=="light"?e.replace("dark","light"):e.replace("light","dark")}function setGiscusTheme(){function e(e){const t=document.querySelector("iframe.giscus-frame");if(!t)return;t.contentWindow.postMessage({giscus:e},"https://giscus.app")}e({setConfig:{theme:getGiscusTheme()}})}document.addEventListener("DOMContentLoaded",function(){const n={src:"https://giscus.app/client.js","data-repo":"cluic/wxauto_doc_web","data-repo-id":"R_kgDONhkCTQ","data-category":"General","data-category-id":"DIC_kwDONhkCTc4Cqx3W","data-mapping":"pathname","data-strict":"0","data-reactions-enabled":"1","data-emit-metadata":"0","data-input-position":"top","data-theme":getGiscusTheme(),"data-lang":"zh-CN",crossorigin:"anonymous",async:""},e=document.createElement("script");Object.entries(n).forEach(([t,n])=>e.setAttribute(t,n)),document.getElementById("giscus").appendChild(e);const t=document.querySelectorAll(".theme-toggle");t&&t.forEach(e=>e.addEventListener("click",setGiscusTheme))}) ``` -------------------------------- ### Initialize WeChat Main Window Instance Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/concepts.md Demonstrates how to create an instance of the `WeChat` class, which serves as the main entry point for WeChat automation. The `nickname` parameter can be used to specify a target WeChat window. ```Python wx = WeChat(nickname="张三") ``` -------------------------------- ### Retrieve Moments Content using GetMoments Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/moment/index.html This Python example shows how to fetch Moments content from the current page and how to paginate to get content from the next page using the `GetMoments` method of the `MomentsWnd` object. ```Python # 获取当前页面的朋友圈内容 moments = pyq.GetMoments() # 通过`next_page`参数获取下一页的朋友圈内容 moments = pyq.GetMoments(next_page=True) ``` -------------------------------- ### Initialize and Manage Dark/Light Theme Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/tags/markdown/index.html This JavaScript snippet initializes the website's color theme based on local storage preferences or the system's preferred color scheme. It defines functions to apply dark or light themes by manipulating CSS classes and the `colorScheme` property on the document's root element. ```JavaScript const defaultTheme="system",setDarkTheme=()=>{document.documentElement.classList.add("dark"),document.documentElement.style.colorScheme="dark"},setLightTheme=()=>{document.documentElement.classList.remove("dark"),document.documentElement.style.colorScheme="light"};"color-theme"in localStorage?localStorage.getItem("color-theme")==="dark"?setDarkTheme():setLightTheme():(defaultTheme==="dark"?setDarkTheme():setLightTheme(),defaultTheme==="system"&&(window.matchMedia("(prefers-color-scheme: dark)").matches?setDarkTheme():setLightTheme())) ``` -------------------------------- ### Initialize wxautox WeChat Object Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/wechat/index.html Demonstrates how to initialize the `WeChat` object from the `wxautox` library. The `nickname` and `debug` parameters can be optionally provided during initialization to specify the target WeChat window or enable debug mode. ```text ``` -------------------------------- ### Sending WeChat Messages with Typing Mode Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/example/example/index.html This snippet demonstrates sending messages with a simulated typing effect using `wxauto`'s `SendTypingText` method. It shows examples for sending plain text and messages with `@`mentions and newlines to specific contacts or groups. ```Python from wxautox import WeChat wx = WeChat() # 普通文本发送 wx.SendTypingText("你好,这是一条测试消息", who="张三") # 使用@功能和换行 wx.SendTypingText("各位好:\n{@张三} 请负责前端部分\n{@李四} 请负责后端部分", who="项目群") ``` -------------------------------- ### Activate wxautox Plus Version Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/install/index.html Command-line instruction to activate the wxautox Plus version using a provided activation code. This step is necessary to unlock full features of the Plus edition. ```Shell wxautox -a 激活码 ``` -------------------------------- ### Get My WeChat Information with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/WeChat.md Retrieves personal WeChat information, such as WeChat ID. ```python wx.GetMyInfo() ``` ```APIDOC GetMyInfo() - Description: Retrieves personal WeChat information (e.g., WeChat ID). - Returns: Dict[str, str] - A dictionary containing personal information. ``` -------------------------------- ### Initialize WeChat Class Instance Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/WeChat.md Demonstrates how to create an instance of the `WeChat` class. The constructor allows for optional parameters like `nickname` to target a specific WeChat window and `debug` to enable debugging mode. ```python from wxautox import WeChat wx = WeChat() ``` -------------------------------- ### Get My Information (wxauto) Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/wechat/index.html Retrieves personal WeChat information, such as WeChat ID. ```Python wx.GetMyInfo() ``` ```APIDOC wx.GetMyInfo() - Description: Retrieves personal WeChat information. - Returns: Dict[str, str] ``` -------------------------------- ### API: Get URL from Link Message Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/message/index.html Extracts the URL from a link message. A timeout can be specified for the operation. ```APIDOC msg.get_url(timeout: int = 10) Description: Retrieves the URL embedded in a link message. Parameters: timeout: int = 10 Description: Timeout for retrieving the URL in seconds. Returns: str Description: The extracted URL string. ``` -------------------------------- ### API: Get Messages from Merged Message Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/message/index.html Retrieves a list of all individual messages contained within a merged message. ```APIDOC msg.get_messages() Description: Retrieves all individual messages contained within a merged message. Parameters: None Returns: List[str] Description: A list of messages from the merged message. ``` -------------------------------- ### Configure WxParam Project Settings Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/concepts.md Shows how to import the `WxParam` object and modify its configuration attributes, such as setting the `LISTENER_EXCUTOR_WORKERS` for the listener thread pool size. ```Python from wxautox import WxParam WxParam.LISTENER_EXCUTOR_WORKERS = 8 ... ``` -------------------------------- ### Initialize Google Analytics and Theme Switching Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/blog/index.html This JavaScript code initializes Google Analytics tracking and implements a theme switching mechanism. It detects the user's preferred color scheme from local storage or system settings and applies 'dark' or 'light' theme classes to the document element. It also sets the `colorScheme` CSS property for consistent rendering. ```JavaScript window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date),gtag("config","G-YTPXPYKV40")const defaultTheme="system",setDarkTheme=()=>{ document.documentElement.classList.add("dark"), document.documentElement.style.colorScheme="dark" }, setLightTheme=()=>{ document.documentElement.classList.remove("dark"), document.documentElement.style.colorScheme="light" }; "color-theme"in localStorage? localStorage.getItem("color-theme")==="dark"? setDarkTheme(): setLightTheme(): (defaultTheme==="dark"? setDarkTheme(): setLightTheme(), defaultTheme==="system"&& (window.matchMedia("(prefers-color-scheme: dark)").matches? setDarkTheme(): setLightTheme() ) ) ``` -------------------------------- ### Markdown Blockquote Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Demonstrates how to format blockquotes in Markdown by prefixing lines with the `>` character, suitable for quoting text. ```markdown As Newton said: > If I have seen further it is by standing on the shoulders of Giants. ``` -------------------------------- ### WeChat Class Initialization Parameters Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/concepts.md Documents the parameters available for initializing the `WeChat` class, which serves as the main entry point for WeChat automation. It includes `nickname` for window identification and `debug` for enabling debug mode. ```APIDOC WeChat(nickname: str = None, debug: bool = False) - nickname: str, default None WeChat nickname, used to locate a specific WeChat window. - debug: bool, default False Whether to enable debug mode. ``` -------------------------------- ### wxautox WeChat Class API Reference Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/wechat/index.html Comprehensive API documentation for the `wxautox.WeChat` class, detailing its constructor and various methods for interacting with WeChat, including session management, message sending, chat window control, and message listening. ```APIDOC WeChat Class and Methods: WeChat(nickname: str = None, debug: bool = False) - Initializes the WeChat object. - Parameters: - nickname (str, optional): WeChat nickname, used to locate a specific WeChat window. Defaults to None. - debug (bool, optional): Whether to enable debug mode. Defaults to False. KeepRunning() - Keeps the program running when only in listening mode, as wxautox uses a daemon thread to listen for messages. - Returns: None GetSession() -> List[SessionElement] - Retrieves the current session list. - Returns: - Type: List[SessionElement] - Description: Current session list. SendUrlCard(url: str, friends: Union[str, List[str]] = None, timeout: int = 10) -> WxResponse - Sends a URL card. - Parameters: - url (str): Required. Link address. - friends (Union[str, List[str]], optional): Target(s) to send to, can be a single username or a list of usernames. Defaults to None. - timeout (int, optional): Waiting time in seconds. Defaults to 10. - Returns: - Type: WxResponse - Description: Sending result. ChatWith(who: str, exact: bool = False) - Opens a chat window with a specific contact. - Parameters: - who (str): Required. The contact to chat with. - exact (bool, optional): Whether to use exact matching when searching for friends. Defaults to False. - Returns: None GetSubWindow(nickname: str) -> Chat - Retrieves a sub-window instance for a specific chat. - Parameters: - nickname (str): Required. The nickname of the sub-window to retrieve. - Returns: - Type: Chat - Description: Sub-window instance. GetAllSubWindow() -> List[Chat] - Retrieves all sub-window instances. - Returns: - Type: List[Chat] - Description: List of all sub-window instances. AddListenChat(nickname: str, callback: Callable[[Message, Chat], None]) -> Union[Chat, WxResponse] - Adds a listener for a chat window. - Parameters: - nickname (str): Required. The chat object to listen to. - callback (Callable[[Message, Chat], None]): Required. Callback function, parameters are (Message object, Chat object). - Returns: - Success: - Type: Chat - Description: The listened sub-window instance. - Failure: - Type: WxResponse - Description: Execution result, contains listener name on success. RemoveListenChat(nickname: str) -> WxResponse - Removes a chat listener. - Parameters: - nickname (str): Required. The chat object to remove the listener from. - Returns: - Type: WxResponse - Description: Execution result. StartListening() - Starts listening for messages. - Returns: None StopListening(remove: bool = True) - Stops listening for messages. - Parameters: - remove (bool, optional): Whether to remove all sub-windows. Defaults to True. - Returns: None Moments(timeout: int = 3) -> MomentsWnd - Enters the Moments (朋友圈) window. - Parameters: - timeout (int, optional): Waiting time in seconds. Defaults to 3. - Returns: - Type: MomentsWnd - Description: Moments window instance. GetNextNewMessage(filter_mute: bool = False) -> Dict[str, List[Message]] - Retrieves the next new message. - Parameters: - filter_mute (bool, optional): Whether to filter out muted messages. Defaults to False. - Returns: - Type: Dict[str, List[Message]] - Description: Message list, key is chat name, value is message list. - Example: {'chat_name': 'wxauto交流', 'chat_type': 'group', 'msg': [ , , , , ... ] } ``` -------------------------------- ### Markdown Inline Code Syntax Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/blog/markdown.md Illustrates how to include inline code snippets within a sentence in Markdown using backticks (` `) around the code. ```markdown Inline `code` has `back-ticks around` it. ``` -------------------------------- ### Initialize Google Analytics Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/tags/index.html Initializes Google Analytics tracking for the website, setting up the dataLayer and configuring the G-YTPXPYKV40 measurement ID for page view tracking. ```JavaScript window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date),gtag("config","G-YTPXPYKV40") ``` -------------------------------- ### Get All Recent Groups (wxauto) Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/wechat/index.html Retrieves a list of all recently chatted groups. Returns a list of group names on success or a WxResponse object on failure. ```Python groups = wx.GetAllRecentGroups() if groups: print(groups) else: print('获取失败') ``` ```APIDOC wx.GetAllRecentGroups() - Description: Retrieves a list of all recently chatted groups. - Returns: WxResponse | List[str] - WxResponse on failure, list of recent group names on success. ``` -------------------------------- ### WxParam Configuration Parameters Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/concepts.md Documents the various configurable parameters available in the `WxParam` class, which control aspects like logging, file paths, message processing, and listener behavior. ```APIDOC WxParam Configuration Parameters: - ENABLE_FILE_LOGGER (bool): default True Whether to enable logging to a file. - DEFAULT_SAVE_PATH (str): default current working directory/wxautox Default save path for downloaded files/images. - MESSAGE_HASH (bool): default False Whether to enable message hashing for auxiliary message judgment. Enabling this may slightly affect performance. - DEFAULT_MESSAGE_XBIAS (int): default 51 X offset from avatar to message, used for message positioning and clicking. - FORCE_MESSAGE_XBIAS (bool): default False Whether to force re-acquisition of X offset automatically. If True, it will re-acquire every startup. - LISTEN_INTERVAL (int): default 1 Message listening time interval in seconds. - LISTENER_EXCUTOR_WORKERS (int): default 4 Listener executor thread pool size. Adjust based on needs and device performance. - SEARCH_CHAT_TIMEOUT (int): default 5 Timeout in seconds for searching chat objects. ``` -------------------------------- ### Get All WeChat Sub-Window Instances Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/WeChat.md Shows how to obtain a list of all currently active `Chat` instances, representing all open chat conversations or sub-windows managed by the `WeChat` object. ```python chats = wx.GetAllSubWindow() ``` -------------------------------- ### Initialize Google Analytics and Manage Site Theme Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/categories/index.html This JavaScript snippet initializes Google Analytics and implements a theme switching mechanism. It detects user preferences from localStorage or system settings (prefers-color-scheme) to apply 'dark' or 'light' themes to the document's root element. ```javascript window.dataLayer=window.dataLayer||[]; function gtag(){dataLayer.push(arguments)} gtag("js", new Date()); gtag("config", "G-YTPXPYKV40"); const defaultTheme="system"; const setDarkTheme=()=>{ document.documentElement.classList.add("dark"); document.documentElement.style.colorScheme="dark" }; const setLightTheme=()=>{ document.documentElement.classList.remove("dark"); document.documentElement.style.colorScheme="light" }; "color-theme"in localStorage ? localStorage.getItem("color-theme")==="dark" ? setDarkTheme() : setLightTheme() : ( defaultTheme==="dark" ? setDarkTheme() : setLightTheme(), defaultTheme==="system" && (window.matchMedia("(prefers-color-scheme: dark)").matches ? setDarkTheme() : setLightTheme() ) ); ``` -------------------------------- ### Get Dialog Box using wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/public/docs/class/chat/index.html This snippet demonstrates how to retrieve the current active dialog box using `wx.GetDialog()` and then interact with it by clicking a button. ```python if dialog := wx.GetDialog(): dialog.click_button("确定") ``` -------------------------------- ### Get All Recent Group Chat Names with wxauto Source: https://github.com/cluic/wxauto_doc_web/blob/main/content/docs/class/WeChat.md Retrieves a list of all recently active group chat names. The function returns a WxResponse object on failure or a list of strings on success. ```python groups = wx.GetAllRecentGroups() if groups: print(groups) else: print('获取失败') ``` ```APIDOC GetAllRecentGroups() - Description: Retrieves a list of all recent group chat names. - Returns: WxResponse | List[str] - Returns WxResponse on failure, or a list of all recent group chat names on success. ```