updatePublishedMsgDaily.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. """
  2. @author: luojunhui
  3. @description: update daily information into official articles v2
  4. """
  5. import time
  6. import json
  7. import traceback
  8. from tqdm import tqdm
  9. from datetime import datetime
  10. from applications import PQMySQL, WeixinSpider, Functions, log, bot, aiditApi
  11. ARTICLE_TABLE = "official_articles_v2"
  12. def get_accounts_v1():
  13. """
  14. 获取账号信息
  15. :return: [{}, {},...], [{}, {}, {}...]
  16. """
  17. with open("config/accountInfoV0914.json", encoding="utf-8") as f:
  18. account_list = json.loads(f.read())
  19. subscription_account = [i for i in account_list if i['type'] == '订阅号']
  20. server_account = [i for i in account_list if i['type'] == '服务号']
  21. return subscription_account, server_account
  22. def get_account_using_status():
  23. """
  24. 获取正在 using 的 ghid
  25. :return:
  26. """
  27. sql = "SELECT gh_id FROM long_articles_publishing_accounts WHERE is_using = 1;"
  28. gh_id_tuple = PQMySQL().select(sql)
  29. gh_id_list = [
  30. i[0] for i in gh_id_tuple
  31. ]
  32. return set(gh_id_list)
  33. def get_accounts():
  34. """
  35. 从 aigc 数据库中获取目前处于发布状态的账号
  36. :return:
  37. "name": line[0],
  38. "ghId": line[1],
  39. "follower_count": line[2],
  40. "account_init_time": int(line[3] / 1000),
  41. "account_type": line[4],
  42. "account_auth": line[5]
  43. """
  44. using_account_set = get_account_using_status()
  45. account_list_with_out_using_status = aiditApi.get_publish_account_from_aigc()
  46. account_list = []
  47. for item in account_list_with_out_using_status:
  48. if item['ghId'] in using_account_set:
  49. item['using_status'] = 1
  50. else:
  51. item['using_status'] = 0
  52. account_list.append(item)
  53. subscription_account = [i for i in account_list if i['account_type'] in {0, 1}]
  54. server_account = [i for i in account_list if i['account_type'] == 2]
  55. return subscription_account, server_account
  56. def insert_each_msg(db_client, account_info, account_name, msg_list):
  57. """
  58. 把消息数据更新到数据库中
  59. :param account_info:
  60. :param db_client:
  61. :param account_name:
  62. :param msg_list:
  63. :return:
  64. """
  65. gh_id = account_info['ghId']
  66. for info in msg_list:
  67. baseInfo = info.get("BaseInfo", {})
  68. appMsgId = info.get("AppMsg", {}).get("BaseInfo", {}).get("AppMsgId", None)
  69. createTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("CreateTime", None)
  70. updateTime = info.get("AppMsg", {}).get("BaseInfo", {}).get("UpdateTime", None)
  71. Type = info.get("AppMsg", {}).get("BaseInfo", {}).get("Type", None)
  72. detail_article_list = info.get("AppMsg", {}).get("DetailInfo", [])
  73. if detail_article_list:
  74. for article in detail_article_list:
  75. title = article.get("Title", None)
  76. Digest = article.get("Digest", None)
  77. ItemIndex = article.get("ItemIndex", None)
  78. ContentUrl = article.get("ContentUrl", None)
  79. SourceUrl = article.get("SourceUrl", None)
  80. CoverImgUrl = article.get("CoverImgUrl", None)
  81. CoverImgUrl_1_1 = article.get("CoverImgUrl_1_1", None)
  82. CoverImgUrl_235_1 = article.get("CoverImgUrl_235_1", None)
  83. ItemShowType = article.get("ItemShowType", None)
  84. IsOriginal = article.get("IsOriginal", None)
  85. ShowDesc = article.get("ShowDesc", None)
  86. show_stat = Functions().show_desc_to_sta(ShowDesc)
  87. ori_content = article.get("ori_content", None)
  88. show_view_count = show_stat.get("show_view_count", 0)
  89. show_like_count = show_stat.get("show_like_count", 0)
  90. show_zs_count = show_stat.get("show_zs_count", 0)
  91. show_pay_count = show_stat.get("show_pay_count", 0)
  92. wx_sn = ContentUrl.split("&sn=")[1].split("&")[0] if ContentUrl else None
  93. status = account_info['using_status']
  94. info_tuple = (
  95. gh_id,
  96. account_name,
  97. appMsgId,
  98. title,
  99. Type,
  100. createTime,
  101. updateTime,
  102. Digest,
  103. ItemIndex,
  104. ContentUrl,
  105. SourceUrl,
  106. CoverImgUrl,
  107. CoverImgUrl_1_1,
  108. CoverImgUrl_235_1,
  109. ItemShowType,
  110. IsOriginal,
  111. ShowDesc,
  112. ori_content,
  113. show_view_count,
  114. show_like_count,
  115. show_zs_count,
  116. show_pay_count,
  117. wx_sn,
  118. json.dumps(baseInfo, ensure_ascii=False),
  119. Functions().str_to_md5(title),
  120. status
  121. )
  122. try:
  123. insert_sql = f"""
  124. INSERT INTO {ARTICLE_TABLE}
  125. (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)
  126. values
  127. (%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);
  128. """
  129. db_client.update(sql=insert_sql, params=info_tuple)
  130. log(
  131. task="updatePublishedMsgDaily",
  132. function="insert_each_msg",
  133. message="插入文章数据成功",
  134. data={
  135. "info": info_tuple
  136. }
  137. )
  138. except Exception as e:
  139. try:
  140. update_sql = f"""
  141. UPDATE {ARTICLE_TABLE}
  142. SET show_view_count = %s, show_like_count=%s
  143. WHERE wx_sn = %s;
  144. """
  145. db_client.update(sql=update_sql,
  146. params=(show_view_count, show_like_count, wx_sn))
  147. log(
  148. task="updatePublishedMsgDaily",
  149. function="insert_each_msg",
  150. message="更新文章数据成功",
  151. data={
  152. "wxSn": wx_sn,
  153. "likeCount": show_like_count,
  154. "viewCount": show_view_count
  155. }
  156. )
  157. except Exception as e:
  158. log(
  159. task="updatePublishedMsgDaily",
  160. function="insert_each_msg",
  161. message="更新文章失败, 报错原因是: {}".format(e),
  162. status="fail"
  163. )
  164. continue
  165. def update_each_account(db_client, account_info, account_name, latest_update_time, cursor=None):
  166. """
  167. 更新每一个账号信息
  168. :param account_info:
  169. :param account_name:
  170. :param cursor:
  171. :param latest_update_time: 最新更新时间
  172. :param db_client: 数据库连接信息
  173. :return: None
  174. """
  175. gh_id = account_info['ghId']
  176. response = WeixinSpider().update_msg_list(ghId=gh_id, index=cursor)
  177. msg_list = response.get("data", {}).get("data", {})
  178. if msg_list:
  179. # do
  180. last_article_in_this_msg = msg_list[-1]
  181. last_time_stamp_in_this_msg = last_article_in_this_msg['AppMsg']['BaseInfo']['UpdateTime']
  182. last_url = last_article_in_this_msg['AppMsg']['DetailInfo'][0]['ContentUrl']
  183. resdata = WeixinSpider().get_account_by_url(last_url)
  184. check_id = resdata['data'].get('data', {}).get('wx_gh')
  185. if check_id == gh_id:
  186. insert_each_msg(
  187. db_client=db_client,
  188. account_info=account_info,
  189. account_name=account_name,
  190. msg_list=msg_list
  191. )
  192. if last_time_stamp_in_this_msg > latest_update_time:
  193. next_cursor = response['data']['next_cursor']
  194. return update_each_account(
  195. db_client=db_client,
  196. account_info=account_info,
  197. account_name=account_name,
  198. latest_update_time=latest_update_time,
  199. cursor=next_cursor
  200. )
  201. log(
  202. task="updatePublishedMsgDaily",
  203. function="update_each_account",
  204. message="账号文章更新成功",
  205. data=response
  206. )
  207. else:
  208. log(
  209. task="updatePublishedMsgDaily",
  210. function="update_each_account",
  211. message="账号文章更新失败",
  212. status="fail",
  213. data=response
  214. )
  215. return
  216. def check_account_info(db_client, gh_id, account_name):
  217. """
  218. 通过 gh_id查询视频信息
  219. :param account_name:
  220. :param db_client:
  221. :param gh_id:
  222. :return:
  223. """
  224. sql = f"""
  225. SELECT accountName, updateTime
  226. FROM {ARTICLE_TABLE}
  227. WHERE ghId = '{gh_id}'
  228. ORDER BY updateTime DESC LIMIT 1;
  229. """
  230. result = db_client.select(sql)
  231. if result:
  232. old_account_name, update_time = result[0]
  233. return {
  234. "account_name": old_account_name,
  235. "update_time": update_time,
  236. "account_type": "history"
  237. }
  238. else:
  239. return {
  240. "account_name": account_name,
  241. "update_time": int(time.time()) - 30 * 24 * 60 * 60,
  242. "account_type": "new"
  243. }
  244. def update_single_account(db_client, account_info):
  245. """
  246. :param account_info:
  247. :param db_client:
  248. :return:
  249. """
  250. gh_id = account_info['ghId']
  251. account_name = account_info['name']
  252. account_detail = check_account_info(db_client, gh_id, account_name)
  253. account_name = account_detail['account_name']
  254. update_time = account_detail['update_time']
  255. update_each_account(
  256. db_client=db_client,
  257. account_info=account_info,
  258. account_name=account_name,
  259. latest_update_time=update_time
  260. )
  261. def check_single_account(db_client, account_item):
  262. """
  263. 校验每个账号是否更新
  264. :param db_client:
  265. :param account_item:
  266. :return: True / False
  267. """
  268. gh_id = account_item['ghId']
  269. account_type = account_item['account_type']
  270. today_str = datetime.today().strftime("%Y-%m-%d")
  271. today_date_time = datetime.strptime(today_str, "%Y-%m-%d")
  272. today_timestamp = today_date_time.timestamp()
  273. sql = f"""
  274. SELECT updateTime
  275. FROM {ARTICLE_TABLE}
  276. WHERE ghId = '{gh_id}'
  277. ORDER BY updateTime
  278. DESC
  279. LIMIT 1;
  280. """
  281. try:
  282. latest_update_time = db_client.select(sql)[0][0]
  283. # 判断该账号当天发布的文章是否被收集
  284. if account_type in {0, 1}:
  285. if int(latest_update_time) > int(today_timestamp):
  286. return True
  287. else:
  288. return False
  289. else:
  290. if int(latest_update_time) > int(today_timestamp) - 7 * 24 * 3600:
  291. return True
  292. else:
  293. return False
  294. except Exception as e:
  295. print("updateTime Error -- {}".format(e))
  296. return False
  297. def update_job():
  298. """
  299. 更新任务
  300. :return:
  301. """
  302. try:
  303. db_client = PQMySQL()
  304. except Exception as e:
  305. error_msg = traceback.format_exc()
  306. bot(
  307. title="更新文章任务连接数据库失败",
  308. detail={
  309. "error": e,
  310. "msg": error_msg
  311. }
  312. )
  313. return
  314. sub_accounts, server_accounts = get_accounts()
  315. s_count = 0
  316. f_count = 0
  317. for sub_item in tqdm(sub_accounts):
  318. try:
  319. update_single_account(db_client, sub_item)
  320. s_count += 1
  321. time.sleep(5)
  322. except Exception as e:
  323. f_count += 1
  324. log(
  325. task="updatePublishedMsgDaily",
  326. function="update_job",
  327. message="单个账号文章更新失败, 报错信息是: {}".format(e),
  328. status="fail",
  329. )
  330. log(
  331. task="updatePublishedMsgDaily",
  332. function="update_job",
  333. message="订阅号更新完成",
  334. data={
  335. "success": s_count,
  336. "fail": f_count
  337. }
  338. )
  339. if f_count / (s_count + f_count) > 0.3:
  340. bot(
  341. title="订阅号超过 30% 的账号更新失败",
  342. detail={
  343. "success": s_count,
  344. "fail": f_count,
  345. "failRate": f_count / (s_count + f_count)
  346. }
  347. )
  348. bot(
  349. title="更新每日发布文章任务完成通知",
  350. detail={
  351. "msg": "订阅号更新完成",
  352. "finish_time": datetime.today().__str__()
  353. },
  354. mention=False
  355. )
  356. for sub_item in tqdm(server_accounts):
  357. try:
  358. update_single_account(db_client, sub_item)
  359. time.sleep(5)
  360. except Exception as e:
  361. print(e)
  362. bot(
  363. title="更新每日发布文章任务完成通知",
  364. detail={
  365. "msg": "服务号更新完成",
  366. "finish_time": datetime.today().__str__()
  367. },
  368. mention=False
  369. )
  370. def check_job():
  371. """
  372. 校验任务
  373. :return:
  374. """
  375. try:
  376. db_client = PQMySQL()
  377. except Exception as e:
  378. error_msg = traceback.format_exc()
  379. bot(
  380. title="校验更新文章任务连接数据库失败",
  381. detail={
  382. "job": "check_job",
  383. "error": e,
  384. "msg": error_msg
  385. }
  386. )
  387. return
  388. sub_accounts, server_accounts = get_accounts()
  389. fail_list = []
  390. # account_list = sub_accounts + server_accounts
  391. account_list = sub_accounts
  392. # check and rework if fail
  393. for sub_item in tqdm(account_list):
  394. res = check_single_account(db_client, sub_item)
  395. if not res:
  396. update_single_account(db_client, sub_item)
  397. # check whether success and bot if fails
  398. for sub_item in tqdm(account_list):
  399. res = check_single_account(db_client, sub_item)
  400. if not res:
  401. fail_list.append(sub_item)
  402. if fail_list:
  403. try:
  404. bot(
  405. title="日常报警, 存在账号更新失败",
  406. detail=fail_list
  407. )
  408. except Exception as e:
  409. print("Timeout Error: {}".format(e))
  410. else:
  411. bot(
  412. title="校验完成通知",
  413. mention=False,
  414. detail={
  415. "msg": "校验任务完成",
  416. "finish_time": datetime.today().__str__()
  417. }
  418. )
  419. def main():
  420. """
  421. main
  422. :return:
  423. """
  424. update_job()
  425. time.sleep(60)
  426. check_job()
  427. if __name__ == '__main__':
  428. main()