python 发送微信消息

python 自动化,可以模拟键盘输入,因此,可以控制微信,发送消息,代码如下:

 1 import sys
 2 import pyautogui
 3 import pyperclip
 4 import time
 5 import configparser
 6 
 7 """
 8 安装依赖:
 9 pip install pyautogui pyperclip pyinstaller
10 
11 打包成 exe:
12 pyinstaller --onefile wx.py
13 
14 用法: wx.exe 用户备注名 消息1  消息2 ... 消息N
15 示例: wx.exe 张三  在吗?   周末有空吗?   出来喝酒呀!
16 
17 
18 """
19 class Wx(object):
20 
21     """ python 在类中,方法名和属性名不能同名这里,用属性用大写,方法用小写 """
22 
23     def __init__(self, name = ''):
24         self.Name = name
25 
26     def name(self, name):
27         self.Name = name
28         return self
29 
30     def config(self, file, section = '', encoding='utf-8'):
31         """
32         读取ini 配置文件
33 
34         ; config.ini 方法示例
35         [db] ; 这是一个 section
36         host = 127.0.0.1
37         port = 3306
38 
39         [redis] ; 这又是一个 section
40         host = localhost
41 
42         """
43 
44         # 创建配置文件对象
45         self.Config = configparser.ConfigParser()
46         self.Config.read(file, encoding)
47         return self
48 
49 
50     def section(self, section = ''):
51         if not section:
52             # 获取所有section
53             return self.Config.sections()
54 
55         return dict(self.Config.items(section))
56 
57 
58     def send(self, messages = "你好"):
59         if not self.Name:
60             print("接收者名称为空!")
61             sys.exit(1)
62 
63         pyautogui.hotkey('ctrl', 'alt', 'w')    # ctrl + alt + w 打开微信
64         pyautogui.hotkey('ctrl', 'f')           # 打开查找
65         pyperclip.copy(self.Name)               # 复制好友昵称到粘贴板
66         pyautogui.hotkey('ctrl', 'v')           # 模拟键盘 ctrl + v 粘贴
67         time.sleep(1)
68         pyautogui.press('enter')                # 回车进入好友消息界面
69 
70         if not isinstance(messages, list):
71             messages = [messages]
72 
73         for msg in messages:
74             pyperclip.copy(msg)             # 复制需要发送的内容到粘贴板
75             pyautogui.hotkey('ctrl', 'v')   # 模拟键盘 ctrl + v 粘贴内容
76             pyautogui.press('enter')        # 发送消息
77             time.sleep(1)    # 每条消息间隔 1 秒
78 
79         return self
80 
81 
82 
83 
84 if __name__ == '__main__':
85 
86     if len(sys.argv) < 3: # 当缺少必要参数时
87         input = input("请输入备注名和待发送多条消息(以空格分割):").split()
88         name = input[0]
89         messages = input[1:]
90     else:
91         name = sys.argv[1]
92         messages = sys.argv[2:]
93 
94 
95     Wx().name(name).send(messages)
96 
97     # 测试读取配置文件
98     # print(Wx().config('config.ini').section("db"))

 

posted @ 2023-05-25 21:57  心随所遇  阅读(709)  评论(0编辑  收藏  举报