gzh_article_monitor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. from applications.utils import str_to_md5
  10. class MonitorConst:
  11. # 文章违规状态
  12. ILLEGAL_STATUS = 1
  13. INIT_STATUS = 0
  14. # 监测周期
  15. MONITOR_CYCLE = 3 * 24 * 3600
  16. # article code
  17. ARTICLE_ILLEGAL_CODE = 25012
  18. ARTICLE_DELETE_CODE = 25005
  19. ARTICLE_SUCCESS_CODE = 0
  20. ARTICLE_UNKNOWN_CODE = 10000
  21. # Task status
  22. TASK_SUCCESS_CODE = 2
  23. TASK_FAIL_CODE = 99
  24. class OutsideGzhArticlesManager(MonitorConst):
  25. def __init__(self, pool):
  26. self.pool = pool
  27. async def update_article_illegal_status(
  28. self, article_id: int, illegal_reason: str
  29. ) -> None:
  30. query = f"""
  31. update outside_gzh_account_monitor
  32. set illegal_status = %s, illegal_reason = %s
  33. where id = %s and illegal_status = %s
  34. """
  35. await self.pool.async_save(
  36. query=query,
  37. params=(self.ILLEGAL_STATUS, illegal_reason, article_id, self.INIT_STATUS),
  38. )
  39. async def whether_published_in_a_week(self, gh_id: str) -> bool:
  40. """
  41. 判断该账号一周内是否有发文,如有,则说无需抓
  42. """
  43. query = f"""
  44. select id, publish_timestamp from outside_gzh_account_monitor
  45. where gh_id = %s
  46. order by publish_timestamp desc
  47. limit %s;
  48. """
  49. response = await self.pool.async_fetch(query=query, params=(gh_id, 1))
  50. if response:
  51. publish_timestamp = response[0]["publish_timestamp"]
  52. if publish_timestamp is None:
  53. return False
  54. else:
  55. return int(time.time()) - publish_timestamp <= self.MONITOR_CYCLE
  56. else:
  57. return False
  58. class OutsideGzhArticlesCollector(OutsideGzhArticlesManager):
  59. async def fetch_outside_account_list(self):
  60. query = f"""
  61. select
  62. t2.group_source_name as account_source,
  63. t3.name as account_name,
  64. t3.gh_id as gh_id,
  65. t3.status as status
  66. from wx_statistics_group_source t1
  67. join wx_statistics_group_source_account t2 on t2.group_source_name = t1.account_source_name
  68. join publish_account t3 on t3.id = t2.account_id
  69. where
  70. t1.mode_type = '代运营服务号';
  71. """
  72. response = await self.pool.async_fetch(query=query, db_name="aigc")
  73. return response
  74. async def fetch_each_account(self, account: dict):
  75. gh_id = account["gh_id"]
  76. # 判断该账号本周是否已经发布过
  77. if await self.whether_published_in_a_week(gh_id):
  78. return
  79. fetch_response = await get_article_list_from_account(gh_id)
  80. try:
  81. msg_list = fetch_response.get("data", {}).get("data", [])
  82. if msg_list:
  83. for msg in tqdm(
  84. msg_list, desc=f"insert account {account['account_name']}"
  85. ):
  86. await self.save_each_msg_to_db(msg, account)
  87. else:
  88. print(f"crawler failed: {account['account_name']}")
  89. except Exception as e:
  90. print(
  91. f"crawler failed: account_name: {account['account_name']}\nerror: {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 = await 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 = 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 = await 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. await 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 whether_title_unsafe(self, title: str) -> bool:
  209. """
  210. :param title: gzh article title
  211. :return: bool
  212. """
  213. title_md5 = str_to_md5(title)
  214. query = f"""
  215. select title_md5 from article_unsafe_title where title_md5 = '{title_md5}';
  216. """
  217. response = await self.pool.async_fetch(query=query)
  218. return True if response else False
  219. async def fetch_article_list_to_check(self, run_date: str = None) -> Optional[List]:
  220. """
  221. :param run_date: 执行日期,格式为“%Y-%m-%d”, default None
  222. """
  223. if not run_date:
  224. run_date = datetime.datetime.today().strftime("%Y-%m-%d")
  225. run_timestamp = int(
  226. datetime.datetime.strptime(run_date, "%Y-%m-%d").timestamp()
  227. )
  228. start_timestamp = run_timestamp - self.MONITOR_CYCLE
  229. query = f"""
  230. select ghId, accountName, title, ContentUrl, wx_sn, from_unixtime(publish_timestamp) as publish_timestamp
  231. from official_articles_v2
  232. where publish_timestamp >= {start_timestamp}
  233. order by publish_timestamp desc;
  234. """
  235. response = await self.pool.async_fetch(query=query, db_name="piaoquan_crawler")
  236. if not response:
  237. await feishu_robot.bot(
  238. title="站内微信公众号发文监测任务异常",
  239. detail={"message": "查询数据库异常"},
  240. )
  241. return None
  242. else:
  243. return response
  244. async def check_each_article(self, article: dict):
  245. gh_id, account_name, title, url, wx_sn, publish_date = article
  246. try:
  247. response = await get_article_detail(url, is_cache=False)
  248. response_code = response["code"]
  249. if response_code == self.ARTICLE_ILLEGAL_CODE:
  250. error_detail = article.get("msg")
  251. query = f"""
  252. insert ignore into illegal_articles
  253. (gh_id, account_name, title, wx_sn, publish_date, illegal_reason)
  254. values
  255. (%s, %s, %s, %s, %s, %s);
  256. """
  257. affected_row = await self.pool.async_save(
  258. query=query,
  259. params=(
  260. gh_id,
  261. account_name,
  262. title,
  263. wx_sn,
  264. publish_date,
  265. error_detail,
  266. ),
  267. )
  268. if affected_row:
  269. if await self.whether_title_unsafe(title):
  270. return
  271. await feishu_robot.bot(
  272. title="文章违规告警",
  273. detail={
  274. "account_name": account_name,
  275. "gh_id": gh_id,
  276. "title": title,
  277. "wx_sn": wx_sn.decode("utf-8"),
  278. "publish_date": str(publish_date),
  279. "error_detail": error_detail,
  280. },
  281. mention=False,
  282. env="prod",
  283. )
  284. await delete_illegal_gzh_articles(gh_id, title)
  285. except Exception as e:
  286. print(f"crawler failed: {account_name}, error: {e}")
  287. async def deal(self):
  288. article_list = await self.fetch_article_list_to_check()
  289. for article in tqdm(article_list, desc="站内文章监测任务"):
  290. await self.check_each_article(article)
  291. return self.TASK_SUCCESS_CODE