updatePublishedMsgDaily.py 14 KB

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