Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

184 rindas
5.8KB

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