crawler_gzh_fans.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import json
  2. from applications.crawler.wechat import (
  3. get_gzh_fans,
  4. get_access_token,
  5. get_union_id_batch,
  6. )
  7. from applications.api import feishu_robot
  8. from applications.utils import run_tasks_with_asyncio_task_group
  9. class CrawlerGzhFansBase:
  10. def __init__(self, pool, log_client):
  11. self.pool = pool
  12. self.log_client = log_client
  13. # 从数据库获取 access_token
  14. async def get_access_token_from_database(self, gh_id):
  15. query = """
  16. SELECT access_token FROM gzh_cookie_info where gh_id = %s and access_token_status = %s;
  17. """
  18. return await self.pool.async_fetch(query=query, params=(gh_id, 1))
  19. # 从数据库获取粉丝 && token
  20. async def get_cookie_token_from_database(self, gh_id):
  21. query = """
  22. SELECT token, cookie FROM gzh_cookie_info WHERE gh_id = %s and token_status = %s;
  23. """
  24. return await self.pool.async_fetch(query=query, params=(gh_id, 1))
  25. # 设置access_token状态为无效
  26. async def set_access_token_as_invalid(self, gh_id):
  27. query = """
  28. UPDATE gzh_cookie_info SET access_token_status = %s WHERE gh_id = %s;
  29. """
  30. return await self.pool.async_save(query=query, params=(0, gh_id))
  31. # 设置 cookie 状态为无效
  32. async def set_cookie_token_as_invalid(self, gh_id):
  33. query = """
  34. UPDATE gzh_cookie_info SET token_status = %s WHERE gh_id = %s;
  35. """
  36. return await self.pool.async_save(query=query, params=(0, gh_id))
  37. # 获取账号列表
  38. async def get_account_list_from_database(self):
  39. query = """
  40. SELECT gh_id, account_name, app_id, app_secret, cursor_openid, cursor_timestamp
  41. FROM gzh_account_info WHERE status = %s;
  42. """
  43. return await self.pool.async_fetch(query=query, params=(1,))
  44. # 获取 open_id 列表
  45. async def get_open_id_list_from_database(self, gh_id):
  46. query = """
  47. SELECT user_openid as openid, 'zh_CN' as lang FROM gzh_fans_info
  48. WHERE status = %s and gh_id = %s LIMIT %s;
  49. """
  50. return await self.pool.async_fetch(query=query, params=(0, gh_id, 20))
  51. # 批量插入粉丝信息
  52. async def insert_gzh_fans_batch(self, account_info, user_list):
  53. for user in user_list:
  54. query = """
  55. INSERT IGNORE INTO gzh_fans_info
  56. (gh_id, account_name, user_openid, user_name, user_create_time, user_head_img, user_remark, identity_type, identity_open_id)
  57. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);
  58. """
  59. params = (
  60. account_info["gh_id"],
  61. account_info["account_name"],
  62. user["user_openid"],
  63. user["user_name"],
  64. user["user_create_time"],
  65. user["user_head_img"],
  66. user["user_remark"],
  67. user["identity_type"],
  68. user["identity_open_id"],
  69. )
  70. await self.pool.async_save(query=query, params=params)
  71. # 更新公众号的 cursor 位置
  72. async def update_gzh_cursor_info(self, gh_id, cursor_id, cursor_timestamp):
  73. query = """
  74. UPDATE gzh_account_info SET cursor_openid = %s, cursor_timestamp = %s WHERE gh_id = %s;
  75. """
  76. return await self.pool.async_save(
  77. query=query, params=(cursor_id, cursor_timestamp, gh_id)
  78. )
  79. # 更新公众号的 cookie
  80. async def set_cookie_for_each_account(self, gh_id, cookie, token):
  81. query = """
  82. UPDATE gzh_cookie_info SET cookie = %s, token = %s, token_status = %s
  83. WHERE gh_id = %s;
  84. """
  85. return await self.pool.async_save(query=query, params=(cookie, token, 1, gh_id))
  86. async def set_access_token_for_each_account(self, gh_id, access_token):
  87. query = """
  88. UPDATE gzh_cookie_info SET access_token = %s, access_token_status = %s WHERE gh_id = %s;
  89. """
  90. return await self.pool.async_save(query=query, params=(access_token, 1, gh_id))
  91. class CrawlerGzhFans(CrawlerGzhFansBase):
  92. def __init__(self, pool, log_client):
  93. super().__init__(pool, log_client)
  94. # 抓取单个账号的粉丝
  95. async def crawl_fans_for_each_account(self, account_info):
  96. cookie_obj = await self.get_cookie_token_from_database(account_info["gh_id"])
  97. if not cookie_obj:
  98. return
  99. if not account_info.get("cursor_openid"):
  100. cursor_openid = ''
  101. else:
  102. cursor_openid = account_info["cursor_openid"]
  103. if not account_info.get("cursor_timestamp"):
  104. cursor_timestamp = ''
  105. else:
  106. cursor_timestamp = account_info["cursor_timestamp"]
  107. response = await get_gzh_fans(
  108. token=cookie_obj[0]["token"],
  109. cookie=cookie_obj[0]["cookie"],
  110. cursor_id=cursor_openid,
  111. cursor_timestamp=cursor_timestamp,
  112. )
  113. base_resp = response.get("base_resp", {})
  114. code = base_resp.get("ret")
  115. error_msg = base_resp.get("err_msg")
  116. match code:
  117. case 0:
  118. user_list = response.get("user_list", {}).get("user_info_list")
  119. next_cursor_id = user_list[-1].get("user_openid")
  120. next_cursor_timestamp = user_list[-1].get("user_create_time")
  121. await self.insert_gzh_fans_batch(account_info, user_list)
  122. await self.update_gzh_cursor_info(
  123. account_info["gh_id"], next_cursor_id, next_cursor_timestamp
  124. )
  125. case '00040':
  126. print(f"token 非法: {error_msg}")
  127. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  128. await feishu_robot.bot(
  129. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  130. detail=account_info,
  131. env="cookie_monitor_bot",
  132. mention=False,
  133. )
  134. case _:
  135. print("token 异常, 请及时刷新")
  136. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  137. await feishu_robot.bot(
  138. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  139. detail=account_info,
  140. env="cookie_monitor_bot",
  141. mention=False,
  142. )
  143. # 通过 access_token && open_id 抓取 union_id
  144. async def get_union_ids_for_each_account(self, account_info: dict):
  145. access_token = await self.get_access_token_from_database(account_info["gh_id"])
  146. if not access_token:
  147. print(f"{account_info['account_name']}: access_token is not available")
  148. response = await get_access_token(account_info['app_id'], account_info["app_secret"])
  149. print(json.dumps(response, indent=4, ensure_ascii=False))
  150. # access_token = response.get("access_token")
  151. # await self.set_access_token_for_each_account(account_info["gh_id"], access_token)
  152. #
  153. # # 通过 access_token 获取 union_id
  154. # user_list = await self.get_open_id_list_from_database(gh_id=account_info["gh_id"])
  155. # union_info = await get_union_id_batch(access_token=access_token ,user_list=user_list)
  156. # print(json.dumps(union_info, indent=4, ensure_ascii=False))
  157. # main function
  158. async def deal(self):
  159. account_list = await self.get_account_list_from_database()
  160. # for account_info in account_list:
  161. # # await self.get_union_ids_for_each_account(account_info)
  162. # await self.crawl_fans_for_each_account(account_info)
  163. return await run_tasks_with_asyncio_task_group(
  164. task_list=account_list,
  165. handler=self.crawl_fans_for_each_account,
  166. max_concurrency=5,
  167. fail_fast=False,
  168. description="抓取公众号账号粉丝",
  169. unit="page",
  170. )