使用Python实现自动发送微信消息源代码

使用Python实现自动发送微信消息源代码

这是我基于python的自动化库uiautomation库实现使用PC版微信向指定微信好友发送文本和文件消息的源代码,可参考使用。

# coding=utf-8
import os
import subprocess
from typing import Union, List, Tuple, Dict
import uiautomation as auto
import pyperclip


class WxSendMsg:
    """用于发送微信消息的类"""

    def __init__(self):
        # 初始化 绑定微信控件
        self._wx = auto.WindowControl(
            Name='微信', ClassName='WeChatMainWndForPC', searchDepth=1, foundIndex=1)
        self._search_edit = self._wx.EditControl(Name='搜索')
        self._chat_btn = self._wx.ButtonControl(Name="聊天")
        self._huiHua_list = self._wx.ListControl(Name="会话")
        self._contact_list = self._wx.ListControl(
            SubName="@str:IDS_FAV_SEARCH_RESULT")
        self._send_btn = self._wx.ButtonControl(Name="发送(S)")

    def _call_wx(self) -> bool:
        """检查微信窗口是否存在"""
        if not self._wx.Exists(1):
            print("未检测到微信窗口,请登录微信并让微信窗口最小化或显示在桌面上。")
            return False
        # 切换到微信主窗口
        self._wx.SwitchToThisWindow()
        self._chat_btn.Click(waitTime=1)
        return True

    def _goto_chat_box(self, search_value: str) -> bool:
        """跳转到指定微信好友的聊天窗口"""
        if not isinstance(search_value, str):
            raise TypeError("查找内容必须是字符串类型")
        # 定位到搜索框
        self._wx.SendKeys(text='{Ctrl}f', waitTime=1)
        self._wx.SendKeys(text='{Ctrl}a', waitTime=1)
        self._wx.SendKey(key=auto.SpecialKeyNames['DELETE'], waitTime=1)
        # 输入搜索内容
        self._search_edit.SendKeys(text=search_value, waitTime=1)
        # 断言
        is_success = self._assert_search(search_value)
        if is_success:
            self._wx.SendKey(key=auto.SpecialKeyNames['ENTER'], waitTime=1)
            print("查询好友成功")
            return True
        else:
            self._wx.SendKey(key=auto.SpecialKeyNames['ESC'], waitTime=1)
            print("查询好友失败")
            return False

    def _assert_search(self, search_value) -> bool:
        """断言查找好友是否成功"""
        items = self._contact_list.GetChildren()
        if items[0].ControlType != auto.ControlType.PaneControl:
            return False
        elif items[0].GetFirstChildControl().Name not in ("联系人", "群聊"):
            return False
        elif items[1].ControlType != auto.ControlType.ListItemControl:
            return False
        # 是联系人或群,判断是否匹配到该好友
        elif items[1].Name == search_value:
            return True
        elif not items[1].TextControl(foundIndex=2).Exists(0.5, 0.1):
            return False
        elif items[1].TextControl(foundIndex=2).Name == "微信号: <em>{}</em>".format(search_value):
            return True
        elif items[1].TextControl(foundIndex=2).Name == "昵称: <em>{}</em>".format(search_value):
            return True
        else:
            return False

    def _send_text(self, msg: str) -> None:
        """发送文本"""
        if not isinstance(msg, str):
            raise TypeError("发送的文本内容必须是字符串类型")
        if len(msg) > 2048:
            raise ValueError("发送的文本内容最大不超过2048")
        input_edit = self._send_btn.GetParentControl(
        ).GetParentControl().GetParentControl().EditControl()
        input_edit.SendKeys(text='{Ctrl}a', waitTime=1)
        input_edit.SendKey(key=auto.SpecialKeyNames['DELETE'], waitTime=1)
        # 设置到剪切板再黏贴到输入框
        # 不能使用uiautomation设置剪切板,内容过长时会导致剪切板内容设置不全
        # auto.SetClipboardText(text=msg)
        pyperclip.copy(msg)
        input_edit.SendKeys('{Ctrl}v', waitTime=1)
        # 一个个字符插入,效率低而且会导致输入的内容格式与设置的内容格式不一致。
        # self.input_edit.SendKeys(text=msg, waitTime=1)
        self._wx.SendKey(key=auto.SpecialKeyNames['ENTER'], waitTime=1)

    def _send_file(self, file_paths: Union[List[str], Tuple[str]]) -> None:
        """发送多个文件"""
        all_path_box = []
        for path in file_paths:
            assert os.path.exists(path), f"{path} 文件路径有误"
            all_path_box.append("'" + path + "'")
        all_path = ",".join(all_path_box)
        command = ['powershell', f'Get-Item {all_path} | Set-Clipboard']
        # subprocess.run阻塞方法,会等待剪切板设置完成
        subprocess.run(command)
        input_edit = self._send_btn.GetParentControl(
        ).GetParentControl().GetParentControl().EditControl()
        input_edit.SendKeys(text='{Ctrl}v', waitTime=1)
        self._wx.SendKey(key=auto.SpecialKeyNames['ENTER'], waitTime=1)

    def send_wx(self, search_value: str, contents: List[Dict[str, Union[str, List[str]]]]) -> bool:
        """
        发送消息,可同时发送文本和文件,不可为空
        
        :param search_value: str, 查找内容,可以是备注、微信昵称或微信号
        :param contents: List[Dict[str, Union[str, List[str]]]], 发送的内容列表,
        每个元素为一个字典,可包含以下键值对:
            - "msg": str, 要发送的文本消息内容
            - "file_paths": List[str], 要发送的文件路径列表
        :return: bool, 发送是否成功
        
        示例:
            search_value = "七鱼ঞ"
            
            contents = [
                {"msg": "hello", "file_paths": ["hello.txt"]}
            ]
            
            sm = WxSendMsg()
            
            sm.send_wx(search_value, contents)
        """
        is_success = self._call_wx()
        if is_success is False:
            return False
        print(f"向好友{search_value}开始发送")
        is_success = self._goto_chat_box(search_value)
        if is_success is False:
            return False
        for content in contents:
            msg = content.get("msg")
            file_paths = content.get("file_paths")
            if not any([msg, file_paths]):
                raise ValueError("请选择文本或文件进行发送,不能发送空消息。")
            if msg:
                self._send_text(msg)
            if file_paths:
                self._send_file(file_paths)
        print(f"向好友{search_value}发送完成")
        return True

uiautomation参考链接

微软官方: https://learn.microsoft.com/zh-cn/dotnet/framework/ui-automation/using-ui-automation-for-automated-testing

GitHub: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows

写在最后

  1. 代码仅供学习交流使用,请勿用于其他用途。
  2. 基于PC端微信版本3.9.6.47进行编写的代码,其他版本的微信很可能不适用。
  3. uiautomation版本为2.0.18,其他版本未测试。
  4. python版本为3.8,需自行测试与其他python版本是否兼容。

文章编写于2023年12月

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值