Python uiautomation
Python uiautomation 是一個用於自動化 GUI 測試和操作的庫,它可以模擬用户操作來執行各種任務。通過這個庫,可以使用Python腳本模擬人工點擊,人工操作界面。本文使用 Python uiautomation 進行微信電腦版的操作。
微信電腦版
以下是本次實驗的版本號。
你需要安裝 uiautomation
pip install uiautomation
然後使用 uiautomation 進行操作。
代碼
import time
import uiautomation as auto
import re
from plyer import notification
notification_history = {} # 歷史消息
def check_wechat_messages():
# 獲取微信窗口
wechat_win = auto.WindowControl(Name="微信", ClassName="WeChatMainWndForPC")
shoukuanWin = wechat_win.ListControl(Name="會話")
bbb = shoukuanWin.GetChildren()
for chatMsg in bbb:
if "條新消息" in chatMsg.Name:
# 計算消息條數
match = re.match(r'([a-zA-Z0-9]+)(\d+)條新消息', chatMsg.Name)
if match:
nickname = match.group(1)
message_count = int(match.group(2))
printInfo = f"{nickname} 給你發送了 {message_count} 條消息"
print(printInfo)
print("------------")
# 獲取消息列表控件
xiaoxis = wechat_win.ListControl(Name="消息")
# 獲取消息列表控件的子控件
xiaoxi_children = xiaoxis.GetChildren()
# 獲取最後一個子控件
last_xiaoxi = xiaoxi_children[-1]
# 打印最後一條消息的內容
print(last_xiaoxi.Name)
# 在指定時間內不重發
last_notification_time = notification_history.get((nickname, message_count), 0)
current_time = time.time()
if current_time - last_notification_time > 15:
# 依次發送
notification_title = f"來自 {nickname} 的 {message_count} 條消息"
notification_message = f"{last_xiaoxi.Name}"
notification.notify(
title=notification_title,
message=notification_message,
app_name="WeChat"
)
# 更新日誌
notification_history[(nickname, message_count)] = current_time
if __name__ == "__main__":
try:
while True:
check_wechat_messages()
time.sleep(2) #2秒檢測一次UI組件
except KeyboardInterrupt:
print("程序退出~")
except Exception as e:
print(f"程序執行出現了問題: {str(e)}")
代碼解析:
以上代碼使用 uiautomation 實時獲取微信聊天列表的消息狀態,一旦有消息發過來,就會獲取到發送人的微信暱稱以及發送的消息內容、消息個數。
每2秒獲取一次UI控件的內容,實測掛在後台對CPU和內存佔用並無明顯影響。
結合Python uiautomation的各種用法,可以做成自動回覆的功能。
UISpy.exe
使用這款軟件,可以獲取到微信電腦版大部分控件的內容。
例如:微信聊天列表、羣名稱、好友微信暱稱、羣人數、微信號等。
還可以獲取到羣內的每一條聊天內容,獲取到你跟好友的聊天記錄。
只要 UISpy.exe 可獲取到的控件內容,那麼你用 Python就可以獲取到。
作者
TANKING