updatePublishedMsgDaily.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. """
  2. @author: luojunhui
  3. @description: update daily information into official articles v2
  4. """
  5. import json
  6. import time
  7. import traceback
  8. import urllib.parse
  9. from argparse import ArgumentParser
  10. from datetime import datetime
  11. from typing import Dict, List, Tuple
  12. from pymysql.cursors import DictCursor
  13. from tqdm import tqdm
  14. from applications import aiditApi
  15. from applications import bot
  16. from applications import create_feishu_columns_sheet
  17. from applications import Functions
  18. from applications import log
  19. from applications import WeixinSpider
  20. from applications.const import updatePublishedMsgTaskConst
  21. from applications.db import DatabaseConnector
  22. from config import denet_config, long_articles_config, piaoquan_crawler_config
  23. ARTICLE_TABLE = "official_articles_v2"
  24. const = updatePublishedMsgTaskConst()
  25. spider = WeixinSpider()
  26. functions = Functions()
  27. def generate_bot_columns():
  28. """
  29. 生成列
  30. :return:
  31. """
  32. columns = [
  33. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="name", display_name="公众号名称"),
  34. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="ghId", display_name="ghId"),
  35. create_feishu_columns_sheet(sheet_type="number", sheet_name="follower_count", display_name="粉丝数"),
  36. create_feishu_columns_sheet(sheet_type="date", sheet_name="account_init_timestamp",
  37. display_name="账号接入系统时间"),
  38. create_feishu_columns_sheet(sheet_type="plain_text", sheet_name="using_status", display_name="利用状态")
  39. ]
  40. return columns
  41. def get_account_status(db_client: DatabaseConnector) -> Dict:
  42. """
  43. 获取账号的实验状态
  44. :return:
  45. """
  46. sql = f"""
  47. SELECT t1.account_id, t2.status
  48. FROM wx_statistics_group_source_account t1
  49. JOIN wx_statistics_group_source t2
  50. ON t1.group_source_name = t2.account_source_name;
  51. """
  52. account_status_list = db_client.fetch(sql, cursor_type=DictCursor)
  53. account_status_dict = {account['account_id']: account['status'] for account in account_status_list}
  54. return account_status_dict
  55. def get_accounts(db_client: DatabaseConnector) -> List[Dict]:
  56. """
  57. 从 aigc 数据库中获取目前处于发布状态的账号
  58. :return:
  59. "name": line[0],
  60. "ghId": line[1],
  61. "follower_count": line[2],
  62. "account_init_time": int(line[3] / 1000),
  63. "account_type": line[4], # 订阅号 or 服务号
  64. "account_auth": line[5]
  65. """
  66. account_list_with_out_using_status = aiditApi.get_publish_account_from_aigc()
  67. account_status_dict = get_account_status(db_client)
  68. account_list = [
  69. {
  70. **item,
  71. 'using_status': 0 if account_status_dict.get(item['account_id']) == '实验' else 1
  72. }
  73. for item in account_list_with_out_using_status
  74. ]
  75. return account_list
  76. def insert_each_msg(db_client: DatabaseConnector, account_info: Dict, msg_list: List[Dict]) -> None:
  77. """
  78. 把消息数据更新到数据库中
  79. :param account_info:
  80. :param db_client:
  81. :param msg_list:
  82. :return:
  83. """
  84. gh_id = account_info['ghId']
  85. account_name = account_info['name']
  86. for info in msg_list:
  87. baseInfo = info.get("BaseInfo", {})
  88. appMsgId = info.get("AppMsg", {}).get("BaseInfo", {}).get("AppMsgId", None)
  89. createTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("CreateTime", None)
  90. updateTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("UpdateTime", None)
  91. Type = info.get("AppMsg", {}).get("BaseInfo", {}).get("Type", None)
  92. detail_article_list = info.get("AppMsg", {}).get("DetailInfo", [])
  93. if detail_article_list:
  94. for article in detail_article_list:
  95. title = article.get("Title", None)
  96. Digest = article.get("Digest", None)
  97. ItemIndex = article.get("ItemIndex", None)
  98. ContentUrl = article.get("ContentUrl", None)
  99. SourceUrl = article.get("SourceUrl", None)
  100. CoverImgUrl = article.get("CoverImgUrl", None)
  101. CoverImgUrl_1_1 = article.get("CoverImgUrl_1_1", None)
  102. CoverImgUrl_235_1 = article.get("CoverImgUrl_235_1", None)
  103. ItemShowType = article.get("ItemShowType", None)
  104. IsOriginal = article.get("IsOriginal", None)
  105. ShowDesc = article.get("ShowDesc", None)
  106. show_stat = functions.show_desc_to_sta(ShowDesc)
  107. ori_content = article.get("ori_content", None)
  108. show_view_count = show_stat.get("show_view_count", 0)
  109. show_like_count = show_stat.get("show_like_count", 0)
  110. show_zs_count = show_stat.get("show_zs_count", 0)
  111. show_pay_count = show_stat.get("show_pay_count", 0)
  112. wx_sn = ContentUrl.split("&sn=")[1].split("&")[0] if ContentUrl else None
  113. status = account_info['using_status']
  114. info_tuple = (
  115. gh_id,
  116. account_name,
  117. appMsgId,
  118. title,
  119. Type,
  120. createTime,
  121. updateTime,
  122. Digest,
  123. ItemIndex,
  124. ContentUrl,
  125. SourceUrl,
  126. CoverImgUrl,
  127. CoverImgUrl_1_1,
  128. CoverImgUrl_235_1,
  129. ItemShowType,
  130. IsOriginal,
  131. ShowDesc,
  132. ori_content,
  133. show_view_count,
  134. show_like_count,
  135. show_zs_count,
  136. show_pay_count,
  137. wx_sn,
  138. json.dumps(baseInfo, ensure_ascii=False),
  139. functions.str_to_md5(title),
  140. status
  141. )
  142. try:
  143. insert_sql = f"""
  144. INSERT INTO {ARTICLE_TABLE}
  145. (ghId, accountName, appMsgId, title, Type, createTime, updateTime, Digest, ItemIndex, ContentUrl, SourceUrl, CoverImgUrl, CoverImgUrl_1_1, CoverImgUrl_255_1, ItemShowType, IsOriginal, ShowDesc, ori_content, show_view_count, show_like_count, show_zs_count, show_pay_count, wx_sn, baseInfo, title_md5, status)
  146. values
  147. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  148. """
  149. db_client.save(query=insert_sql, params=info_tuple)
  150. log(
  151. task="updatePublishedMsgDaily",
  152. function="insert_each_msg",
  153. message="插入文章数据成功",
  154. data={
  155. "info": info_tuple
  156. }
  157. )
  158. except Exception as e:
  159. try:
  160. update_sql = f"""
  161. UPDATE {ARTICLE_TABLE}
  162. SET show_view_count = %s, show_like_count=%s
  163. WHERE wx_sn = %s;
  164. """
  165. db_client.save(query=update_sql,
  166. params=(show_view_count, show_like_count, wx_sn))
  167. log(
  168. task="updatePublishedMsgDaily",
  169. function="insert_each_msg",
  170. message="更新文章数据成功",
  171. data={
  172. "wxSn": wx_sn,
  173. "likeCount": show_like_count,
  174. "viewCount": show_view_count
  175. }
  176. )
  177. except Exception as e:
  178. log(
  179. task="updatePublishedMsgDaily",
  180. function="insert_each_msg",
  181. message="更新文章失败, 报错原因是: {}".format(e),
  182. status="fail"
  183. )
  184. continue
  185. def update_each_account(db_client: DatabaseConnector, account_info: Dict, latest_update_time: int, cursor=None):
  186. """
  187. 更新每一个账号信息
  188. :param account_info:
  189. :param cursor:
  190. :param latest_update_time: 最新更新时间
  191. :param db_client: 数据库连接信息
  192. :return: None
  193. """
  194. gh_id = account_info['ghId']
  195. response = spider.update_msg_list(ghId=gh_id, index=cursor)
  196. msg_list = response.get("data", {}).get("data", [])
  197. if msg_list:
  198. # do
  199. last_article_in_this_msg = msg_list[-1]
  200. last_time_stamp_in_this_msg = last_article_in_this_msg['AppMsg']['BaseInfo']['UpdateTime']
  201. last_url = last_article_in_this_msg['AppMsg']['DetailInfo'][0]['ContentUrl']
  202. resdata = spider.get_account_by_url(last_url)
  203. check_id = resdata['data'].get('data', {}).get('wx_gh')
  204. if check_id == gh_id:
  205. insert_each_msg(
  206. db_client=db_client,
  207. account_info=account_info,
  208. msg_list=msg_list
  209. )
  210. if last_time_stamp_in_this_msg > latest_update_time:
  211. next_cursor = response['data']['next_cursor']
  212. return update_each_account(
  213. db_client=db_client,
  214. account_info=account_info,
  215. latest_update_time=latest_update_time,
  216. cursor=next_cursor
  217. )
  218. log(
  219. task="updatePublishedMsgDaily",
  220. function="update_each_account",
  221. message="账号文章更新成功",
  222. data=response
  223. )
  224. else:
  225. log(
  226. task="updatePublishedMsgDaily",
  227. function="update_each_account",
  228. message="账号文章更新失败",
  229. status="fail",
  230. data=response
  231. )
  232. return
  233. def check_account_info(db_client: DatabaseConnector, gh_id: str) -> int:
  234. """
  235. 通过 gh_id查询账号信息的最新发布时间
  236. :param db_client:
  237. :param gh_id:
  238. :return:
  239. """
  240. sql = f"""
  241. SELECT MAX(publish_timestamp)
  242. FROM {ARTICLE_TABLE}
  243. WHERE ghId = '{gh_id}';
  244. """
  245. result = db_client.fetch(sql)
  246. if result:
  247. return result[0][0]
  248. else:
  249. # 新号,抓取周期定位抓取时刻往前推30天
  250. return int(time.time()) - const.NEW_ACCOUNT_CRAWL_PERIOD
  251. def update_single_account(db_client: DatabaseConnector, account_info: Dict):
  252. """
  253. 更新单个账号
  254. :param db_client:
  255. :param account_info:
  256. :return:
  257. """
  258. gh_id = account_info['ghId']
  259. max_publish_time = check_account_info(db_client, gh_id)
  260. update_each_account(
  261. db_client=db_client,
  262. account_info=account_info,
  263. latest_update_time=max_publish_time
  264. )
  265. def check_single_account(db_client: DatabaseConnector, account_item: Dict) -> bool:
  266. """
  267. 校验每个账号是否更新
  268. :param db_client:
  269. :param account_item:
  270. :return: True / False
  271. """
  272. gh_id = account_item['ghId']
  273. account_type = account_item['account_type']
  274. today_str = datetime.today().strftime("%Y-%m-%d")
  275. today_date_time = datetime.strptime(today_str, "%Y-%m-%d")
  276. today_timestamp = today_date_time.timestamp()
  277. sql = f"""
  278. SELECT max(updateTime)
  279. FROM {ARTICLE_TABLE}
  280. WHERE ghId = '{gh_id}';
  281. """
  282. try:
  283. latest_update_time = db_client.fetch(sql)[0][0]
  284. # 判断该账号当天发布的文章是否被收集
  285. if account_type in const.SUBSCRIBE_TYPE_SET:
  286. if int(latest_update_time) > int(today_timestamp):
  287. return True
  288. else:
  289. return False
  290. else:
  291. if int(latest_update_time) > int(today_timestamp) - 7 * 24 * 3600:
  292. return True
  293. else:
  294. return False
  295. except Exception as e:
  296. print(e)
  297. return False
  298. def get_articles(db_client: DatabaseConnector):
  299. """
  300. :return:
  301. """
  302. sql = f"""
  303. SELECT ContentUrl, wx_sn
  304. FROM {ARTICLE_TABLE}
  305. WHERE publish_timestamp in {(const.DEFAULT_STATUS, const.REQUEST_FAIL_STATUS)};"""
  306. response = db_client.fetch(sql)
  307. return response
  308. def update_publish_timestamp(db_client: DatabaseConnector, row: Tuple):
  309. """
  310. 更新发布时间戳 && minigram 信息
  311. :param db_client:
  312. :param row:
  313. :return:
  314. """
  315. url = row[0]
  316. wx_sn = row[1]
  317. try:
  318. response = spider.get_article_text(url)
  319. response_code = response['code']
  320. if response_code == const.ARTICLE_DELETE_CODE:
  321. publish_timestamp_s = const.DELETE_STATUS
  322. root_source_id_list = []
  323. elif response_code == const.ARTICLE_ILLEGAL_CODE:
  324. publish_timestamp_s = const.ILLEGAL_STATUS
  325. root_source_id_list = []
  326. elif response_code == const.ARTICLE_SUCCESS_CODE:
  327. data = response['data']['data']
  328. publish_timestamp_ms = data['publish_timestamp']
  329. publish_timestamp_s = int(publish_timestamp_ms / 1000)
  330. mini_program = data.get('mini_program', [])
  331. if mini_program:
  332. root_source_id_list = [
  333. urllib.parse.parse_qs(
  334. urllib.parse.unquote(i['path'])
  335. )['rootSourceId'][0]
  336. for i in mini_program
  337. ]
  338. else:
  339. root_source_id_list = []
  340. else:
  341. publish_timestamp_s = const.UNKNOWN_STATUS
  342. root_source_id_list = []
  343. except Exception as e:
  344. publish_timestamp_s = const.REQUEST_FAIL_STATUS
  345. root_source_id_list = None
  346. error_msg = traceback.format_exc()
  347. print(e, error_msg)
  348. update_sql = f"""
  349. UPDATE {ARTICLE_TABLE}
  350. SET publish_timestamp = %s, root_source_id_list = %s
  351. WHERE wx_sn = %s;
  352. """
  353. db_client.save(
  354. query=update_sql,
  355. params=(
  356. publish_timestamp_s,
  357. json.dumps(root_source_id_list, ensure_ascii=False),
  358. wx_sn
  359. ))
  360. if publish_timestamp_s == const.REQUEST_FAIL_STATUS:
  361. return row
  362. else:
  363. return None
  364. def get_article_detail_job(db_client: DatabaseConnector):
  365. """
  366. 获取发布文章详情
  367. :return:
  368. """
  369. article_tuple = get_articles(db_client)
  370. for article in tqdm(article_tuple):
  371. try:
  372. update_publish_timestamp(db_client=db_client, row=article)
  373. except Exception as e:
  374. print(e)
  375. error_msg = traceback.format_exc()
  376. print(error_msg)
  377. # check 一遍存在请求失败-1 && 0 的文章
  378. process_failed_articles = get_articles(db_client)
  379. fail_list = []
  380. if process_failed_articles:
  381. for article in tqdm(process_failed_articles):
  382. try:
  383. res = update_publish_timestamp(db_client=db_client, row=article)
  384. fail_list.append({"wx_sn": res[1], "url": res[0]})
  385. except Exception as e:
  386. print(e)
  387. error_msg = traceback.format_exc()
  388. print(error_msg)
  389. # 通过msgId 来修改publish_timestamp
  390. update_sql = f"""
  391. UPDATE {ARTICLE_TABLE} oav
  392. JOIN (
  393. SELECT ghId, appMsgId, MAX(publish_timestamp) AS publish_timestamp
  394. FROM {ARTICLE_TABLE}
  395. WHERE publish_timestamp > %s
  396. GROUP BY ghId, appMsgId
  397. ) vv
  398. ON oav.appMsgId = vv.appMsgId AND oav.ghId = vv.ghId
  399. SET oav.publish_timestamp = vv.publish_timestamp
  400. WHERE oav.publish_timestamp <= %s;
  401. """
  402. db_client.save(
  403. query=update_sql,
  404. params=(0, 0)
  405. )
  406. # 若还是无 publish_timestamp,用update_time当作 publish_timestamp
  407. update_sql_2 = f"""
  408. UPDATE {ARTICLE_TABLE}
  409. SET publish_timestamp = updateTime
  410. WHERE publish_timestamp < %s;
  411. """
  412. db_client.save(
  413. query=update_sql_2,
  414. params=0
  415. )
  416. if fail_list:
  417. bot(
  418. title="更新文章任务,请求detail失败",
  419. detail=fail_list
  420. )
  421. def whether_title_unsafe(db_client: DatabaseConnector, title: str):
  422. """
  423. 检查文章标题是否已经存在违规记录
  424. :param db_client:
  425. :param title:
  426. :return:
  427. """
  428. title_md5 = functions.str_to_md5(title)
  429. sql = f"""
  430. SELECT title_md5
  431. FROM article_unsafe_title
  432. WHERE title_md5 = '{title_md5}';
  433. """
  434. res = db_client.fetch(sql)
  435. if res:
  436. return True
  437. else:
  438. return False
  439. def update_job(piaoquan_crawler_db_client, aigc_db_client):
  440. """
  441. 更新任务
  442. :return:
  443. """
  444. account_list = get_accounts(db_client=aigc_db_client)
  445. # 订阅号
  446. subscription_accounts = [i for i in account_list if i['account_type'] in const.SUBSCRIBE_TYPE_SET]
  447. success_count = 0
  448. fail_count = 0
  449. for sub_item in tqdm(subscription_accounts):
  450. try:
  451. update_single_account(piaoquan_crawler_db_client, sub_item)
  452. success_count += 1
  453. time.sleep(5)
  454. except Exception as e:
  455. fail_count += 1
  456. log(
  457. task="updatePublishedMsgDaily",
  458. function="update_job",
  459. message="单个账号文章更新失败, 报错信息是: {}".format(e),
  460. status="fail",
  461. )
  462. log(
  463. task="updatePublishedMsgDaily",
  464. function="update_job",
  465. message="订阅号更新完成",
  466. data={
  467. "success": success_count,
  468. "fail": fail_count
  469. }
  470. )
  471. if fail_count / (success_count + fail_count) > const.SUBSCRIBE_FAIL_RATE_THRESHOLD:
  472. bot(
  473. title="订阅号超过 {}% 的账号更新失败".format(int(const.SUBSCRIBE_FAIL_RATE_THRESHOLD * 100)),
  474. detail={
  475. "success": success_count,
  476. "fail": fail_count,
  477. "failRate": fail_count / (success_count + fail_count)
  478. }
  479. )
  480. bot(
  481. title="更新每日发布文章任务完成通知",
  482. detail={
  483. "msg": "订阅号更新完成",
  484. "finish_time": datetime.today().__str__()
  485. },
  486. mention=False
  487. )
  488. # 服务号
  489. server_accounts = [i for i in account_list if i['account_type'] == const.SERVICE_TYPE]
  490. for sub_item in tqdm(server_accounts):
  491. try:
  492. update_single_account(piaoquan_crawler_db_client, sub_item)
  493. time.sleep(5)
  494. except Exception as e:
  495. print(e)
  496. bot(
  497. title="更新每日发布文章任务完成通知",
  498. detail={
  499. "msg": "服务号更新完成",
  500. "finish_time": datetime.today().__str__()
  501. },
  502. mention=False
  503. )
  504. def check_job(piaoquan_crawler_db_client, aigc_db_client):
  505. """
  506. 校验任务
  507. :return:
  508. """
  509. account_list = get_accounts(db_client=aigc_db_client)
  510. # 订阅号
  511. subscription_accounts = [i for i in account_list if i['account_type'] in const.SUBSCRIBE_TYPE_SET]
  512. fail_list = []
  513. # check and rework if fail
  514. for sub_item in tqdm(subscription_accounts):
  515. res = check_single_account(piaoquan_crawler_db_client, sub_item)
  516. if not res:
  517. try:
  518. update_single_account(piaoquan_crawler_db_client, sub_item)
  519. except Exception as e:
  520. print(e)
  521. print(sub_item)
  522. # fail_list.append(sub_item)
  523. # check whether success and bot if fails
  524. for sub_item in tqdm(subscription_accounts):
  525. res = check_single_account(piaoquan_crawler_db_client, sub_item)
  526. if not res:
  527. # 去掉三个不需要查看的字段
  528. sub_item.pop('account_type', None)
  529. sub_item.pop('account_auth', None)
  530. sub_item.pop('account_id', None)
  531. fail_list.append(sub_item)
  532. if fail_list:
  533. try:
  534. bot(
  535. title="更新当天发布文章,存在未更新的账号",
  536. detail={
  537. "columns": generate_bot_columns(),
  538. "rows": fail_list
  539. },
  540. table=True
  541. )
  542. except Exception as e:
  543. print("Timeout Error: {}".format(e))
  544. else:
  545. bot(
  546. title="更新当天发布文章,所有账号均更新成功",
  547. mention=False,
  548. detail={
  549. "msg": "校验任务完成",
  550. "finish_time": datetime.today().__str__()
  551. }
  552. )
  553. def monitor(piaoquan_crawler_db_client, long_articles_db_client, run_date):
  554. """
  555. 监控任务, 监测周期为7天,监测文章是否被违规,若监测到违规文章,则进行告警
  556. :return:
  557. """
  558. if not run_date:
  559. run_date = datetime.today().strftime("%Y-%m-%d")
  560. monitor_start_timestamp = int(datetime.strptime(run_date, "%Y-%m-%d").timestamp()) - const.MONITOR_PERIOD
  561. select_sql = f"""
  562. SELECT ghId, accountName, title, ContentUrl, wx_sn, from_unixtime(publish_timestamp) AS publish_timestamp
  563. FROM {ARTICLE_TABLE}
  564. WHERE publish_timestamp >= {monitor_start_timestamp};
  565. """
  566. article_list = piaoquan_crawler_db_client.fetch(select_sql)
  567. for article in tqdm(article_list, desc="monitor article list"):
  568. gh_id = article[0]
  569. account_name = article[1]
  570. title = article[2]
  571. # 判断标题是否存在违规记录
  572. if whether_title_unsafe(long_articles_db_client, title):
  573. continue
  574. url = article[3]
  575. wx_sn = article[4]
  576. publish_date = article[5]
  577. try:
  578. response = spider.get_article_text(url, is_cache=False)
  579. response_code = response['code']
  580. if response_code == const.ARTICLE_ILLEGAL_CODE:
  581. bot(
  582. title="文章违规告警",
  583. detail={
  584. "ghId": gh_id,
  585. "accountName": account_name,
  586. "title": title,
  587. "wx_sn": str(wx_sn),
  588. "publish_date": str(publish_date)
  589. },
  590. mention=False
  591. )
  592. aiditApi.delete_articles(
  593. gh_id=gh_id,
  594. title=title
  595. )
  596. except Exception as e:
  597. error_msg = traceback.format_exc()
  598. log(
  599. task="monitor",
  600. function="monitor",
  601. message="请求文章详情失败",
  602. data={
  603. "ghId": gh_id,
  604. "accountName": account_name,
  605. "title": title,
  606. "wx_sn": str(wx_sn),
  607. "error": str(e),
  608. "msg": error_msg
  609. }
  610. )
  611. def main():
  612. """
  613. main
  614. :return:
  615. """
  616. parser = ArgumentParser()
  617. parser.add_argument(
  618. "--run_task",
  619. help="update: update_job, check: check_job, detail: get_article_detail_job, monitor: monitor")
  620. parser.add_argument(
  621. "--run_date",
  622. help="--run_date %Y-%m-%d",
  623. )
  624. args = parser.parse_args()
  625. # 初始化数据库连接
  626. try:
  627. piaoquan_crawler_db_client = DatabaseConnector(piaoquan_crawler_config)
  628. piaoquan_crawler_db_client.connect()
  629. aigc_db_client = DatabaseConnector(denet_config)
  630. aigc_db_client.connect()
  631. long_articles_db_client = DatabaseConnector(long_articles_config)
  632. except Exception as e:
  633. error_msg = traceback.format_exc()
  634. bot(
  635. title="更新文章任务连接数据库失败",
  636. detail={
  637. "error": e,
  638. "msg": error_msg
  639. }
  640. )
  641. return
  642. if args.run_task:
  643. run_task = args.run_task
  644. match run_task:
  645. case "update":
  646. update_job(piaoquan_crawler_db_client=piaoquan_crawler_db_client, aigc_db_client=aigc_db_client)
  647. get_article_detail_job(db_client=piaoquan_crawler_db_client)
  648. case "check":
  649. check_job(piaoquan_crawler_db_client=piaoquan_crawler_db_client, aigc_db_client=aigc_db_client)
  650. case "detail":
  651. get_article_detail_job(db_client=piaoquan_crawler_db_client)
  652. case "monitor":
  653. if args.run_date:
  654. run_date = args.run_date
  655. else:
  656. run_date = None
  657. monitor(piaoquan_crawler_db_client=piaoquan_crawler_db_client,
  658. long_articles_db_client=long_articles_db_client, run_date=run_date)
  659. case _:
  660. print("No such task, input update: update_job, check: check_job, detail: get_article_detail_job")
  661. else:
  662. update_job(piaoquan_crawler_db_client=piaoquan_crawler_db_client, aigc_db_client=aigc_db_client)
  663. check_job(piaoquan_crawler_db_client=piaoquan_crawler_db_client, aigc_db_client=aigc_db_client)
  664. get_article_detail_job(db_client=piaoquan_crawler_db_client)
  665. if __name__ == '__main__':
  666. main()