gzh_article_monitor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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, error = 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, error = 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 = 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']}\n"
  92. f"error: {e}\n"
  93. )
  94. async def save_each_msg_to_db(self, msg: dict, account: dict):
  95. base_info = msg["AppMsg"]["BaseInfo"]
  96. detail_info = msg["AppMsg"]["DetailInfo"]
  97. app_msg_id = base_info["AppMsgId"]
  98. create_timestamp = base_info["CreateTime"]
  99. publish_type = base_info["Type"]
  100. # insert each article
  101. for article in detail_info:
  102. link = article["ContentUrl"]
  103. article_detail = get_article_detail(link)
  104. response_code = article_detail["code"]
  105. if response_code == self.ARTICLE_ILLEGAL_CODE:
  106. illegal_reason = article_detail.get("msg")
  107. # bot and return
  108. await feishu_robot.bot(
  109. title="文章违规告警",
  110. detail={
  111. "账号名称": article["account_name"],
  112. "标题": article["title"],
  113. "违规理由": illegal_reason,
  114. "发布日期": datetime.datetime.fromtimestamp(
  115. create_timestamp
  116. ).strftime("%Y-%m-%d %H:%M:%S"),
  117. "账号合作商": article["account_source"],
  118. },
  119. env="outside_gzh_monitor",
  120. mention=False,
  121. )
  122. elif response_code == self.ARTICLE_SUCCESS_CODE:
  123. insert_query = f"""
  124. insert ignore into outside_gzh_account_monitor
  125. (account_name, gh_id, account_source, account_type, app_msg_id, publish_type, position, title, link,
  126. channel_content_id, crawler_timestamp, publish_timestamp)
  127. values
  128. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  129. """
  130. await self.pool.async_save(
  131. query=insert_query,
  132. params=(
  133. account["account_name"],
  134. account["gh_id"],
  135. account["account_source"],
  136. "服务号",
  137. app_msg_id,
  138. publish_type,
  139. article["ItemIndex"],
  140. article["Title"],
  141. link,
  142. article_detail["data"]["data"]["channel_content_id"],
  143. int(time.time()),
  144. int(article_detail["data"]["data"]["publish_timestamp"] / 1000),
  145. ),
  146. )
  147. else:
  148. continue
  149. async def deal(self):
  150. account_list = await self.fetch_outside_account_list()
  151. for account in tqdm(account_list):
  152. try:
  153. await self.fetch_each_account(account)
  154. except Exception as e:
  155. print(f"crawler failed: {account['account_name']}, error: {e}")
  156. class OutsideGzhArticlesMonitor(OutsideGzhArticlesManager):
  157. async def fetch_article_list_to_check(self):
  158. publish_timestamp_threshold = int(time.time()) - self.MONITOR_CYCLE
  159. fetch_query = f"""
  160. select id, account_name, gh_id, account_source, account_type,
  161. title, link, from_unixtime(publish_timestamp) as publish_date
  162. from outside_gzh_account_monitor
  163. where illegal_status = {self.INIT_STATUS} and publish_timestamp > {publish_timestamp_threshold};
  164. """
  165. response, error = await self.pool.async_fetch(query=fetch_query)
  166. return response
  167. async def check_each_article(self, article: dict):
  168. """
  169. check each article
  170. """
  171. link = article["link"]
  172. article_detail = get_article_detail(link)
  173. response_code = article_detail["code"]
  174. if response_code == self.ARTICLE_ILLEGAL_CODE:
  175. illegal_reason = article_detail.get("msg")
  176. # illegal_reason = '测试报警功能'
  177. feishu_robot.bot(
  178. title="文章违规告警",
  179. detail={
  180. "账号名称": article["account_name"],
  181. "标题": article["title"],
  182. "违规理由": illegal_reason,
  183. "发布日期": str(article["publish_date"]),
  184. "账号合作商": article["account_source"],
  185. },
  186. env="outside_gzh_monitor",
  187. mention=False,
  188. )
  189. article_id = article["id"]
  190. await self.update_article_illegal_status(article_id, illegal_reason)
  191. else:
  192. return
  193. async def deal(self):
  194. article_list = await self.fetch_article_list_to_check()
  195. for article in tqdm(article_list, desc="外部服务号监控"):
  196. try:
  197. await self.check_each_article(article)
  198. except Exception as e:
  199. print(
  200. f"crawler failed: account_name: {article['account_name']}\n"
  201. f"link: {article['link']}\n"
  202. f"title: {article['title']}\n"
  203. f"error: {e}\n"
  204. )
  205. return self.TASK_SUCCESS_CODE
  206. class InnerGzhArticlesMonitor(MonitorConst):
  207. def __init__(self, pool):
  208. self.pool = pool
  209. async def whether_title_unsafe(self, title: str) -> bool:
  210. """
  211. :param title: gzh article title
  212. :return: bool
  213. """
  214. title_md5 = str_to_md5(title)
  215. query = f"""
  216. select title_md5 from article_unsafe_title where title_md5 = '{title_md5}';
  217. """
  218. response, error = await self.pool.async_fetch(query=query)
  219. return True if response else False
  220. async def fetch_article_list_to_check(self, run_date: str = None) -> Optional[List]:
  221. """
  222. :param run_date: 执行日期,格式为“%Y-%m-%d”, default None
  223. """
  224. if not run_date:
  225. run_date = datetime.datetime.today().strftime("%Y-%m-%d")
  226. run_timestamp = int(
  227. datetime.datetime.strptime(run_date, "%Y-%m-%d").timestamp()
  228. )
  229. start_timestamp = run_timestamp - self.MONITOR_CYCLE
  230. query = f"""
  231. select ghId, accountName, title, ContentUrl, wx_sn, from_unixtime(publish_timestamp) as publish_timestamp
  232. from official_articles_v2
  233. where publish_timestamp >= {start_timestamp}
  234. order by publish_timestamp desc;
  235. """
  236. response, error = await self.pool.async_fetch(
  237. query=query, db_name="piaoquan_crawler"
  238. )
  239. if error:
  240. await feishu_robot.bot(
  241. title="站内微信公众号发文监测任务异常",
  242. detail={"error": error, "message": "查询数据库异常"},
  243. )
  244. return None
  245. else:
  246. return response
  247. async def check_each_article(self, article: dict):
  248. gh_id, account_name, title, url, wx_sn, publish_date = article
  249. try:
  250. response = get_article_detail(url, is_cache=False)
  251. response_code = response["code"]
  252. if response_code == self.ARTICLE_ILLEGAL_CODE:
  253. error_detail = article.get("msg")
  254. query = f"""
  255. insert ignore into illegal_articles
  256. (gh_id, account_name, title, wx_sn, publish_date, illegal_reason)
  257. values
  258. (%s, %s, %s, %s, %s, %s);
  259. """
  260. affected_row = await self.pool.async_save(
  261. query=query,
  262. params=(
  263. gh_id,
  264. account_name,
  265. title,
  266. wx_sn,
  267. publish_date,
  268. error_detail,
  269. ),
  270. )
  271. if affected_row:
  272. if await self.whether_title_unsafe(title):
  273. return
  274. await feishu_robot.bot(
  275. title="文章违规告警",
  276. detail={
  277. "account_name": account_name,
  278. "gh_id": gh_id,
  279. "title": title,
  280. "wx_sn": wx_sn.decode("utf-8"),
  281. "publish_date": str(publish_date),
  282. "error_detail": error_detail,
  283. },
  284. mention=False,
  285. env="prod",
  286. )
  287. await delete_illegal_gzh_articles(gh_id, title)
  288. except Exception as e:
  289. print(f"crawler failed: {account_name}, error: {e}")
  290. async def deal(self):
  291. article_list = await self.fetch_article_list_to_check()
  292. for article in tqdm(article_list, desc="站内文章监测任务"):
  293. await self.check_each_article(article)
  294. return self.TASK_SUCCESS_CODE