crawler_gzh_fans.py 6.7 KB

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