本类是继承了 cluic/wxauto 的微信机器人模块 Windows版本微信客户端自动化
可实现简单的发送、接收微信消息、保存聊天图片
wxauto模块地址: https://github.com/cluic/wxauto
本文代码的功能是实现向微信公众号发送特定消息并监听返回消息来爬取微信公众号返回的消息
直接上代码:
import time
import uiautomation as uia
from .languages import *
from .utils import *
from .elements import *
from .errors import *
from .color import *
from wxauto.wxauto import WeChat
class WxGzh(WeChat):
def __init__(self, language='cn') -> None:
super().__init__(language)
def SendGzhMsg(self, msg, who=None, clear=True):
# 获取窗口
msg_box = self.GetShowGzhWindows(who)
# 如果有输入按钮,就点一下
if msg_box.ButtonControl(Name='输入').Exists(1, 0):
msg_box.ButtonControl(Name='输入').Click(simulateMove=False)
editbox = msg_box.EditControl(searchDepth=10)
if not editbox.Exists(0, 0):
# time.sleep(1)
editbox = msg_box.EditControl(searchDepth=11)
if not editbox.HasKeyboardFocus:
editbox.Click(simulateMove=False)
if clear:
editbox.SendKeys('{Ctrl}a', waitTime=0)
t0 = time.time()
while True:
if time.time() - t0 > 10:
raise TimeoutError(f'发送消息超时 --> {editbox.Name} - {msg}')
SetClipboardText(msg)
editbox.SendKeys('{Ctrl}v')
if editbox.GetValuePattern().Value:
break
editbox.SendKeys('{Enter}')
def GetGzhAllMsgs(self, who):
msg_box = self.GetShowGzhWindows(who)
MsgItems = msg_box.ListControl().GetChildren()
msgs = []
for MsgItem in MsgItems:
msgs.append(self._split(MsgItem, False))
if not [i for i in msgs if i[1] == f"[{self._lang('图片')}]"]:
self.lastmsgid = msgs[-1][-1] if msgs else None
return msgs
def GetGzhRecMsg(self, who, num=0):
'''
这个要跟到发送消息后面用
:param who:
:param num:
:return:
'''
msgs = self.GetGzhAllMsgs(who)
lastmsg = msgs[-1] if msgs else None
if lastmsg[0] == 'Self' and num < 5:
time.sleep(0.5)
num += 1
return self.GetGzhRecMsg(who, num)
if lastmsg[0] == who:
return lastmsg[1]
def GetShowGzhWindows(self, who):
"""
获取并显示公众号的窗口
:param who:
:return:
"""
try:
msg_box = uia.WindowControl(Name=who, ClassName="ChatWnd", searchDepth=1)
if not msg_box.Exists():
# 没找到的话,就变例一边所有的窗口
for element in uia.GetRootControl().GetChildren():
if element.ClassName == "ChatWnd" and element.TextControl(Name=who).Exists():
msg_box = element
if not msg_box.Exists():
self.ChatWith(who)
time.sleep(0.5)
return self.GetShowGzhWindows(who)
if msg_box.Exists():
msg_box.SwitchToThisWindow()
return msg_box
except:
print('没有获取到窗口')
return False
代码继承了wxauto模块,需要先下载wxauto模块,并安装依赖使用
使用方法
wx = WxGzh()
who = "公众号名称"
wx.SendGzhMsg("你好呀西部盒子",who)
print("获取到到所有消息",wx.GetGzhAllMsgs(who))
print("获取最新的回复消息",wx.GetGzhRecMsg(who))
最后感谢wxauto及所有依赖包的开发者