您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

224 行
7.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():
  67. logger.info('自动从群添加好友')
  68. wxchat=gewe_chat.wxchat
  69. while True:
  70. login_keys = list(redis_helper.redis_helper.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'))
  71. logger.info(f"Fetching login keys: {login_keys}")
  72. # 遍历每一个获取到的登录键
  73. for k in login_keys:
  74. r= redis_helper.redis_helper.get_hash(k)
  75. # print(r)
  76. token_id = r.get('tokenId')
  77. app_id = r.get('appId')
  78. nickname=r.get('nickName')
  79. wxid = r.get('wxid')
  80. status=r.get('status')
  81. if status=='1':
  82. c = wxchat.get_wxchat_config_from_cache(app_id)
  83. contacts = wxchat.get_contacts_brief_from_cache(wxid)
  84. contact_wxids = [c.get('userName') for c in contacts]
  85. chatrooms = c.get('addContactsFromChatroomIdWhiteList',[])
  86. for chatroom_id in chatrooms:
  87. chatroom = wxchat.get_group_info_from_cache(wxid,chatroom_id)
  88. chatroom_nickname=chatroom.get('nickName')
  89. chatroot_member_list=chatroom.get('memberList',[])
  90. contact_set = set(contact_wxids)
  91. remaining_chatroot_members = [x for x in chatroot_member_list if x.get('wxid') not in contact_set]
  92. for m in remaining_chatroot_members:
  93. ret,msg,data=wxchat.add_group_member_as_friend(token_id,app_id,chatroom_id,m.get('wxid'),f'您好,我是来自{chatroom_nickname}群的{nickname}')
  94. logger.info(f'{nickname} 向 {chatroom_nickname}群的{m.get("nickname")}发送好友邀请 {msg}')
  95. time.sleep(3)
  96. time.sleep(3)
  97. else:
  98. logger.info(f'微信ID {wxid} 未登录 {app_id} ,群成员不能定时定时')
  99. time.sleep(3)
  100. #time.sleep(60*10)
  101. time.sleep(3600*24)
  102. def start_wxchat_thread():
  103. # gewe_chat.start()
  104. scan_wx_login_info()
  105. # 启动同步联系人线程
  106. threading.Thread(target=fetch_and_save_contacts2).start()
  107. #threading.Thread(target=auto_contacts_from_chatroom).start()
  108. def scan_wx_login_info():
  109. gewe_chat.start()
  110. wxchat = gewe_chat.wxchat
  111. cursor = 0
  112. while True:
  113. cursor, login_keys = redis_helper.redis_helper.client.scan(cursor, match='__AI_OPS_WX__:LOGININFO:*')
  114. for k in login_keys:
  115. r = redis_helper.redis_helper.get_hash(k)
  116. app_id=r.get("appId")
  117. #tel=r.get("mobile")
  118. token_id=r.get("tokenId")
  119. wxid=r.get("wxid")
  120. is_online = wxchat.check_online(token_id, app_id)
  121. if is_online:
  122. logger.info(f'微信ID {wxid} 在APPID {app_id} 已经在线')
  123. else:
  124. # 尝试重连
  125. res = wxchat.reconnection(token_id, app_id)
  126. if res.get('ret') == 200:
  127. logger.info(f'微信ID {wxid} 在APPID {app_id} 重连成功')
  128. # 同步联系人
  129. #fetch_and_save_contacts(wxchat, token_id, app_id, k)
  130. else:
  131. print("重连失败,重新登录...")
  132. print("发送离线消息到kafka")
  133. redis_helper.redis_helper.update_hash_field(k,'status',0)
  134. time.sleep(3)
  135. # 如果游标为 0,则表示扫描完成
  136. if cursor == 0:
  137. break
  138. app = Flask(__name__)
  139. # api = Api(app)
  140. flask_api = Api(app,errors=errors, catch_all_404s=True)
  141. # 设置日志(logger 已在 log.py 中配置)
  142. app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
  143. app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
  144. app.logger.setLevel(logging.DEBUG) # 设置日志级别
  145. # 添加拦截器
  146. app.before_request(before_request)
  147. app.after_request(after_request)
  148. app.register_error_handler(Exception, handle_exception)
  149. # 定义路由
  150. flask_api.add_resource(MessagesResource, '/messages')
  151. flask_api.add_resource(DeleteFriendResource, '/api/contacts/deletefriend')
  152. flask_api.add_resource(GetFriendsInfoResource, '/api/contacts/getfriends')
  153. flask_api.add_resource(GetWxchatConfigResource, '/api/wxchat/getconfig')
  154. flask_api.add_resource(SaveWxchatConfigResource, '/api/wxchat/saveconfig')
  155. flask_api.add_resource(GetGroupsInfoResource, '/api/groups/getchatroominfo')
  156. flask_api.add_resource(GetLoginInfoResource, '/api/agent/getlogin')
  157. flask_api.add_resource(SendSNSTextResource, '/api/sns/sendtext')
  158. flask_api.add_resource(SendSNSImageResource, '/api/sns/sendimages')
  159. flask_api.add_resource(SendSNSVideoResource, '/api/sns/sendvideo')
  160. load_config()
  161. worker()
  162. if __name__ == '__main__':
  163. # 获取环境变量
  164. environment = os.environ.get('environment', 'default')
  165. port = 80 if environment == 'default' else 5000
  166. app.run(debug=False, host='0.0.0.0', port=port)