wxauto

repository·main·Indexed 27 days ago

https://github.com/cluic/wxauto

A Python library for automating WeChat on Windows using UIAutomation technology. It provides functionality to send text, files, and emotions, manage group members and contacts, and retrieve chat history. Key features include the WeChat and Chat classes for interface interaction, and a comprehensive Message class for handling various content types (text, image, video, file, etc.) and performing actions like quoting, forwarding, and downloading media. Requires Windows 10/11 or Server 2016+, WeChat version 3.9.X, and Python 3.9 or higher.

Tokens
11.5K
Snippets
38
Records
94
Agent score
86%

What's inside wxauto

  1. Quickstart with wxauto

    main

    To begin automating WeChat, you need to import the WeChat class from wxauto and initialize an instance. This instance serves as the primary interface for interacting with the WeChat client.

    from wxauto import WeChat
    
    # Initialize the WeChat instance
    wx = WeChat()
  2. Listen for incoming messages with callbacks

    main

    You can monitor specific chats for new messages using AddListenChat. This requires a callback function (e.g., on_message) that handles the incoming msg and chat objects. To keep the listener active, you must call wx.KeepRunning(). Use RemoveListenChat to stop monitoring a specific nickname.

    Common tasks within a callback:

    • Logging: Write msg.content to a file.
    • Downloading: Use msg.download() for image or video types.
    • Auto-reply: Use msg.quote('text') if the message is an instance of FriendMessage.
    from wxauto import WeChat
    from wxauto.msgs import FriendMessage
    import time
    
    wx = WeChat()
    
    def on_message(msg, chat):
        # Log to file
        with open('msgs.txt', 'a', encoding='utf-8') as f:
            f.write(msg.content + '\n')
    
        # Download media
        if msg.type in ('image', 'video'):
            print(msg.download())
    
        # Auto-reply to friends
        if isinstance(msg, FriendMessage):
            msg.quote('收到')
    
    # Start listening to '张三'
    wx.AddListenChat(nickname="张三", callback=on_message)
    
    # Keep the program running to listen
    wx.KeepRunning()
    
    # Later, to stop listening:
    # wx.RemoveListenChat(nickname="张三")
  3. Keep the program running for message listening

    main

    Because wxauto uses daemon threads to listen for messages, the main thread will exit immediately if the script only contains listening logic. Call KeepRunning() to prevent the program from exiting and ensure continuous monitoring.

    from wxauto import WeChat
    
    wx = WeChat()
    wx.AddListenChat('张三', callback=lambda msg, chat: ...)
    
    # Keep the program running to ensure normal listening
    wx.KeepRunning()
  4. System Requirements for wxauto

    main

    To use wxauto, ensure your environment meets the following specifications:

    • OS: Windows 10, 11, or Windows Server 2016 or later.
    • WeChat Version: 3.9.X.
    • Python Version: 3.9 or higher.
  5. Configure global settings via WxParam

    main

    You can modify the default behavior of wxauto by updating the attributes of the WxParam class before initializing a WeChat instance.

    Key configuration properties:

    • ENABLE_FILE_LOGGER (bool, default: True): Enable/disable log files.
    • DEFAULT_SAVE_PATH (str, default: ./wxauto): Default directory for downloading files/images.
    • MESSAGE_HASH (bool, default: False): Enable message hashing for better identification (may impact performance).
    • DEFAULT_MESSAGE_XBIAS (int, default: 51): X-offset from avatar to message for positioning/clicking.
    • FORCE_MESSAGE_XBIAS (bool, default: True): Force recalculation of X-offset on every startup (useful for high DPI/scaling settings).
    • LISTEN_INTERVAL (int, default: 1): Interval in seconds for listening to messages.
    • LISTENER_EXCUTOR_WORKERS (int, default: 4): Size of the listener executor thread pool.
    • SEARCH_CHAT_TIMEOUT (int, default: 5): Timeout in seconds when searching for chat objects.
    • NOTE_LOAD_TIMEOUT (int, default: 30): Timeout in seconds for loading WeChat notes.
    from wxauto import WxParam
    
    # Set 8 listener threads
    WxParam.LISTENER_EXCUTOR_WORKERS = 8
  6. Initialize the WeChat client

    main

    To start automating WeChat, instantiate the WeChat class. You can specify the client language to ensure UI element matching works correctly.

    Supported languages:

    • cn: Simplified Chinese (default)
    • cn_t: Traditional Chinese
    • en: English
  7. Initialize WeChat and send/receive messages

    main

    Use the WeChat class to automate basic interactions. You can initialize an instance, send messages to specific contacts using SendMsg, and retrieve all messages from the current active chat window using GetAllMessage. Each message object contains content and type attributes.

    from wxauto import WeChat
    
    # Initialize WeChat instance
    wx = WeChat()
    
    # Send message to '张三'
    wx.SendMsg("你好", who="张三")
    
    # Get messages from current chat window
    msgs = wx.GetAllMessage()
    for msg in msgs:
        print(f"消息内容: {msg.content}, 消息类型: {msg.type}")
  8. Identify and reply to FriendMessage objects

    main

    When processing messages, you can identify if a message was sent by a friend using either the attr property or by checking the object type with isinstance. Once identified, you can use the .reply() method to respond.

    from wxauto.msgs import *
    
    # Assume 'msg' is a retrieved Message object
    
    # Method 1: Check the 'attr' property
    if msg.attr == 'friend':
        msg.reply('收到')
    
    # Method 2: Use isinstance check
    if isinstance(msg, FriendMessage):
        msg.reply('收到')
    from wxauto.msgs import *
    
    # Assume 'msg' is a retrieved Message object
    
    # Method 1: Check the 'attr' property
    if msg.attr == 'friend':
        msg.reply('收到')
    
    # Method 2: Use isinstance check
    if isinstance(msg, FriendMessage):
        msg.reply('收到')
  9. Manage FriendMessage interactions

    main

    For messages sent by friends or group members (FriendMessage), use these methods:

    • sender_info(): Returns a dictionary containing the sender's information.
    • at(content, quote=False): Sends an @ mention to the message sender.
    • add_friend(addmsg=None, remark=None, tags=None, permission='朋友圈', timeout=3): Attempts to add the sender as a friend with optional remarks, tags, and permission settings.
    • multi_select(): Selects the message for use in bulk forwarding (merge forwarding).
  10. Automate WeChat login and QR code retrieval

    main

    To automate the login process, use the LoginWnd class by providing the path to your WeChat.exe. You can call .login() to start the process or .get_qrcode() to retrieve the file path of the login QR code image.

    from wxauto import LoginWnd
    
    wxpath = "D:/path/to/WeChat.exe"
    loginwnd = LoginWnd(wxpath)
    
    # Perform login
    loginwnd.login()
    
    # Or get the QR code path
    qrcode_path = loginwnd.get_qrcode()
    print(qrcode_path)
  11. Perform actions on HumanMessage (click, quote, forward, delete)

    main

    The HumanMessage class (and its subclasses like FriendMessage or SelfMessage) provides several interaction methods:

    • click(): Clicks the message (useful for images or videos).
    • select_option(option): Right-clicks the message and selects a specific menu option (e.g., msg.select_option("复制")).
    • quote(text, at=None, timeout=3): Quotes the message and replies with the specified text. Supports @ users.
    • forward(targets, message=None, timeout=3): Forwards the message to specified targets (name or list) with an optional additional message.
    • delete(): Deletes the message.
    • download_head_image(): Downloads the sender's profile picture.
    msg.click()
    msg.select_option("复制")
    msg.quote("回复内容")
    msg.forward("张三", message="转发会议材料给你,请查收")
    msg.delete()
    msg.download_head_image()
  12. Merge forward messages

    main

    To merge forward messages, first open the target chat using ChatWith, retrieve messages with GetAllMessage, and select specific messages using msg.multi_select(). Note that multi_select() is available on HumanMessage objects. Finally, call MergeForward(targets) where targets is a list of recipient nicknames.

    from wxauto import WeChat
    from wxauto.msgs import HumanMessage
    
    wx = WeChat()
    
    # Open chat
    wx.ChatWith("工作群")
    
    # Select last 5 human messages
    msgs = wx.GetAllMessage()
    n = 0
    for msg in msgs[::-1]:
        if n >= 5:
            break
        if isinstance(msg, HumanMessage):
            n += 1
            msg.multi_select()
    
    # Merge forward to specific targets
    targets = ['张三', '李四']
    wx.MergeForward(targets)