🚀彻底解放双手!微信消息自动化发送脚本工具实战教程
🌈 个人主页:创客白泽 - CSDN博客
🔥 系列专栏:🐍《Python开源项目实战》
💡 热爱不止于代码,热情源自每一个灵感闪现的夜晚。愿以开源之火,点亮前行之路。
👍 如果觉得这篇文章有帮助,欢迎您一键三连,分享给更多人哦
📌 概述
在当今数字化办公场景中,自动化工具已成为提升工作效率的利器。本文将深入剖析一个基于Python的微信自动化工具开发全过程,该工具集成了即时消息发送、定时任务管理和微信进程控制三大核心功能模块。
技术栈亮点:
- PyQt5构建美观的GUI界面
- uiautomation实现Windows UI自动化
- psutil进行进程管理
- 多线程处理保持UI响应
- 完整的异常处理机制
🛠️ 功能全景
1. 核心功能模块
模块名称 | 功能描述 |
---|---|
即时消息发送 | 支持文本+文件混合发送,智能识别联系人 |
定时任务管理 | 精确到秒的定时发送,支持循环任务配置 |
微信进程控制 | 启动/激活/退出微信的一键操作 |
2. 特色功能
- 智能窗口激活:自动置顶微信窗口并居中显示
- 文件绝对路径处理:自动转换相对路径为绝对路径
- 任务持久化:运行时任务列表维护
- 健壮性设计:多重异常处理+操作状态反馈
🎥 效果展示
1. 主界面概览
2. 定时任务配置
3. 操作日志演示
🔧 实现步骤详解
1. 环境准备
pip install pyqt5 psutil uiautomation
2. 工程结构设计
WeChatAutomation/
├── main.py # 主程序入口
├── wechat.ico # 程序图标
└── README.md # 使用说明
3. 核心实现流程
- GUI框架搭建:采用QMainWindow+TabWidget布局
- 工作线程封装:WorkerThread类继承QThread
- 定时任务调度:QTimer秒级轮询检查
- UI自动化控制:uiautomation操作微信窗口
- 异常处理体系:三级错误捕获机制
💻 代码深度解析
1. 多线程任务处理
class WorkerThread(QThread):
finished = pyqtSignal(str, bool) # 信号参数:消息内容, 是否成功
def run(self):
try:
result = self.func(*self.args, **self.kwargs)
self.finished.emit(result or "操作成功", True)
except Exception as e:
self.finished.emit(f"错误: {
str(e)}", False)
设计要点:
- 采用信号槽机制实现线程间通信
- 统一错误处理接口
- 支持任意函数的多线程执行
2. 微信窗口控制核心
def wechat_active():
# 超时设置优化
uiautomation.uiautomation.TIME_OUT_SECOND = 2
if ifProcessRunning():
try:
# 快捷键激活方案
desktop = uiautomation.PaneControl(Name='任务栏')
desktop.SendKeys('{Ctrl}{Alt}w')
except:
# 异常后备方案
os.system('taskkill /F /im "WeChat.exe"')
wechat_start()
else:
wechat_start()
# 恢复默认超时
uiautomation.uiautomation.TIME_OUT_SECOND = 20
wechatWindow = uiautomation.WindowControl(
searchDepth=1,
className='WeChatMainWndForPC',
Name='微信'
)
优化策略:
- 动态调整UI查找超时时间
- 多方案组合提高成功率
- 异常后的自动恢复机制
3. 定时任务调度系统
def check_scheduled_tasks(self):
now = datetime.now()
for task in self.scheduled_tasks:
if not task["completed"] and now >= task["send_time"]:
success = self.send_message(
recipient=task["recipient"],
message=task["message"],
file_path=task["file_path"]
)
if success and task["repeat"]: # 重复任务处理
task["send_time"] = now + timedelta(
minutes=task["interval"]
)
task["completed"] = False
else:
task["completed"] = True
算法特点:
- 低精度定时检查(1秒间隔)
- 支持单次/循环任务模式
- 非阻塞式任务执行
📥 源码获取
# -*- coding:utf-8 -*-
import sys
import psutil
import uiautomation
import os
import time
from datetime import datetime, timedelta
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTabWidget, QLabel, QLineEdit, QTextEdit, QPushButton,
QFileDialog, QMessageBox, QStatusBar, QGroupBox,
QDateTimeEdit, QCheckBox, QSpinBox)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QIcon, QFont
class WorkerThread(QThread):
finished = pyqtSignal(str, bool) # message, success
def __init__(self, func, *args, **kwargs):
super().__init__()
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
try:
result = self.func(*self.args, **self.kwargs)
self.finished.emit(result or "操作成功", True)
except Exception as e:
self.finished.emit(f"错误: {
str(e)}", False)
class WeChatAutomationApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("微信自动化发送工具---BY 白泽")
self.setGeometry(100, 100, 787, 639)
self.setWindowIcon(QIcon("wechat.ico")) # 替换为你的图标文件
# 定时任务列表
self.scheduled_tasks = []
self.timer = QTimer(self)
self.timer.timeout.connect(self.check_scheduled_tasks)
self.timer.start(1000) # 每秒检查一次
# 设置全局字体
font = QFont("Microsoft YaHei", 10)
QApplication.setFont(font)
# 主控件
self.main_widget = QWidget()
self.setCentralWidget(self.main_widget)
# 主布局
self.main_layout = QVBoxLayout(self.main_widget)
self.main_layout.setContentsMargins(15, 15, 15, 15)
self.main_layout.setSpacing(15)
# 创建标签页
self.tabs = QTabWidget()
self.main_layout.addWidget(self.tabs)
# 创建各个标签页
self.create_send_tab()
self.create_schedule_tab()
self.create_control_tab()
# 状态栏
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage("🟢 就绪")
# 样式设置
self.set_style()
def set_style(self):
self.setStyleSheet("""
QMainWindow {
background-color: #f5f5f5;
}
QTabWidget::pane {
border: 1px solid #d3d3d3;
border-radius: 5px;
padding: 5px;
background: white;
}
QTabBar::tab {
padding: 8px 15px;
border: 1px solid #d3d3d3;
border-bottom: none;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
background: #e9e9e9;
margin-right: 2px;
}
QTabBar::tab:selected {
background: white;
border-bottom: 1px solid white;
margin-bottom: -1px;
}
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
min-width: 80px;
}
QPushButton:hover {
background-color: #45a049;
}
QPushButton:pressed {
background-color: #3d8b40;
}
QPushButton:disabled {
background-color: #cccccc;
}
QLineEdit, QTextEdit {
border: 1px solid #d3d3d3;
border-radius: 4px;
padding: 5px;
}
QLabel {
color: #333333;
}
QStatusBar {
background-color: #e9e9e9;
color: #333333;
}
QGroupBox {
border: 1px solid #d3d3d3;
border-radius: 5px;
margin-top: 10px;
padding-top: 15px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 3px;
}
QDateTimeEdit {
padding: 5px;
}
""")
def create_send_tab(self):
"""创建发送消息标签页"""
self.send_tab = QWidget()
self.tabs.addTab(self.send_tab, "📩 即时发送")
layout = QVBoxLayout(self.send_tab