gzh_article_monitor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import time
  2. import datetime
  3. from typing import Optional, List
  4. from tqdm import tqdm
  5. from applications.api import feishu_robot
  6. from applications.api import delete_illegal_gzh_articles
  7. from applications.crawler.wechat import get_article_detail
  8. from applications.crawler.wechat import get_article_list_from_account
  9. class MonitorConst:
  10. # 文章违规状态
  11. ILLEGAL_STATUS = 1
  12. INIT_STATUS = 0
  13. # 监测周期
  14. MONITOR_CYCLE = 3 * 24 * 3600
  15. # article code
  16. ARTICLE_ILLEGAL_CODE = 25012
  17. ARTICLE_DELETE_CODE = 25005
  18. ARTICLE_SUCCESS_CODE = 0
  19. ARTICLE_UNKNOWN_CODE = 10000
  20. # Task status
  21. TASK_SUCCESS_CODE = 2
  22. TASK_FAIL_CODE = 99
  23. class OutsideGzhArticlesManager(MonitorConst):
  24. def __init__(self, pool):
  25. self.pool = pool
  26. async def update_article_illegal_status(
  27. self, article_id: int, illegal_reason: str
  28. ) -> None:
  29. query = f"""
  30. update outside_gzh_account_monitor
  31. set illegal_status = %s, illegal_reason = %s
  32. where id = %s and illegal_status = %s
  33. """
  34. await self.pool.async_save(
  35. query=query,
  36. params=(self.ILLEGAL_STATUS, illegal_reason, article_id, self.INIT_STATUS),
  37. )
  38. async def whether_published_in_a_week(self, gh_id: str) -> bool:
  39. """
  40. 判断该账号一周内是否有发文,如有,则说无需抓
  41. """
  42. query = f"""
  43. select id, publish_timestamp from outside_gzh_account_monitor
  44. where gh_id = %s
  45. order by publish_timestamp desc
  46. limit %s;
  47. """
  48. response, error = await self.pool.async_fetch(query=query, params=(gh_id, 1))
  49. if response:
  50. publish_timestamp = response[0]["publish_timestamp"]
  51. if publish_timestamp is None:
  52. return False
  53. else:
  54. return int(time.time()) - publish_timestamp <= self.MONITOR_CYCLE
  55. else:
  56. return False
  57. class OutsideGzhArticlesCollector(OutsideGzhArticlesManager):
  58. async def fetch_outside_account_list(self):
  59. query = f"""
  60. select
  61. t2.group_source_name as account_source,
  62. t3.name as account_name,
  63. t3.gh_id as gh_id,
  64. t3.status as status
  65. from wx_statistics_group_source t1
  66. join wx_statistics_group_source_account t2 on t2.group_source_name = t1.account_source_name
  67. join publish_account t3 on t3.id = t2.account_id
  68. where
  69. t1.mode_type = '代运营服务号';
  70. """
  71. response, error = await self.pool.async_fetch(query=query, db_name="aigc")
  72. return response
  73. async def fetch_each_account(self, account: dict):
  74. gh_id = account["gh_id"]
  75. # 判断该账号本周是否已经发布过
  76. if await self.whether_published_in_a_week(gh_id):
  77. return
  78. fetch_response = get_article_list_from_account(gh_id)
  79. try:
  80. msg_list = fetch_response.get("data", {}).get("data", [])
  81. if msg_list:
  82. for msg in tqdm(
  83. msg_list, desc=f"insert account {account['account_name']}"
  84. ):
  85. await self.save_each_msg_to_db(msg, account)
  86. else:
  87. print(f"crawler failed: {account['account_name']}")
  88. except Exception as e:
  89. print(
  90. f"crawler failed: account_name: {account['account_name']}\n"
  91. f"error: {e}\n"
  92. )
  93. async def save_each_msg_to_db(self, msg: dict, account: dict):
  94. base_info = msg["AppMsg"]["BaseInfo"]
  95. detail_info = msg["AppMsg"]["DetailInfo"]
  96. app_msg_id = base_info["AppMsgId"]
  97. create_timestamp = base_info["CreateTime"]
  98. publish_type = base_info["Type"]
  99. # insert each article
  100. for article in detail_info:
  101. link = article["ContentUrl"]
  102. article_detail = get_article_detail(link)
  103. response_code = article_detail["code"]
  104. if response_code == self.ARTICLE_ILLEGAL_CODE:
  105. illegal_reason = article_detail.get("msg")
  106. # bot and return
  107. await feishu_robot.bot(
  108. title="文章违规告警",
  109. detail={
  110. "账号名称": article["account_name"],
  111. "标题": article["title"],
  112. "违规理由": illegal_reason,
  113. "发布日期": datetime.datetime.fromtimestamp(
  114. create_timestamp
  115. ).strftime("%Y-%m-%d %H:%M:%S"),
  116. "账号合作商": article["account_source"],
  117. },
  118. env="outside_gzh_monitor",
  119. mention=False,
  120. )
  121. elif response_code == self.ARTICLE_SUCCESS_CODE:
  122. insert_query = f"""
  123. insert ignore into outside_gzh_account_monitor
  124. (account_name, gh_id, account_source, account_type, app_msg_id, publish_type, position, title, link,
  125. channel_content_id, crawler_timestamp, publish_timestamp)
  126. values
  127. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  128. """
  129. await self.pool.async_save(
  130. query=insert_query,
  131. params=(
  132. account["account_name"],
  133. account["gh_id"],
  134. account["account_source"],
  135. "服务号",
  136. app_msg_id,
  137. publish_type,
  138. article["ItemIndex"],
  139. article["Title"],
  140. link,
  141. article_detail["data"]["data"]["channel_content_id"],
  142. int(time.time()),
  143. int(article_detail["data"]["data"]["publish_timestamp"] / 1000),
  144. ),
  145. )
  146. else:
  147. continue
  148. async def deal(self):
  149. account_list = await self.fetch_outside_account_list()
  150. for account in tqdm(account_list):
  151. try:
  152. await self.fetch_each_account(account)
  153. except Exception as e:
  154. print(f"crawler failed: {account['account_name']}, error: {e}")
  155. class OutsideGzhArticlesMonitor(OutsideGzhArticlesManager):
  156. async def fetch_article_list_to_check(self):
  157. publish_timestamp_threshold = int(time.time()) - self.MONITOR_CYCLE
  158. fetch_query = f"""
  159. select id, account_name, gh_id, account_source, account_type,
  160. title, link, from_unixtime(publish_timestamp) as publish_date
  161. from outside_gzh_account_monitor
  162. where illegal_status = {self.INIT_STATUS} and publish_timestamp > {publish_timestamp_threshold};
  163. """
  164. response, error = await self.pool.async_fetch(query=fetch_query)
  165. return response
  166. async def check_each_article(self, article: dict):
  167. """
  168. check each article
  169. """
  170. link = article["link"]
  171. article_detail = get_article_detail(link)
  172. response_code = article_detail["code"]
  173. if response_code == self.ARTICLE_ILLEGAL_CODE:
  174. illegal_reason = article_detail.get("msg")
  175. # illegal_reason = '测试报警功能'
  176. feishu_robot.bot(
  177. title="文章违规告警",
  178. detail={
  179. "账号名称": article["account_name"],
  180. "标题": article["title"],
  181. "违规理由": illegal_reason,
  182. "发布日期": str(article["publish_date"]),
  183. "账号合作商": article["account_source"],
  184. },
  185. env="outside_gzh_monitor",
  186. mention=False,
  187. )
  188. article_id = article["id"]
  189. await self.update_article_illegal_status(article_id, illegal_reason)
  190. else:
  191. return
  192. async def deal(self):
  193. article_list = await self.fetch_article_list_to_check()
  194. for article in tqdm(article_list, desc="外部服务号监控"):
  195. try:
  196. await self.check_each_article(article)
  197. except Exception as e:
  198. print(
  199. f"crawler failed: account_name: {article['account_name']}\n"
  200. f"link: {article['link']}\n"
  201. f"title: {article['title']}\n"
  202. f"error: {e}\n"
  203. )
  204. return self.TASK_SUCCESS_CODE
  205. class InnerGzhArticlesMonitor(MonitorConst):
  206. def __init__(self, pool):
  207. self.pool = pool
  208. async def fetch_article_list_to_check(self, run_date: str = None) -> Optional[List]:
  209. """
  210. :param run_date: 执行日期,格式为“%Y-%m-%d”, default None
  211. """
  212. if not run_date:
  213. run_date = datetime.datetime.today().strftime("%Y-%m-%d")
  214. run_timestamp = int(
  215. datetime.datetime.strptime(run_date, "%Y-%m-%d").timestamp()
  216. )
  217. start_timestamp = run_timestamp - self.MONITOR_CYCLE
  218. query = f"""
  219. select ghId, accountName, title, ContentUrl, wx_sn, from_unixtime(publish_timestamp) as publish_timestamp
  220. from official_articles_v2
  221. where publish_timestamp >= {start_timestamp}
  222. order by publish_timestamp desc;
  223. """
  224. response, error = await self.pool.async_fetch(
  225. query=query, db_name="piaoquan_crawler"
  226. )
  227. if error:
  228. await feishu_robot.bot(
  229. title="站内微信公众号发文监测任务异常",
  230. detail={"error": error, "message": "查询数据库异常"},
  231. )
  232. return None
  233. else:
  234. return response
  235. async def check_each_article(self, article: dict):
  236. gh_id, account_name, title, url, wx_sn, publish_date = article
  237. try:
  238. response = get_article_detail(url, is_cache=False)
  239. response_code = response["code"]
  240. if response_code == self.ARTICLE_ILLEGAL_CODE:
  241. error_detail = article.get("msg")
  242. query = f"""
  243. insert ignore into illegal_articles
  244. (gh_id, account_name, title, wx_sn, publish_date, illegal_reason)
  245. values
  246. (%s, %s, %s, %s, %s, %s);
  247. """
  248. affected_row = await self.pool.async_save(
  249. query=query,
  250. params=(
  251. gh_id,
  252. account_name,
  253. title,
  254. wx_sn,
  255. publish_date,
  256. error_detail,
  257. ),
  258. )
  259. if affected_row:
  260. await feishu_robot.bot(
  261. title="文章违规告警",
  262. detail={
  263. "account_name": account_name,
  264. "gh_id": gh_id,
  265. "title": title,
  266. "wx_sn": wx_sn.decode("utf-8"),
  267. "publish_date": str(publish_date),
  268. "error_detail": error_detail,
  269. },
  270. mention=False,
  271. env="prod"
  272. )
  273. await delete_illegal_gzh_articles(gh_id, title)
  274. except Exception as e:
  275. print(f"crawler failed: {article['account_name']}, error: {e}")
  276. async def deal(self):
  277. article_list = await self.fetch_article_list_to_check()
  278. for article in tqdm(article_list, desc="站内文章监测任务"):
  279. await self.check_each_article(article)
  280. return self.TASK_SUCCESS_CODE