You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

224 lines
7.1KB

  1. from flask import Flask, send_from_directory, request,jsonify
  2. from flask_restful import Api,got_request_exception
  3. from resources.user_resource import UserResource
  4. from resources.messages_resource import MessagesResource
  5. from resources.contacts_resources import DeleteFriendResource,GetFriendsInfoResource
  6. from resources.config_reources import GetWxchatConfigResource ,SaveWxchatConfigResource
  7. from resources.groups_resources import GetGroupsInfoResource
  8. from common.log import logger, log_exception
  9. from common.interceptors import before_request, after_request, handle_exception
  10. import threading
  11. from common import kafka_helper, redis_helper,utils
  12. import logging
  13. from config import load_config
  14. from wechat.biz import start_kafka_consumer_thread
  15. from wechat import gewe_chat
  16. import os,time,json
  17. from voice.ali.ali_voice import AliVoice
  18. # 自定义错误消息
  19. errors = {
  20. 'UserAlreadyExistsError': {
  21. 'message': "A user with that username already exists.",
  22. 'status': 409,
  23. },
  24. 'ResourceDoesNotExist': {
  25. 'message': "A resource with that ID no longer exists.",
  26. 'status': 410,
  27. 'extra': "Any extra information you want.",
  28. },
  29. }
  30. def worker():
  31. kafka_helper.start()
  32. redis_helper.start()
  33. start_wxchat_thread()
  34. start_kafka_consumer_thread()
  35. def fetch_and_save_contacts2():
  36. """
  37. 获取联系人列表并保存到缓存
  38. """
  39. wxchat=gewe_chat.wxchat
  40. while True:
  41. login_keys = list(redis_helper.redis_helper.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'))
  42. logger.info(f"Fetching login keys: {login_keys}")
  43. # 遍历每一个获取到的登录键
  44. for k in login_keys:
  45. r= redis_helper.redis_helper.get_hash(k)
  46. # print(r)
  47. token_id = r.get('tokenId')
  48. app_id = r.get('appId')
  49. wxid = r.get('wxid')
  50. status=r.get('status')
  51. if status=='1':
  52. ret,msg,contacts_list = wxchat.fetch_contacts_list(token_id, app_id)
  53. friend_wxids = contacts_list['friends'][3:] # 可以调整截取范围
  54. #friend_wxids.remove('weixin')
  55. wxchat.save_contacts_brief_to_cache(token_id, app_id, wxid, friend_wxids)
  56. logger.info(f'微信ID {wxid} 登录APPID {app_id} 成功,联系人已定时保存')
  57. chatrooms=contacts_list['chatrooms']
  58. wxchat.save_groups_info_to_cache(token_id, app_id, wxid, chatrooms)
  59. logger.info(f'微信ID {wxid} 登录APPID {app_id} 成功,群信息已定时保存')
  60. else:
  61. logger.info(f'微信ID {wxid} 未登录 {app_id} ,联系人不能定时保存')
  62. time.sleep(3)
  63. time.sleep(60*10)
  64. def start_wxchat_thread():
  65. # gewe_chat.start()
  66. scan_wx_login_info()
  67. # 启动同步联系人线程
  68. threading.Thread(target=fetch_and_save_contacts2).start()
  69. def scan_wx_login_info():
  70. gewe_chat.start()
  71. wxchat = gewe_chat.wxchat
  72. cursor = 0
  73. while True:
  74. cursor, login_keys = redis_helper.redis_helper.client.scan(cursor, match='__AI_OPS_WX__:LOGININFO:*')
  75. for k in login_keys:
  76. r = redis_helper.redis_helper.get_hash(k)
  77. app_id=r.get("appId")
  78. #tel=r.get("mobile")
  79. token_id=r.get("tokenId")
  80. wxid=r.get("wxid")
  81. is_online = wxchat.check_online(token_id, app_id)
  82. if is_online:
  83. logger.info(f'微信ID {wxid} 在APPID {app_id} 已经在线')
  84. else:
  85. # 尝试重连
  86. res = wxchat.reconnection(token_id, app_id)
  87. if res.get('ret') == 200:
  88. logger.info(f'微信ID {wxid} 在APPID {app_id} 重连成功')
  89. # 同步联系人
  90. #fetch_and_save_contacts(wxchat, token_id, app_id, k)
  91. else:
  92. print("重连失败,重新登录...")
  93. print("发送离线消息到kafka")
  94. redis_helper.redis_helper.update_hash_field(k,'status',0)
  95. time.sleep(3)
  96. # 如果游标为 0,则表示扫描完成
  97. if cursor == 0:
  98. break
  99. # def app_run():
  100. # app = Flask(__name__)
  101. # # api = Api(app)
  102. # flask_api = Api(app,errors=errors, catch_all_404s=True)
  103. # # 设置日志(logger 已在 log.py 中配置)
  104. # app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
  105. # app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
  106. # app.logger.setLevel(logging.DEBUG) # 设置日志级别
  107. # # 添加拦截器
  108. # app.before_request(before_request)
  109. # app.after_request(after_request)
  110. # app.register_error_handler(Exception, handle_exception)
  111. # # 定义路由
  112. # flask_api.add_resource(UserResource, '/api/user', '/api/user/<int:user_id>')
  113. # flask_api.add_resource(MessagesResource, '/messages')
  114. # flask_api.add_resource(DeleteFriendResource, '/api/contacts/deletefriend')
  115. # flask_api.add_resource(GetFriendsInfoResource, '/api/contacts/getfriends')
  116. # flask_api.add_resource(GetWxchatConfigResource, '/api/wxchat/getconfig')
  117. # flask_api.add_resource(SaveWxchatConfigResource, '/api/wxchat/saveconfig')
  118. # flask_api.add_resource(GetGroupsInfoResource, '/api/groups/getchatroominfo')
  119. # load_config()
  120. # worker()
  121. # # 获取环境变量
  122. # environment = os.environ.get('environment', 'default')
  123. # port = 5000 if environment == 'default' else 80 # default 使用 5000,其他环境使用 80
  124. # if environment == 'default':
  125. # app.run(debug=False, host='0.0.0.0', port=port) # 默认直接启动 Flask 内置服务器
  126. # else:
  127. # # 在非 default 环境中,使用 Gunicorn 启动应用
  128. # #os.system(f"gunicorn -w 4 -b 0.0.0.0:{port} app:app") # 启动 Gunicorn,4 个工作进程
  129. # app.run()
  130. app = Flask(__name__)
  131. # api = Api(app)
  132. flask_api = Api(app,errors=errors, catch_all_404s=True)
  133. # 设置日志(logger 已在 log.py 中配置)
  134. app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
  135. app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
  136. app.logger.setLevel(logging.DEBUG) # 设置日志级别
  137. # 添加拦截器
  138. app.before_request(before_request)
  139. app.after_request(after_request)
  140. app.register_error_handler(Exception, handle_exception)
  141. # 定义路由
  142. flask_api.add_resource(UserResource, '/api/user', '/api/user/<int:user_id>')
  143. flask_api.add_resource(MessagesResource, '/messages')
  144. flask_api.add_resource(DeleteFriendResource, '/api/contacts/deletefriend')
  145. flask_api.add_resource(GetFriendsInfoResource, '/api/contacts/getfriends')
  146. flask_api.add_resource(GetWxchatConfigResource, '/api/wxchat/getconfig')
  147. flask_api.add_resource(SaveWxchatConfigResource, '/api/wxchat/saveconfig')
  148. flask_api.add_resource(GetGroupsInfoResource, '/api/groups/getchatroominfo')
  149. load_config()
  150. worker()
  151. if __name__ == '__main__':
  152. # 获取环境变量
  153. environment = os.environ.get('environment', 'default')
  154. port = 80 if environment == 'default' else 5000
  155. app.run(debug=False, host='0.0.0.0', port=port)