SuperAPI AI Directory

wxauto-dev

General & other

View repository

Updated 10-15 19:50

About this skill

WxAuto-Dev Skill

Based on the wxautox4 library, help users quickly build WeChat automation bots.

Execution Flow

Step -1: Environment Description (Highest Priority)

The user may write code on a development machine and run it on another Windows device.Do not attempt to detect or help the user configure the environment, simply briefly inform them of the runtime environment requirements at the start:

The wxautox4 bot needs to run in the following environment (the development machine does not need to meet these requirements):

  • Windows 10/11, WeChat PC version 4.1
  • Python 3.9-3.12, install wxautox4:pip install wxautox4
  • Activate:wxautox4 -a 激活码(the activation code is available at https://dusapi.com/register after registering at https://wxauto.org/purchase for purchase)
  • Check activation status:wxautox4 -k

After informing them, proceed directly to requirement clarification and code generation. Do not wait for the user to confirm the environment, and do not help the user execute any environment configuration commands.

Step 0: Requirement Clarification

When the requirements are unclear,mustuse the inquiry tool available in the current environment (AskUserQuestion / Ask User / question, etc., called by the actual tool name) to guide the user; do not guess.

Inquiry example (call by the actual tool name; the following is reference question content):

# 监听对象不明确时,询问:
问题:您想监听哪些对象的消息?
选项:
  - 特定群聊或好友(只监听指定的群或好友)
  - 所有新消息(无差别获取所有聊天的新消息)

# 功能需求模糊时,询问:
问题:您需要机器人实现什么功能?(可多选)
选项:
  - 消息监听和记录
  - 关键词自动回复
  - 朋友圈操作(发布、点赞、评论)
  - 智能对话(接入 AI 大模型)

Step 1: Select a Template

Requirement Template
Monitor a specified group/friend Template 1
Keyword auto-reply Template 2
Moments posting Template 3
Moments monitoring (likes/comments) Template 4
Indiscriminately monitor all messages Template 5

Step 2: Generate Code

All generated code must include:

  • ✅ try-except error handling + 3 retries
  • ✅ logging
  • ✅ signal handler for graceful exit
  • ✅ Safe sending (first ChatWith → verify ChatInfo → then SendMsg)
  • ✅ init_wechat handles the "main window not found" error

Additional requirements when integrating an AI API:

  • Use load_dotenv() to load .env (os.getenv alone cannot read .env), including model configuration
  • requirements.txt must include python-dotenv>=1.0.0
  • The default model is claude-sonnet-4-6 or claude-opus-4-6

Step 3: Syntax Check (Must Be Performed)

python3 -m py_compile wxbot.py

If there are errors, fix them and check again until it passes.

Step 4: Output Files

Must output:wxbot.py + README.md(generate only this document; do not generate QUICKSTART.md, etc.)

Additional output when integrating an AI API:requirements.txt(including python-dotenv) + .env.example


Core API Quick Reference

from wxautox4 import WeChat
from wxautox4.msgs import FriendMessage
from wxautox4.msgs.friend import FriendTextMessage, FriendImageMessage

wx = WeChat()  # 初始化

# 监听指定对象
wx.AddListenChat(nickname='群名或好友昵称', callback=on_message)
wx.KeepRunning()  # 保持运行(阻塞)

# 无差别获取所有新消息
result = wx.GetNextNewMessage(filter_mute=True, callback=on_message)
# result: {'chat_name': '...', 'chat_type': 'group/friend', 'msg': [...]}

# 获取当前聊天所有消息
messages = wx.GetAllMessage()

# 切换聊天 + 获取当前聊天信息
wx.ChatWith(who='张三')
chat_info = wx.ChatInfo()  # {'chat_type': 'friend', 'chat_name': '张三'}

# 发送消息(不要直接用,用 safe_send_msg)
wx.SendMsg(msg='你好')
wx.SendMsg(msg='请注意', at='李四')  # @某人
wx.AtAll(msg='重要通知')             # @所有人
wx.SendFiles(filepath='C:/file.txt')

# 朋友圈
wx.PublishMoment(text='内容', media_files=['1.png'], privacy_config={...})
pyq = wx.Moments(timeout=3)
moments = pyq.GetMoments()          # 获取当前页
moments = pyq.GetMoments(next_page=True)  # 下一页
moment.Like()                       # 点赞
moment.Like(False)                  # 取消赞
moment.Comment('很棒!')            # 评论
pyq.Close()

# 好友管理
newfriends = wx.GetNewFriends(acceptable=True)
friend.accept(remark='备注', tags=['客户'])
wx.AddNewFriend(keywords='张三', addmsg='我是小明', remark='老张', tags=['同学'])

Message Object Properties:msg.type(text/image/file/voice/video)、msg.attr(self/friend/system)、msg.sender、msg.content、msg.raw

Message Object Methods:msg.reply(text)、msg.download(savepath)


Code Templates

All templates share the following boilerplate code (write it out completely when generating):

# 样板:logging + signal + init_wechat + safe_send_msg
import logging, signal, sys, time
from wxautox4 import WeChat

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler('wxbot.log', encoding='utf-8'), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

def signal_handler(signum, frame):
    logger.info("收到退出信号")
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

class WxBot:
    def init_wechat(self, max_retries=3):
        for attempt in range(max_retries):
            try:
                self.wx = WeChat()
                logger.info("微信初始化成功")
                return True
            except Exception as e:
                if "未找到已登录的客户端主窗口" in str(e):
                    logger.error("未找到微信窗口,请确保微信已登录,如问题持续请退出重新登录")
                else:
                    logger.error(f"初始化失败: {e}")
                if attempt < max_retries - 1:
                    time.sleep(5)
        return False

    def safe_send_msg(self, target: str, msg: str, max_retries: int = 3) -> bool:
        for attempt in range(max_retries):
            try:
                self.wx.ChatWith(who=target)
                time.sleep(0.5)
                if self.wx.ChatInfo().get('chat_name') == target:
                    self.wx.SendMsg(msg=msg)
                    return True
            except Exception as e:
                logger.error(f"发送失败 ({attempt+1}/{max_retries}): {e}")
                if attempt < max_retries - 1:
                    time.sleep(1)
        return False

Template 1: Listen to a specified group/friend

Key difference: use AddListenChat + KeepRunning, the callback receives (msg, chat) two parameters, and you can directly use chat.SendMsg() to reply.

from wxautox4.msgs.friend import FriendTextMessage

LISTEN_TARGET = "工作群"   # 修改为要监听的群名或好友昵称
KEYWORD = "通知"           # 触发回复的关键词

class ListenBot(WxBot):
    def __init__(self):
        self.wx = None

    def on_message(self, msg, chat):
        try:
            logger.info(f"{msg.sender}: {msg.content}")
            if isinstance(msg, FriendTextMessage) and KEYWORD in msg.sender:
                for attempt in range(3):
                    try:
                        chat.SendMsg("收到")
                        break
                    except Exception as e:
                        if attempt < 2: time.sleep(1)
        except Exception as e:
            logger.error(f"处理消息出错: {e}", exc_info=True)

    def start(self):
        if not self.init_wechat(): return
        try:
            self.wx.AddListenChat(nickname=LISTEN_TARGET, callback=self.on_message)
            logger.info(f"已添加监听: {LISTEN_TARGET},按 Ctrl+C 停止")
            self.wx.KeepRunning()
        except Exception as e:
            logger.error(f"启动失败: {e}")

if __name__ == "__main__":
    ListenBot().start()

Template 2: Keyword auto-reply

Key difference: multi-target listening + keyword dictionary matching.

from wxautox4.msgs.friend import FriendTextMessage

LISTEN_TARGETS = ["客服群", "咨询群"]
REPLY_RULES = {
    "价格": "请查看价格表:...",
    "联系方式": "联系电话:xxx,邮箱:xxx@example.com",
    "营业时间": "周一至周五 9:00-18:00",
}

class AutoReplyBot(WxBot):
    def __init__(self):
        self.wx = None

    def on_message(self, msg, chat):
        try:
            if not isinstance(msg, FriendTextMessage): return
            for keyword, reply in REPLY_RULES.items():
                if keyword in msg.content:
                    for attempt in range(3):
                        try:
                            chat.SendMsg(reply)
                            logger.info(f"已回复关键词[{keyword}]给 {msg.sender}")
                            break
                        except Exception as e:
                            if attempt < 2: time.sleep(1)
                    break
        except Exception as e:
            logger.error(f"处理消息出错: {e}", exc_info=True)

    def start(self):
        if not self.init_wechat(): return
        for target in LISTEN_TARGETS:
            try:
                self.wx.AddListenChat(nickname=target, callback=self.on_message)
                logger.info(f"已添加监听: {target}")
            except Exception as e:
                logger.error(f"添加监听失败 {target}: {e}")
        self.wx.KeepRunning()

if __name__ == "__main__":
    AutoReplyBot().start()

Template 3: Scheduled Moments posting

Key difference: use schedule for scheduling, call PublishMoment。

import schedule

class MomentBot(WxBot):
    def __init__(self):
        self.wx = None

    def publish_moment(self, text: str, media_files: list = None, max_retries: int = 3):
        for attempt in range(max_retries):
            try:
                self.wx.PublishMoment(text=text, media_files=media_files)
                logger.info(f"发布朋友圈成功: {text[:20]}")
                return True
            except Exception as e:
                logger.error(f"发布失败 ({attempt+1}/{max_retries}): {e}")
                if attempt < max_retries - 1: time.sleep(2)
        return False

    def daily_task(self):
        text = f"早安!今天是 {time.strftime('%Y-%m-%d')}"
        self.publish_moment(text=text)
        # 带图片示例:self.publish_moment(text=text, media_files=[r"D:\1.png"])

    def start(self):
        if not self.init_wechat(): return
        schedule.every().day.at("09:00").do(self.daily_task)
        logger.info("朋友圈机器人已启动")
        while True:
            schedule.run_pending()
            time.sleep(60)

if __name__ == "__main__":
    MomentBot().start()

Template 4: Moments monitoring (likes/comments)

Key difference: periodically call Moments().GetMoments(), like/comment on new content.

class MomentMonitorBot(WxBot):
    def __init__(self):
        self.wx = None
        self.processed = set()  # 已处理的朋友圈 ID

    def process_moments(self):
        try:
            pyq = self.wx.Moments(timeout=3)
            if not pyq:
                logger.error("无法打开朋友圈")
                return
            for moment in pyq.GetMoments():
                mid = moment.content
                if mid in self.processed: continue
                try:
                    moment.Like()
                    logger.info(f"已点赞: {moment.author}")
                except Exception as e:
                    logger.error(f"点赞失败: {e}")
                if "关键词" in moment.content:
                    try:
                        moment.Comment("很棒!")
                    except Exception as e:
                        logger.error(f"评论失败: {e}")
                self.processed.add(mid)
                time.sleep(1)
            pyq.Close()
        except Exception as e:
            logger.error(f"处理朋友圈出错: {e}", exc_info=True)

    def start(self):
        if not self.init_wechat(): return
        logger.info("朋友圈监控已启动,每 10 分钟检查一次")
        while True:
            self.process_moments()
            time.sleep(600)

if __name__ == "__main__":
    MomentMonitorBot().start()

Template 5: Indiscriminately listen to all messages

Key difference: loop call GetNextNewMessage。⚠️ The callback must never call SendMsg/ChatWith, messages that need replies are added to a queue, and sent uniformly after GetNextNewMessage returns.

from collections import deque
from wxautox4.msgs.friend import FriendTextMessage

FILTER_MUTE = True
SLEEP_INTERVAL = 1

class AllMessageBot(WxBot):
    def __init__(self):
        self.wx = None
        self.running = True
        self.pending_replies: deque = deque()  # 待回复队列

    def on_new_message(self, msg):
        """
        ⚠️ 严禁在此处调用 SendMsg / ChatWith!
        只做:记录日志、下载文件、将需要回复的消息加入队列。
        """
        try:
            logger.info(f"{msg.sender}: {msg.content}")
            if msg.type in ['image', 'file', 'video']:
                try: msg.download()
                except Exception as e: logger.error(f"下载失败: {e}")
            # 需要回复时,加入队列
            if isinstance(msg, FriendTextMessage) and "帮助" in msg.content:
                self.pending_replies.append((msg.sender, "您好,我是自动回复机器人"))
        except Exception as e:
            logger.error(f"callback 出错: {e}", exc_info=True)

    def flush_pending_replies(self):
        """GetNextNewMessage 返回后,统一发送回复"""
        while self.pending_replies:
            target, reply = self.pending_replies.popleft()
            self.safe_send_msg(target, reply)

    def start(self):
        if not self.init_wechat(): return
        logger.info("无差别监听已启动,按 Ctrl+C 停止")
        while self.running:
            try:
                result = self.wx.GetNextNewMessage(filter_mute=FILTER_MUTE, callback=self.on_new_message)
                if result:
                    logger.info(f"收到来自 {result.get('chat_name')} 的 {len(result.get('msg', []))} 条消息")
                self.flush_pending_replies()  # 必须在 GetNextNewMessage 返回后调用
                time.sleep(SLEEP_INTERVAL)
            except KeyboardInterrupt:
                self.running = False
            except Exception as e:
                logger.error(f"运行出错: {e}", exc_info=True)
                time.sleep(5)

if __name__ == "__main__":
    AllMessageBot().start()

Code quality checklist

After generating code, check in order:

  • python3 -m py_compile wxbot.py passed (must be the first step)
  • All wxautox4 calls have try-except + 3 retries
  • Sending messages uses safe_send_msg (switch first, then verify, then send)
  • init_wechat handles the "main window not found" error
  • There are no SendMsg/ChatWith calls inside the callback of GetNextNewMessage
  • If an AI API is used: there is load_dotenv(), requirements.txt contains python-dotenv
  • Only one README.md is generated as documentation

FAQ

Problem Solution
未激活 / license error Run wxautox4 -a 激活码; if there is no activation code, go to https://dusapi.com/register to register,https://wxauto.org/purchase to purchase
未找到已登录的客户端主窗口 Re-run the code, or exit WeChat and log in again
Message listening does not take effect Check whether the nickname is correct, and view wxbot.log
Sending message failed Confirm that safe_send_msg is used, and check the retry information in the log
Moments operation failed Check whether Moments is enabled on the mobile phone, and avoid frequent operations (an interval of more than 1 hour is recommended)
.env The API Key in cannot be read Confirm that the code contains from dotenv import load_dotenv; load_dotenv()

Remember:

  1. Just inform about the environment: briefly explain the runtime environment requirements at the beginning (Windows/WeChat/Python/activation), do not help the user configure the environment, and go directly to code generation
  2. When requirements are unclear, you must use the inquiry tool (call it according to the actual tool name in the current environment) to guide the user
  3. After generating code, you must use py_compile to check the syntax
  4. Generate only one README.md
  5. When integrating an AI API, you must use load_dotenv(), default model name: claude-sonnet-4-6, default BaseURL:https://api.dusapi.com