auto_reply_cards_monitor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import json
  2. import time
  3. import uuid
  4. import xml.etree.ElementTree as ET
  5. from datetime import datetime, timedelta
  6. from urllib.parse import unquote, parse_qs
  7. from applications.utils import fetch_from_odps
  8. from applications.utils import AsyncHttpClient
  9. from applications.crawler.wechat import get_article_list_from_account
  10. from applications.crawler.wechat import get_article_detail
  11. class AutoReplyCardsMonitorConst:
  12. # fetch_status
  13. FETCH_INIT_STATUS = 0
  14. FETCH_PROCESSING_STATUS = 1
  15. FETCH_SUCCESS_STATUS = 2
  16. FETCH_FAIL_STATUS = 3
  17. # task_status
  18. INIT_STATUS = 0
  19. PROCESSING_STATUS = 1
  20. SUCCESS_STATUS = 2
  21. FAIL_STATUS = 99
  22. # account_status
  23. VALID_STATUS = 1
  24. INVALID_STATUS = 0
  25. class AutoReplyCardsMonitorUtils(AutoReplyCardsMonitorConst):
  26. @staticmethod
  27. def generate_task_id(task_name, gh_id):
  28. match task_name:
  29. case "follow":
  30. return f"{task_name}_{gh_id}"
  31. case _:
  32. return f"{task_name}_{uuid.uuid4()}"
  33. @staticmethod
  34. def extract_reply_cards(msg_type, root):
  35. page_path = root.find(".//pagepath").text
  36. card_title = root.find(".//title").text
  37. mini_program = root.find(".//sourcedisplayname").text
  38. file_id = root.find("appmsg/appattach/cdnthumburl").text
  39. ase_key = root.find("appmsg/appattach/aeskey").text
  40. file_size = root.find("appmsg/appattach/cdnthumblength").text
  41. return {
  42. "title": card_title,
  43. "page_path": page_path,
  44. "msg_type": msg_type,
  45. "mini_program": mini_program,
  46. "file_id": file_id,
  47. "file_size": file_size,
  48. "ase_key": ase_key,
  49. }
  50. @staticmethod
  51. def extract_reply_articles(msg_type, root):
  52. title = root.find("appmsg/title").text
  53. url = root.find("appmsg/url").text
  54. cover_url = root.find("appmsg/thumburl").text
  55. account_name = root.find("appmsg/sourcedisplayname").text
  56. gh_id = root.find("appmsg/sourceusername").text
  57. desc = root.find("appmsg/des").text
  58. return {
  59. "msg_type": msg_type,
  60. "title": title,
  61. "url": url,
  62. "cover_url": cover_url,
  63. "account_name": account_name,
  64. "gh_id": gh_id,
  65. "desc": desc,
  66. }
  67. # 解析 xml
  68. @staticmethod
  69. def extract_callback_xml(self, xml_text):
  70. try:
  71. root = ET.fromstring(xml_text)
  72. msg_type = root.find("appmsg/type").text
  73. match msg_type:
  74. case "5":
  75. return self.extract_reply_articles(msg_type, root)
  76. case "33":
  77. return self.extract_reply_cards(msg_type, root)
  78. case "36":
  79. return self.extract_reply_cards(msg_type, root)
  80. case _:
  81. return {
  82. "msg_type": msg_type,
  83. }
  84. except Exception as e:
  85. print(e)
  86. return {}
  87. # 解析 page_path
  88. @staticmethod
  89. def extract_page_path(page_path):
  90. pass
  91. @staticmethod
  92. async def get_cover_url(aes_key, total_size, file_id):
  93. url = "http://api.geweapi.com/gewe/v2/api/message/downloadCdn"
  94. data = {
  95. "appId": "wx_anFlUnezoUynU3SKcqTWk",
  96. "aesKey": aes_key,
  97. "totalSize": total_size,
  98. "fileId": file_id,
  99. "type": "3",
  100. "suffix": "jpg",
  101. }
  102. headers = {
  103. "X-GEWE-TOKEN": "d3fb918f-0f36-4769-b095-410181614231",
  104. "Content-Type": "application/json",
  105. }
  106. async with AsyncHttpClient() as client:
  107. response = await client.post(url, headers=headers, data=json.dumps(data))
  108. return response
  109. @staticmethod
  110. async def get_sample_url(recent_articles):
  111. for article in recent_articles:
  112. link = article["ContentUrl"]
  113. print(link)
  114. response = await get_article_detail(article_link=link)
  115. print(response)
  116. if not response:
  117. continue
  118. code = response["code"]
  119. if code == 0 or code == 25006:
  120. return link
  121. return None
  122. # 获取检测的账号 list
  123. @staticmethod
  124. def get_monitor_account_list():
  125. yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y%m%d")
  126. query = f"""
  127. SELECT 公众号名, ghid, count(DISTINCT mid) AS uv
  128. FROM loghubods.opengid_base_data
  129. WHERE dt = {yesterday}
  130. AND hotsencetype = 1074
  131. AND usersharedepth = 0
  132. AND channel = '公众号合作-即转-稳定'
  133. GROUP BY 公众号名, ghid
  134. HAVING uv > 100
  135. ORDER BY uv DESC
  136. ;
  137. """
  138. result = fetch_from_odps(query)
  139. return result
  140. # 下载封面图片
  141. async def download_cover(self, url, file_path):
  142. pass
  143. # 上传封面至 oss
  144. async def upload_cover(self, file_path):
  145. pass
  146. class AutoReplyCardsMonitorMapper(AutoReplyCardsMonitorUtils):
  147. def __init__(self, pool, log_client):
  148. self.pool = pool
  149. self.log_client = log_client
  150. # 获取关注公众号任务结果
  151. async def get_follow_account_task_result(self, task_id):
  152. pass
  153. # 创建自动回复任务
  154. async def create_auto_reply_task(self):
  155. pass
  156. # 获取自动回复任务结果
  157. async def get_auto_reply_task_result(self, task_id):
  158. query = """
  159. SELECT task_result, task_status, err_msg,from_unixtime(update_timestamp / 1000) AS update_time
  160. FROM gzh_msg_record
  161. WHERE task_id = %s;
  162. """
  163. return await self.pool.async_fetch(
  164. query=query, params=(task_id,), db_name="aigc"
  165. )
  166. # 获取关注公众号任务列表
  167. async def get_follow_account_task_list(self):
  168. pass
  169. # 获取自动回复任务列表
  170. async def get_auto_reply_task_list(self):
  171. pass
  172. # 插入待关注公众号
  173. async def insert_accounts_task(self, account_name, gh_id):
  174. pass
  175. # 查询账号
  176. async def fetch_account_status(self, account_name):
  177. query = """
  178. SELECT partner_name, partner_id, gh_id, status, follow_status
  179. FROM cooperate_accounts
  180. WHERE account_name = %s;
  181. """
  182. return await self.pool.async_fetch(
  183. query=query, params=(account_name,)
  184. )
  185. # 更新账号状态为无效
  186. async def set_account_as_invalid(self, gh_id):
  187. query = """
  188. UPDATE cooperate_accounts SET status = %s WHERE gh_id = %s;
  189. """
  190. await self.pool.async_save(query=query, params=(self.INVALID_STATUS, gh_id))
  191. # 插入AIGC关注公众号任务
  192. async def insert_aigc_follow_account_task(self, task_id, link):
  193. timestamp = int(time.time() * 1000)
  194. query = """
  195. INSERT INTO gzh_msg_record (task_id, biz_type, task_params, create_timestamp, update_timestamp) VALUES (%s, %s, %s, %s, %s);
  196. """
  197. return await self.pool.async_save(query=query, params=(task_id, "follow", link, timestamp, timestamp), db_name="aigc")
  198. # 插入AIGC自动回复任务
  199. async def insert_aigc_auto_reply_task(self, task_id, account_name):
  200. timestamp = int(time.time() * 1000)
  201. query = """
  202. INSERT INTO gzh_msg_record (task_id, task_params, create_timestamp, update_timestamp) VALUES (%s, %s, %s, %s);
  203. """
  204. return await self.pool.async_save(query=query, params=(task_id, account_name, timestamp, timestamp), db_name="aigc")
  205. # 为账号设置 sample_url
  206. async def set_sample_url(self, gh_id, sample_url):
  207. query = """
  208. UPDATE cooperate_accounts SET sample_link = %s WHERE gh_id = %s;
  209. """
  210. return await self.pool.async_save(query=query, params=(sample_url, gh_id))
  211. # 修改账号的关注状态
  212. async def update_follow_status(self, gh_id, ori_status, new_status):
  213. query = """
  214. UPDATE cooperate_accounts SET follow_status = %s WHERE gh_id = %s and follow_status = %s;
  215. """
  216. return await self.pool.async_save(query=query, params=(new_status, gh_id, ori_status))
  217. # 从 aigc 获取关注结果
  218. async def fetch_follow_account_status(self, gh_id):
  219. query = """
  220. SELECT task_status, err_msg
  221. FROM gzh_msg_record
  222. WHERE task_id = %s;
  223. """
  224. return await self.pool.async_fetch(
  225. query=query, params=(f"follow_{gh_id}",), db_name="aigc"
  226. )
  227. class AutoReplyCardsMonitor(AutoReplyCardsMonitorMapper):
  228. def __init__(self, pool, log_client):
  229. super().__init__(pool, log_client)
  230. # 创建单个关注公众号任务
  231. async def create_follow_account_task(self, gh_id):
  232. response = await get_article_list_from_account(account_id=gh_id)
  233. code = response.get("code")
  234. match code:
  235. case 0:
  236. recent_articles = response['data']['data'][0]['AppMsg']['DetailInfo']
  237. article_url = await self.get_sample_url(recent_articles)
  238. print(article_url)
  239. if article_url:
  240. await self.set_sample_url(gh_id, article_url)
  241. task_id = self.generate_task_id(task_name="follow", gh_id=gh_id)
  242. affected_rows = await self.insert_aigc_follow_account_task(task_id, article_url)
  243. if affected_rows:
  244. await self.update_follow_status(gh_id, self.INIT_STATUS, self.PROCESSING_STATUS)
  245. case 25013:
  246. await self.set_account_as_invalid(gh_id)
  247. case _:
  248. pass
  249. async def follow_gzh_task(self):
  250. account_list = self.get_monitor_account_list()
  251. for account in account_list:
  252. try:
  253. fetch_response = await self.fetch_account_status(account.公众号名)
  254. if not fetch_response:
  255. print("账号不存在", account)
  256. # todo 没有 gh_id, 暂时无法存储账号
  257. # affected_rows =await self.insert_accounts_task(account.公众号名, account.ghid)
  258. # if affected_rows:
  259. # await self.create_follow_account_task(account.ghid)
  260. else:
  261. account_detail = fetch_response[0]
  262. status = account_detail["status"]
  263. follow_status = account_detail["follow_status"]
  264. if not status:
  265. print("账号已经迁移或者封禁")
  266. continue
  267. match follow_status:
  268. case self.INIT_STATUS:
  269. await self.create_follow_account_task(account_detail["gh_id"])
  270. case self.PROCESSING_STATUS:
  271. fetch_response = await self.fetch_follow_account_status(account_detail["gh_id"])
  272. if not fetch_response:
  273. await self.update_follow_status(account_detail["gh_id"], self.PROCESSING_STATUS, self.INIT_STATUS)
  274. task_status = fetch_response[0]["task_status"]
  275. match task_status:
  276. case self.FETCH_INIT_STATUS:
  277. continue
  278. case self.FETCH_PROCESSING_STATUS:
  279. continue
  280. case self.FETCH_SUCCESS_STATUS:
  281. await self.update_follow_status(account_detail["gh_id"], self.PROCESSING_STATUS, self.SUCCESS_STATUS)
  282. case self.FETCH_FAIL_STATUS:
  283. await self.update_follow_status(account_detail["gh_id"], self.PROCESSING_STATUS, self.FAIL_STATUS)
  284. case self.SUCCESS_STATUS:
  285. continue
  286. case _:
  287. print(f"{account.公众号名}账号状态异常")
  288. except Exception as e:
  289. print(f"处理账号{account.公众号名}异常", e)
  290. # main function
  291. async def deal(self, task_name):
  292. match task_name:
  293. case "follow_gzh_task":
  294. await self.follow_gzh_task()
  295. case _:
  296. print("task_error")