auto_reply_cards_monitor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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(query=query, params=(account_name,))
  183. # 更新账号状态为无效
  184. async def set_account_as_invalid(self, gh_id):
  185. query = """
  186. UPDATE cooperate_accounts SET status = %s WHERE gh_id = %s;
  187. """
  188. await self.pool.async_save(query=query, params=(self.INVALID_STATUS, gh_id))
  189. # 插入AIGC关注公众号任务
  190. async def insert_aigc_follow_account_task(self, task_id, link):
  191. timestamp = int(time.time() * 1000)
  192. query = """
  193. INSERT INTO gzh_msg_record (task_id, biz_type, task_params, create_timestamp, update_timestamp) VALUES (%s, %s, %s, %s, %s);
  194. """
  195. return await self.pool.async_save(
  196. query=query,
  197. params=(task_id, "follow", link, timestamp, timestamp),
  198. db_name="aigc",
  199. )
  200. # 插入AIGC自动回复任务
  201. async def insert_aigc_auto_reply_task(self, task_id, account_name):
  202. timestamp = int(time.time() * 1000)
  203. query = """
  204. INSERT INTO gzh_msg_record (task_id, task_params, create_timestamp, update_timestamp) VALUES (%s, %s, %s, %s);
  205. """
  206. return await self.pool.async_save(
  207. query=query,
  208. params=(task_id, account_name, timestamp, timestamp),
  209. db_name="aigc",
  210. )
  211. # 为账号设置 sample_url
  212. async def set_sample_url(self, gh_id, sample_url):
  213. query = """
  214. UPDATE cooperate_accounts SET sample_link = %s WHERE gh_id = %s;
  215. """
  216. return await self.pool.async_save(query=query, params=(sample_url, gh_id))
  217. # 修改账号的关注状态
  218. async def update_follow_status(self, gh_id, ori_status, new_status):
  219. query = """
  220. UPDATE cooperate_accounts SET follow_status = %s WHERE gh_id = %s and follow_status = %s;
  221. """
  222. return await self.pool.async_save(
  223. query=query, params=(new_status, gh_id, ori_status)
  224. )
  225. # 从 aigc 获取关注结果
  226. async def fetch_follow_account_status(self, gh_id):
  227. query = """
  228. SELECT task_status, err_msg
  229. FROM gzh_msg_record
  230. WHERE task_id = %s;
  231. """
  232. return await self.pool.async_fetch(
  233. query=query, params=(f"follow_{gh_id}",), db_name="aigc"
  234. )
  235. class AutoReplyCardsMonitor(AutoReplyCardsMonitorMapper):
  236. def __init__(self, pool, log_client):
  237. super().__init__(pool, log_client)
  238. # 创建单个关注公众号任务
  239. async def create_follow_account_task(self, gh_id):
  240. response = await get_article_list_from_account(account_id=gh_id)
  241. code = response.get("code")
  242. match code:
  243. case 0:
  244. recent_articles = response["data"]["data"][0]["AppMsg"]["DetailInfo"]
  245. article_url = await self.get_sample_url(recent_articles)
  246. print(article_url)
  247. if article_url:
  248. await self.set_sample_url(gh_id, article_url)
  249. task_id = self.generate_task_id(task_name="follow", gh_id=gh_id)
  250. affected_rows = await self.insert_aigc_follow_account_task(
  251. task_id, article_url
  252. )
  253. if affected_rows:
  254. await self.update_follow_status(
  255. gh_id, self.INIT_STATUS, self.PROCESSING_STATUS
  256. )
  257. case 25013:
  258. await self.set_account_as_invalid(gh_id)
  259. case _:
  260. pass
  261. async def follow_gzh_task(self):
  262. account_list = self.get_monitor_account_list()
  263. for account in account_list:
  264. try:
  265. fetch_response = await self.fetch_account_status(account.公众号名)
  266. if not fetch_response:
  267. print("账号不存在", account)
  268. # todo 没有 gh_id, 暂时无法存储账号
  269. # affected_rows =await self.insert_accounts_task(account.公众号名, account.ghid)
  270. # if affected_rows:
  271. # await self.create_follow_account_task(account.ghid)
  272. else:
  273. account_detail = fetch_response[0]
  274. status = account_detail["status"]
  275. follow_status = account_detail["follow_status"]
  276. if not status:
  277. print("账号已经迁移或者封禁")
  278. continue
  279. match follow_status:
  280. case self.INIT_STATUS:
  281. await self.create_follow_account_task(
  282. account_detail["gh_id"]
  283. )
  284. case self.PROCESSING_STATUS:
  285. fetch_response = await self.fetch_follow_account_status(
  286. account_detail["gh_id"]
  287. )
  288. if not fetch_response:
  289. await self.update_follow_status(
  290. account_detail["gh_id"],
  291. self.PROCESSING_STATUS,
  292. self.INIT_STATUS,
  293. )
  294. task_status = fetch_response[0]["task_status"]
  295. match task_status:
  296. case self.FETCH_INIT_STATUS:
  297. continue
  298. case self.FETCH_PROCESSING_STATUS:
  299. continue
  300. case self.FETCH_SUCCESS_STATUS:
  301. await self.update_follow_status(
  302. account_detail["gh_id"],
  303. self.PROCESSING_STATUS,
  304. self.SUCCESS_STATUS,
  305. )
  306. case self.FETCH_FAIL_STATUS:
  307. await self.update_follow_status(
  308. account_detail["gh_id"],
  309. self.PROCESSING_STATUS,
  310. self.FAIL_STATUS,
  311. )
  312. case self.SUCCESS_STATUS:
  313. continue
  314. case _:
  315. print(f"{account.公众号名}账号状态异常")
  316. except Exception as e:
  317. print(f"处理账号{account.公众号名}异常", e)
  318. # main function
  319. async def deal(self, task_name):
  320. match task_name:
  321. case "follow_gzh_task":
  322. await self.follow_gzh_task()
  323. case _:
  324. print("task_error")