search_key_mac.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/2/20
  4. """
  5. 安装 atomac:
  6. 1.翻墙
  7. 2.pip3 install git+https://github.com/pyatom/pyatom/
  8. """
  9. import json
  10. import os
  11. import sys
  12. import time
  13. import atomac
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common.feishu import Feishu
  17. class SearchKey:
  18. # 启动微信 / 微信指数小程序 ; 关闭微信 / 微信指数小程序
  19. @classmethod
  20. def start_wechat(cls, log_type, crawler):
  21. try:
  22. # 启动应用并获取应用信息
  23. bundle_id = "com.tencent.xinWeChat"
  24. Common.logger(log_type, crawler).info("启动微信")
  25. atomac.launchAppByBundleId(bundle_id)
  26. automator = atomac.getAppRefByBundleId(bundle_id)
  27. time.sleep(1)
  28. # 获取当前应用window
  29. window = automator.windows()[0]
  30. Common.logger(log_type, crawler).info(f"当前应用window:{window.AXTitle}")
  31. # 查找聊天按钮
  32. Common.logger(log_type, crawler).info("查找聊天按钮")
  33. chat_btn = window.findFirstR(AXHelp="微信", AXRole="AXRadioButton")
  34. # print(chat_btn.getAttributes())
  35. # 点击聊天按钮,展开聊天列表
  36. Common.logger(log_type, crawler).info("点击聊天按钮")
  37. chat_btn.Press()
  38. time.sleep(1)
  39. # 查找文件传输助手
  40. Common.logger(log_type, crawler).info("查找文件传输助手")
  41. chat_help = window.findFirstR(AXIdentifier="MMChatsTableCellView_0" ,AXRole="AXCell")
  42. Common.logger(log_type, crawler).info(f"文件传输助手:{chat_help}")
  43. chat_help_position = chat_help.AXPosition
  44. chat_help_size = chat_help.AXSize
  45. chat_help_coor = (abs(chat_help_position[0])+chat_help_size[0]/2, abs(chat_help_position[1])+chat_help_size[1]/2)
  46. Common.logger(log_type, crawler).info(f"文件传输助手坐标:{chat_help_coor}")
  47. Common.logger(log_type, crawler).info("点击文件传输助手")
  48. for i in range(2):
  49. chat_help.clickMouseButtonLeft(chat_help_coor)
  50. time.sleep(1)
  51. Common.logger(log_type, crawler).info("查找微信指数小程序消息")
  52. weixinzhishu = window.findFirstR(AXValue="微信指数", AXRole="AXStaticText")
  53. Common.logger(log_type, crawler).info(f"微信指数小程序:{weixinzhishu}")
  54. weixinzhishu_box = weixinzhishu.AXPosition
  55. weixinzhishu_position = weixinzhishu.AXSize
  56. weixinzhishu_coord = (abs(weixinzhishu_box[0])+weixinzhishu_position[0]/2, abs(weixinzhishu_box[1])+weixinzhishu_position[1])
  57. Common.logger(log_type, crawler).info(f"微信指数小程序坐标:{weixinzhishu_coord}")
  58. Common.logger(log_type, crawler).info("点击微信指数小程序消息")
  59. for i in range(2):
  60. weixinzhishu.clickMouseButtonLeft(weixinzhishu_coord)
  61. time.sleep(3)
  62. close_wechat = window.findFirstR(AXSubrole="AXCloseButton", AXRole="AXButton")
  63. close_wechat.Press()
  64. time.sleep(1)
  65. Common.logger(log_type, crawler).info("关闭微信成功")
  66. Common.logger(log_type, crawler).info("关闭微信指数小程序")
  67. time.sleep(3)
  68. cmd = "ps aux | grep Program.app | grep -v grep | awk '{print $2}' | xargs kill -9"
  69. os.system(cmd)
  70. Common.logger(log_type, crawler).info("微信指数小程序关闭成功")
  71. time.sleep(1)
  72. except Exception as e:
  73. Common.logger(log_type, crawler).info(f"start_wechat:{e}\n")
  74. # 获取微信指数小程序 search_key
  75. @classmethod
  76. def get_wechat_key(cls, log_type, crawler):
  77. try:
  78. while True:
  79. chlsfile_path = f"./{crawler}/{crawler}_chlsfiles/"
  80. if len(os.listdir(chlsfile_path)) == 0:
  81. Common.logger(log_type, crawler).info("chlsfile文件夹空,等待 3 秒")
  82. time.sleep(3)
  83. cls.start_wechat(log_type, crawler)
  84. continue
  85. Common.logger(log_type, crawler).info(f"chlsfile_list:{sorted(os.listdir(chlsfile_path))}")
  86. # 获取最新的 chlsfile
  87. chlsfile = sorted(os.listdir(chlsfile_path))[-1]
  88. # 分离文件名与扩展名
  89. new_file = os.path.splitext(chlsfile)
  90. # 重命名文件后缀
  91. os.rename(os.path.join(chlsfile_path, chlsfile),
  92. os.path.join(chlsfile_path, new_file[0] + ".txt"))
  93. with open(f"{chlsfile_path}{new_file[0]}.txt", encoding='utf-8-sig', errors='ignore') as f:
  94. contents = json.load(f, strict=False)
  95. if "search.weixin.qq.com" not in [text['host'] for text in contents]:
  96. return "未找到wechat_key"
  97. else:
  98. for content in contents:
  99. if content["host"] == "search.weixin.qq.com" and content["path"] == "/cgi-bin/wxaweb/wxawebreport":
  100. # print(f"content:{content}")
  101. text = content['request']['body']['text']
  102. search_key = json.loads(text)['search_key']
  103. openid = json.loads(text)['openid']
  104. wechat_key_dict = {
  105. "search_key": search_key,
  106. "openid": openid,
  107. }
  108. return wechat_key_dict
  109. elif content["host"] == "search.weixin.qq.com" and content["path"] == "/cgi-bin/wxaweb/wxindexgetusergroup":
  110. text = content['request']['body']['text']
  111. search_key = json.loads(text)['search_key']
  112. openid = json.loads(text)['openid']
  113. wechat_key_dict = {
  114. "search_key": search_key,
  115. "openid": openid,
  116. }
  117. return wechat_key_dict
  118. else:
  119. return "未找到wechat_key"
  120. except Exception as e:
  121. Common.logger(log_type, crawler).error(f"get_wechat_key:{e}\n")
  122. # 删除 chlsfile 文件
  123. @classmethod
  124. def remove_chlsfile(cls, log_type, crawler):
  125. try:
  126. all_file_path = f"./{crawler}/{crawler}_chlsfiles/"
  127. if not os.path.exists(all_file_path):
  128. os.mkdir(all_file_path)
  129. all_file = os.listdir(all_file_path)
  130. for file in all_file:
  131. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  132. except Exception as e:
  133. Common.logger(log_type, crawler).error(f"remove_file异常:{e}\n")
  134. # 删除微信指数小程序 search_key
  135. @classmethod
  136. def del_wechat_key(cls, log_type, crawler):
  137. try:
  138. while True:
  139. sheet = Feishu.get_values_batch(log_type, crawler, 'sVL74k')
  140. if sheet is None:
  141. Common.logger(log_type, crawler).info(f"wechat_key_sheet:{sheet}, 1秒后重新获取")
  142. time.sleep(1)
  143. continue
  144. if len(sheet) <= 51:
  145. return
  146. else:
  147. Feishu.dimension_range(log_type, crawler, 'sVL74k', 'ROWS', 52, 52)
  148. except Exception as e:
  149. Common.logger(log_type, crawler).error(f"del_wechat_key异常:{e}\n")
  150. # 微信指数小程序 search_key 写入飞书
  151. @classmethod
  152. def write_wechat_key(cls, log_type, crawler):
  153. try:
  154. Common.logger(log_type, crawler).info(f"清空 chlsfiles 文件夹")
  155. cls.remove_chlsfile(log_type, crawler)
  156. Common.logger(log_type, crawler).info('获取 wechat_key')
  157. while True:
  158. cls.start_wechat(log_type, crawler)
  159. wechat_key_dict = cls.get_wechat_key(log_type, crawler)
  160. if wechat_key_dict is None or wechat_key_dict == "未找到wechat_key":
  161. Common.logger(log_type, crawler).info("未找到wechat_key,重新获取")
  162. time.sleep(1)
  163. continue
  164. for k, v in wechat_key_dict.items():
  165. Common.logger(log_type, crawler).info(f"{k}:{v}")
  166. Feishu.insert_columns(log_type, crawler, 'sVL74k', 'ROWS', 1, 2)
  167. time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
  168. values = [[time_str, wechat_key_dict['search_key'], wechat_key_dict['openid']]]
  169. time.sleep(1)
  170. Feishu.update_values(log_type, crawler, 'sVL74k', 'A2:Z2', values)
  171. cls.del_wechat_key(log_type, crawler)
  172. Common.logger(log_type, crawler).info("wechat_key写入飞书成功")
  173. Common.del_logs(log_type, crawler)
  174. return
  175. except Exception as e:
  176. Common.logger(log_type, crawler).error(f"write_wechat_key:{e}\n")
  177. @classmethod
  178. def main(cls, log_type, crawler):
  179. while True:
  180. try:
  181. cls.write_wechat_key(log_type, crawler)
  182. Common.logger(log_type, crawler).info('休眠10秒\n')
  183. time.sleep(10)
  184. except Exception as e:
  185. Common.logger(log_type, crawler).error(f"{e}\n")
  186. if __name__ == "__main__":
  187. # SearchKey.start_wechat("search", "weixinzhishu")
  188. # SearchKey.del_wechat_key("search", "weixinzhishu")
  189. # SearchKey.write_wechat_key("search", "weixinzhishu")
  190. # print(SearchKey.get_wechat_key("search", "weixinzhishu"))
  191. SearchKey.main("search", "weixinzhishu")
  192. pass