Build a Stable Mac WeChat RPA Group Chat Bot with AppleScript: A Comprehensive Step-by-Step Guide

If you frequently deal with repetitive tasks on WeChat—such as answering routine questions in group chats, logging data, or summarizing information—you’ve probably wondered if there’s a way to automate these processes with a bot. While there are many WeChat bot solutions available, most suffer from either poor stability or require additional costs. Today, I’ll share a simple RPA (Robotic Process Automation) group chat bot built with AppleScript and the Mac version of the WeChat client. It may not be the fastest or most feature-rich, but it’s incredibly stable, and you can build it entirely by yourself with minimal technical effort.

Why Do You Need This WeChat Bot?

Before creating this bot, I tested several mainstream solutions, with WeChaty being the most popular. However, I encountered significant limitations in practical use: WeChaty relies on “puppets”—essentially bridges that enable the bot to interact with WeChat. The free web-based or UOS puppets are notoriously unstable, often disconnecting unexpectedly without warning. On the other hand, more reliable and feature-complete puppets like ipadlocal require purchasing tokens, adding unnecessary costs.

As someone who only uses Mac devices, these solutions didn’t meet my needs. That’s when I developed this bot using AppleScript (macOS’s built-in automation language) and a small amount of Python code. It operates directly on the Mac WeChat client, no third-party APIs required. As long as your WeChat is logged in and stable, the bot will keep running—no unexpected disconnections or subscription fees.

In short, this bot is ideal for:


  • Automating responses in fixed group chats or private conversations (e.g., answering FAQs, logging expenses, or aggregating information)

  • Integrating with your own tools (such as connecting to a large language model to summarize articles)

  • Users who prioritize stability and low cost (virtually free)

  • Anyone with a Mac device and basic technical literacy

Preparation: Tools and Environment You’ll Need

Before diving into the setup, let’s confirm your device and environment meet the requirements. The bot’s core is AppleScript, which handles most automation tasks, paired with a small Python script to simulate mouse clicks—since AppleScript’s native click functionality doesn’t work directly with the WeChat client.

Prerequisites

  1. A Mac computer with the WeChat desktop app installed (I used WeChat Version 3.8.6 (28078); other versions may require minor script adjustments)
  2. A logged-in WeChat account (the bot will use this account to send and receive messages)
  3. Python 3 interpreter (preinstalled on most Macs; verify with python3 --version in Terminal)
  4. The PyUserInput library (for simulating mouse clicks)

How to Install PyUserInput

PyUserInput is a Python library that enables mouse and keyboard automation. While it’s marked as “Deprecated” (no longer actively maintained), it still works seamlessly on macOS at the time of writing. If it stops working in the future, you can replace it with alternative tools like PyAutoGUI— the core logic will remain the same.

Installing PyUserInput is straightforward:

  1. Open Terminal (found in Applications → Utilities → Terminal)
  2. Enter the following command and press Enter:
pip3 install PyUserInput
  1. Wait for the installation to complete. You’ll see a “Successfully installed” message once it’s done.

Core Files Explained: What Powers the Bot?

The bot relies on two key files—think of them as the “brain” and “hands” of your automation tool:


  • wemac.applescript: The main script file responsible for locating the chat window, reading messages, determining if a response is needed, and sending replies.

  • mouseclick.py: A helper Python script that handles mouse click operations (called by AppleScript, since AppleScript can’t click inside the WeChat client on its own).

You’ll need to obtain these two files (from the project repository) and configure them to match your WeChat environment. Below, we’ll focus on configuring wemac.applescript—this is the most critical step to get your bot working.

Detailed Configuration Steps: Let the Bot Recognize Your WeChat Setup

Open the wemac.applescript file in a text editor (such as TextEdit, VS Code, or Sublime Text). You’ll need to modify five key variables—these settings tell the bot how to find your chat window, identify itself, and run properly.

5 Core Variables to Modify (Must-Do!)

These variables act as the bot’s “setup wizard.” Each one directly impacts performance, so take time to configure them correctly:

Variable Name Purpose Example Value
chatWindowName The name of the chat window the bot will monitor. For private chats, use the contact’s nickname or remark; for group chats, use the group name. “Company Project Group” or “Zhang San”
botName The bot’s WeChat nickname (or remark). It uses this to detect when someone @mentions it (and trigger a response). “Data Assistant Bot”
pythonBin The file path to your Python 3 interpreter (needed to run mouseclick.py). “/usr/local/bin/python3”
workingDir The folder path where mouseclick.py is stored (your bot’s working directory). “/Users/yourname/wechat-bot”
windowOffset Used to locate messages sent by the bot (to delete them later). Typically calculated as: Monitor Width - 400 - 20. 1440 (for a 1920×1080 monitor: 1920-400-20=1440)

How to Find the Correct Values for These Variables

Let’s break down how to get each value—no technical expertise required:

  1. chatWindowName
    Open WeChat, navigate to the chat you want the bot to monitor, and copy the exact name from the top of the chat window. Avoid extra spaces or special characters (e.g., if the group is named “Marketing Team 🚀”, include the emoji if it’s part of the official name).

  2. botName
    Open WeChat, go to the “Me” tab, and copy your nickname exactly (case-sensitive). If you’ve set a remark for your own account, use that instead—just ensure it matches the script.

  3. pythonBin
    In Terminal, type which python3 and press Enter. The output (e.g., /usr/local/bin/python3) is your Python 3 path—copy it directly into the script.

  4. workingDir
    Locate the folder where you saved mouseclick.py. Right-click the folder, select “Get Info,” and copy the “Where” path (e.g., /Users/johndoe/Documents/WeChatBot).

  5. windowOffset
    First, find your monitor’s resolution:


    • Go to System Preferences → Displays → Resolution.

    • Note the width (e.g., 1920 for a 1920×1080 monitor).

    • Calculate: Monitor Width - 400 - 20. For a 1920-width monitor, that’s 1440.

    • If the bot fails to delete its own messages later, adjust this value slightly (e.g., ±50) until it works.

Running the Bot: What to Know for the First Launch

Once you’ve configured the variables, you’re ready to test the script. But before running it, double-check these critical items to avoid errors:

3 Pre-Run Checks

  1. WeChat is Logged In
    Ensure the Mac WeChat app is logged in, and the chat window specified in chatWindowName is open (it doesn’t need to be front-and-center, but it should be visible in WeChat’s window list).

  2. File Paths Are Correct
    Verify that mouseclick.py is stored in the folder specified by workingDir. If not, the script will throw a “file not found” error.

  3. Permission Settings
    If you see a “no permission to control WeChat” warning:


    • Go to System Preferences → Security & Privacy → Privacy → Automation.

    • Check the box next to Terminal (or your text editor/script runner) to allow it to control WeChat.

Step-by-Step First Run

  1. Open Terminal and navigate to the folder where wemac.applescript is stored. Use the cd command (e.g., cd /Users/yourname/wechat-bot).
  2. Run the script with this command:

    osascript wemac.applescript
    
  3. Watch the WeChat window:


    • The script will automatically locate the target chat window and click on it.

    • It will then delete the most recent message in the chat (this is intentional—more on why below).

    • If the deleted message included an @mention of your bot (matching botName), the bot will send a reply.
  4. The script will exit after processing one message (this is normal for a single run).

Why Does the Bot Delete Messages?

This is a practical workaround: the bot has no built-in way to track which messages it’s already processed. By deleting each message after handling it, it avoids replying to the same message multiple times.

If you’re worried about accidentally deleting important chat history, test the bot in a dedicated test group first. Once you’re comfortable with its behavior, you can use it in production chats.

Keeping the Bot Running 24/7: How to Automate Continuous Operation

The above steps only process one message at a time. To make the bot run indefinitely, you’ll need to loop the script. The simplest way is to create a run.sh shell script that repeatedly executes wemac.applescript.

How to Create and Use run.sh

  1. In your workingDir folder, create a new text file and name it run.sh.
  2. Open the file and paste the following code (this loops the script every 3 seconds):

    #!/bin/bash
    while true; do
      osascript /Users/yourname/wechat-bot/wemac.applescript  # Replace with your script’s full path
      sleep 3  # Adjust the interval (in seconds) as needed
    done
    
  3. Save the file, then open Terminal and navigate to workingDir.
  4. Grant execution permission to run.sh with this command:

    chmod +x run.sh
    
  5. Start the bot:

    ./run.sh
    

The bot will now check for new messages every 3 seconds. To stop it, press Ctrl + C in Terminal.

What’s the Best Interval Time?

Adjust the sleep value (in seconds) based on your chat volume:


  • High-traffic group chats: Use 2–3 seconds (avoid setting it too low—frequent script runs may cause WeChat to lag).

  • Low-traffic chats: Use 5–10 seconds to reduce resource usage.

Customizing Responses: Make the Bot Say What You Want

By default, the bot’s replies are basic, but you can customize them to fit your needs—whether that’s integrating a large language model, logging data, or triggering other tools.

Where to Modify the Response Logic

Open wemac.applescript and find the comment labeled “消息处理逻辑” (Message Processing Logic)—this is around line 270. This is where you’ll define how the bot generates replies.

AppleScript’s functionality is limited, so we recommend using external scripts (e.g., Python, Node.js) to handle complex logic. The bot can call these scripts via the shell, capture their output, and send it as a reply.

Example: Calling a Python Script for Custom Replies

Suppose you have a Python script reply_handler.py that processes user questions and returns answers (e.g., summarizing articles or logging expenses). Here’s how to integrate it into wemac.applescript:

-- Message Processing Logic
set question to the content of the message  -- Get the user’s message content
-- Call the Python script to generate a reply
set replyMessage to do shell script "python3 " & quoted form of (workingDir & "/reply_handler.py") & " " & (my escaped(question))

Key details to note:


  • escaped(question): A built-in function in the script that escapes special characters (e.g., spaces, quotes) in the user’s message. This prevents “injection attacks” (e.g., malicious commands hidden in messages like ; rm -rf *).

  • quoted form of: Ensures the script can handle file paths with spaces or special characters (e.g., /Users/yourname/My WeChat Bot).

Practical Use Case: Expense Tracking

Let’s say you want the bot to log expenses when you send a message like “Coffee: $30”. Create a Python script expense_recorder.py with this logic:

import sys

def record_expense(question):
    # Parse the message (e.g., "Coffee: $30" → item="Coffee", amount="$30")
    if ": $" in question:
        item, amount = question.split(": $")
        # Log to a file (simplified example)
        with open("expenses.txt", "a") as f:
            f.write(f"Item: {item.strip()}, Amount: ${amount.strip()}\n")
        return f"Expense recorded: {item.strip()} - ${amount.strip()}"
    else:
        return "Invalid format. Use: 'Item: $Amount' (e.g., 'Lunch: $15')"

if __name__ == "__main__":
    question = sys.argv[1]
    print(record_expense(question))

When you @mention the bot with “Coffee: 30″.

Limitations of the Bot: When It Might Not Be the Right Fit

While this bot is incredibly stable, its design (simulating manual interactions with the WeChat client) comes with inherent limitations. It’s important to understand these upfront to avoid disappointment:

  1. No Access to Unique User IDs
    The bot can only identify users by their nicknames or remarks—not by openid, unionid, or other unique identifiers. If a user changes their nickname, the bot may fail to recognize them.

  2. No Unique Message IDs
    Since it uses message deletion to track processed messages, there’s no way to retrieve or reference historical messages. It also can’t distinguish between duplicate messages (e.g., two users sending the same text).

  3. Slow Processing Speed
    It handles one message per script run. If messages are sent faster than the script’s loop interval (e.g., 3 seconds), some messages may never be processed.

  4. Mac-Only
    The bot relies on AppleScript and the Mac WeChat client— it won’t work on Windows, Linux, or mobile devices. However, you can run multiple bots on one Mac using virtual machines.

  5. Single-Window Limitation
    One script can only monitor one chat window. To handle multiple group chats, you’ll need to run multiple instances of the script, which may slow down your Mac.

Future Features to Explore (TODO List)

This bot is a basic version with room for expansion. If you want to enhance it, consider adding these features:


  • Support for non-text messages (images, voice notes, links)

  • Ability to send images and files

  • WeChat Moments automation (e.g., auto-liking, posting updates)

  • Compatibility with WeChat Work (Enterprise WeChat)

Frequently Asked Questions (FAQ)

1. Will this bot get my WeChat account banned?

The risk is extremely low. The bot simulates human interactions (clicking, typing, deleting messages) rather than using unauthorized APIs, so it’s unlikely to be detected by WeChat’s anti-bot systems. However, WeChat’s policies may change—avoid using the bot for spam, advertising, or other violations to keep your account safe.

2. Do I need to reconfigure windowOffset if I change monitors?

Yes. windowOffset depends on your monitor’s width. After changing monitors, update the value using the new resolution (Monitor Width – 400 – 20). If the bot fails to delete its messages,微调 (fine-tune) the value by ±50 until it works.

3. Can I use a language other than Python for mouse clicks?

Absolutely. Any language that can simulate mouse clicks and be called via the shell (e.g., Node.js, Bash scripts) will work. Just replace the Python-related commands in wemac.applescript with your preferred language’s execution command.

4. Why is the bot not responding?

Check these common issues first:


  • Is WeChat logged in, and is the target chat window open?

  • Does chatWindowName exactly match the chat window’s name (including spaces/emojis)?

  • Are pythonBin and workingDir paths correct?

  • Did you grant Terminal/your script runner permission to control WeChat?

  • If you see an “element not found” error, retry the script—this is a common AppleScript quirk with app automation.

5. How can I make the bot reply only to specific keywords?

Add a condition in the “Message Processing Logic” section of wemac.applescript. For example, to only reply to messages containing “record”:

set question to the content of the message
if question contains "record" then
  set replyMessage to "Processing your record request..."  -- Or call an external script
else
  set replyMessage to ""  -- No reply for non-matching messages
end if

6. Can I run multiple bots on one Mac?

Yes. You can create separate copies of wemac.applescript (with different chatWindowName and botName values) and run them via multiple run.sh scripts. Just ensure your Mac has enough resources (CPU/RAM) to handle concurrent script runs.

7. What if PyUserInput stops working?

Replace it with an alternative mouse automation library like PyAutoGUI. Install PyAutoGUI with pip3 install pyautogui, then modify mouseclick.py to use PyAutoGUI’s click function. The rest of the script logic will remain unchanged.

Conclusion: The Right Tool for Stability and Simplicity

This Mac WeChat RPA bot may not be the most feature-packed option on the market, but it excels where it matters most: stability, low cost, and ease of use. If you need a reliable way to automate repetitive WeChat tasks without paying for expensive tokens or dealing with frequent disconnections, this solution is perfect for you.

The setup process is straightforward—most of the work involves configuring a few variables and testing the script. Once running, the bot will operate quietly in the background, handling your routine tasks so you can focus on more important work.

As you use the bot, feel free to customize it to fit your needs—whether that’s integrating with a large language model, logging data, or adding support for new message types. The beauty of this solution is its flexibility: it’s a starting point that you can adapt to your unique workflow.

If you encounter issues during setup, refer back to the FAQ section or double-check your configuration variables—most problems stem from typos in file paths or chat window names. With a little patience, you’ll have a stable, custom WeChat bot up and running in no time.