0


python_uiautoanimation实现自动化微信聊天

文章目录

yma16-logo

⭐前言

大家好,我是yma16,本文分享python_uiautoanimation实现自动化微信聊天。

uiautoanimation简介

uiautomation封装了微软UIAutomation API,支持自动化Win32,MFC,WPF,Modern UI(Metro UI), Qt, IE, Firefox(version<=56 or >=60

开源文档:https://github.com/yinkaisheng/Python-UIAutomation-for-Windows?tab=readme-ov-file

python系列文章
python爬虫_基本数据类型
python爬虫_函数的使用
python爬虫_requests的使用
python爬虫_selenuim可视化质量分
python爬虫_django+vue3可视化csdn用户质量分
python爬虫_正则表达式获取天气预报并用echarts折线图显示
python爬虫_requests获取bilibili锻刀村系列的字幕并用分词划分可视化词云图展示

⭐微软inspect工具定位元素

💖工具查找属性

官方地址:https://learn.microsoft.com/zh-cn/windows/win32/winauto/inspect-objects
打开inspect点击元素即可查找属性,这里我查找微信小程序平台的窗口
在这里插入图片描述

⭐查找微信窗口

💖命令行查找运行窗口

pip 安装 automation 在scripts目录下运行automation.py

  1. automation.py -t0# 打印当前激活窗口的所有控件
  2. automation.py -r-d1-t0# 打印桌面(树的根控件 )和它的第一层子窗口(TopLevel顶层窗口)

⭐查找微信的聊天窗口

首先查找微信主窗口

  1. import uiautomation as auto
  2. if__name__=='__main__':
  3. global wechatWindow
  4. wechatWindow = auto.WindowControl(searchDepth=1, Name="微信", ClassName='WeChatMainWndForPC')
  5. print('wechatWindow',wechatWindow)

查找窗口
在这里插入图片描述

⭐封装发送消息

查找输入框
在这里插入图片描述

  1. defsendMsg(wechatWindow,msg):# 群聊
  2. edit = wechatWindow.EditControl(Name='微信小程序平台')
  3. prefix=""
  4. edit.SendKeys(prefix+msg)
  5. sendButton = wechatWindow.ButtonControl(Name='发送(S)')
  6. sendButton.Click()

⭐定时查询消息

定位消息元素
定时查找消息
遇到@回复消息

  1. import uiautomation as auto
  2. import json,time
  3. import requests,json
  4. API_KEY ="API_KEY "
  5. SECRET_KEY ="SECRET_KEY "
  6. def receive_commend(url, message):
  7. payload = json.dumps({"messages":[{"role":"user",
  8. "content": message
  9. }]})
  10. headers ={'Content-Type':'application/json'}
  11. response = requests.request("POST", url, headers=headers, data=payload)if response.status_code ==200:
  12. return response.json()['result']
  13. else:
  14. return response.text
  15. def get_access_token():
  16. url ="https://aip.baidubce.com/oauth/2.0/token"
  17. params ={"grant_type":"client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}return str(requests.post(url, params=params).json().get("access_token"))
  18. def ai_answer(question):
  19. url ="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()return receive_commend(url, question)
  20. def sendMsg(wechatWindow,msg):
  21. # 群聊
  22. edit = wechatWindow.EditControl(ProcessId='微信小程序平台')prefix=""
  23. edit.SendKeys(prefix+msg)
  24. sendButton = wechatWindow.ButtonControl(Name='发送(S)')
  25. sendButton.Click()
  26. def writeJson(data,name):
  27. with open("./db/"+name, 'w', encoding='utf-8') as write_f:
  28. write_f.write(json.dumps(data, indent=4, ensure_ascii=False))
  29. def saveOldChatJson(data):
  30. writeJson(data,'oldChat.json')
  31. def saveNewChatJson(data):
  32. writeJson(data,'newChat.json')
  33. def openNewJson():
  34. with open("./db/newChat.json", 'r', encoding='utf-8') as open_f:
  35. content = open_f.read()
  36. readJson = json.loads(content)return readJson
  37. def openOldJson():
  38. with open("./db/oldChat.json", 'r', encoding='utf-8') as open_f:
  39. content = open_f.read()
  40. readJson = json.loads(content)return readJson
  41. def getMsg(wechatWindow):
  42. oldJson=openOldJson()newChatFileJson=openNewJson()
  43. wechatWindow.SetFocus()
  44. messages = wechatWindow.ListControl(Name='消息')
  45. replyRes =[]chatRes=[]# 备份newJson=oldJson
  46. markFont ='@robot\u2005'sendTime='empty_time'
  47. isCall ='否'
  48. isFinish ='否'# 新的聊天记录newChatJson={}
  49. print('messages',messages)map_index=0max_len=len(messages.GetChildren())foriin range(1):
  50. if max_len <=0:
  51. breakmessage=messages.GetChildren()[max_len-1]# 跳过
  52. print('message',message)
  53. content = message.Name
  54. print('content',content)if content in["查看更多", "以下为新消息","以下是新消息"]:
  55. print('匹配新消息')continue
  56. details = message.GetChildren()[0].GetChildren()if len(details)==0:
  57. sendTime = content
  58. continuename=''detail=''me=''
  59. print('details', details)
  60. nickname, detail, me = details
  61. name = nickname.Name
  62. print('nickname, detail, me',nickname, detail, me)if me.Name:
  63. name = me.Name
  64. if name == markFont:
  65. continueif not (content =="[图片]" or content.startswith("[语音]")):
  66. details = detail.GetChildren()if len(details)==0:
  67. continue
  68. detail = details[-1].GetChildren()[0].GetChildren()[0].GetChildren()[0]
  69. details = detail.GetChildren()if len(details)!=0:
  70. link_title = details[0].Name
  71. link_content = details[1].Name
  72. content += link_title+'/n'+link_content
  73. recieveMsg=content.strip()# 本人 聊天跳过(出现在newChat.json则跳过)if sendTime in newChatFileJson.keys()\
  74. or isinstance(sendTime,str)\
  75. and sendTime in oldJson.keys()\
  76. and'isFinish'in oldJson[sendTime].keys()\
  77. and oldJson[sendTime]['isFinish']=='是'\
  78. and oldJson[sendTime]['content']==recieveMsg:
  79. print('time empty___',oldJson[sendTime])continue
  80. elif(markFont in recieveMsg and name != markFont ):
  81. isCall='是'askQuestion=recieveMsg.replace(markFont,'')
  82. print(askQuestion)if askQuestion:
  83. prefix='@'+name+'\u2005关于“'+askQuestion+'”的回复: '
  84. sendMsg(wechatWindow,prefix+ai_answer(askQuestion))isFinish='是'# 写入数据
  85. replyRes.append([sendTime, name, recieveMsg, isCall, isFinish])# 新的聊天记录
  86. chatRes.append([sendTime, name, recieveMsg])# 替换 旧消息foritemin replyRes:
  87. timeItem=item[0]if isinstance(timeItem,str):
  88. # 已回复的消息
  89. newJson[str(timeItem)]={"name":item[1],
  90. "content":item[2],
  91. "isFinish":item[4]}# 替换foritemin chatRes:
  92. timeItem=item[0]if isinstance(timeItem,str):
  93. # 新的消息回复
  94. newChatJson[str(timeItem)]={"name":item[1],
  95. "content":item[2]}# 已回复的记录
  96. saveOldChatJson(newJson)# 新的消息回复
  97. saveNewChatJson(newChatJson)
  98. re_run()
  99. def re_run():
  100. time.sleep(3)
  101. global wechatWindow
  102. getMsg(wechatWindow)if__name__=='__main__':
  103. global wechatWindow
  104. wechatWindow = auto.WindowControl(searchDepth=1, Name="微信", ClassName='WeChatMainWndForPC')
  105. print('wechatWindow',wechatWindow)
  106. getMsg(wechatWindow)

定时轮询查找消息调用chatgpt回复
在这里插入图片描述

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
在这里插入图片描述

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 感谢你的阅读!

标签: python 自动化 微信

本文转载自: https://blog.csdn.net/qq_38870145/article/details/142111547
版权归原作者 yma16 所有, 如有侵权,请联系我们删除。

“python_uiautoanimation实现自动化微信聊天”的评论:

还没有评论