Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

258 lines
8.9KB

  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 common.log import logger, log_exception
  6. from common.interceptors import before_request, after_request, handle_exception
  7. import threading
  8. from common import kafka_helper, redis_helper,utils
  9. import logging
  10. from config import load_config
  11. from wechat.biz import start_kafka_consumer_thread
  12. from channel import channel_factory
  13. from wechat import gewe_chat
  14. import os,time,json
  15. from voice.ali.ali_voice import AliVoice
  16. # 自定义错误消息
  17. errors = {
  18. 'UserAlreadyExistsError': {
  19. 'message': "A user with that username already exists.",
  20. 'status': 409,
  21. },
  22. 'ResourceDoesNotExist': {
  23. 'message': "A resource with that ID no longer exists.",
  24. 'status': 410,
  25. 'extra': "Any extra information you want.",
  26. },
  27. }
  28. def save_friends_to_redis(wxid, friends):
  29. # 将联系人信息保存到 Redis,使用一个合适的 key
  30. hash_key = f"__AI_OPS_WX__:CONTACTS_BRIEF:{wxid}"
  31. redis_helper.redis_helper.set_hash(hash_key,{"data":json.dumps(friends,ensure_ascii=False)})
  32. # def save_contacts_brief_to_redis(wxid, friends):
  33. # # 将联系人信息保存到 Redis,使用一个合适的 key
  34. # hash_key = f"__AI_OPS_WX__:CONTACTS_BRIEF:{wxid}"
  35. # # 获取缓存中的数据,如果缓存不存在则初始化为空列表
  36. # cache_str = redis_helper.redis_helper.get_hash_field(hash_key, "data")
  37. # cache = json.loads(cache_str) if cache_str else []
  38. # # 合并联系人信息
  39. # cache.extend(friends)
  40. # # 将合并后的联系人数据保存回 Redis
  41. # redis_helper.redis_helper.update_hash_field(hash_key, "data", {
  42. # "data": json.dumps(cache, ensure_ascii=False)
  43. # })
  44. def worker():
  45. kafka_helper.start()
  46. redis_helper.start()
  47. start_wxchat_thread()
  48. start_kafka_consumer_thread()
  49. def start_wxchat_thread_free():
  50. gewe_chat.start()
  51. wxchat=gewe_chat.wxchat
  52. token_id = wxchat.get_token_id()
  53. # token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
  54. print(f'tokenId: {token_id}')
  55. qr_code = wxchat.get_login_qr_code(token_id)
  56. # print(qr_code)
  57. base64_string = qr_code.get('qrImgBase64')
  58. app_id = qr_code.get('appId')
  59. uuid = qr_code.get('uuid')
  60. print(f'appId: {app_id}')
  61. print(f'uuid: {uuid}')
  62. wxchat.qrCallback(uuid,base64_string)
  63. while True:
  64. res=wxchat.check_login(token_id,app_id,uuid)
  65. flag=res.get('status')
  66. if flag == 2:
  67. break
  68. time.sleep(3)
  69. print('登录成功')
  70. call_back_url="http://xgejpm.natappfree.cc/messages"
  71. res=wxchat.callback_collect(token_id,call_back_url)
  72. print(f'设置回调地址:{call_back_url}')
  73. print(token_id)
  74. print(app_id)
  75. wxchat.fetch_contacts_list(token_id, app_id)
  76. def start_wxchat_thread():
  77. gewe_chat.start()
  78. wxchat=gewe_chat.wxchat
  79. # token_id = wxchat.get_token_id()
  80. token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
  81. tel='18029274615'
  82. region_id='440000'
  83. print(f'tokenId: {token_id}')
  84. hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
  85. login_info=redis_helper.redis_helper.get_hash(hash_key)
  86. if not login_info:
  87. qr_code = wxchat.get_login_qr_code(token_id)
  88. # print(qr_code)
  89. base64_string = qr_code.get('qrImgBase64')
  90. app_id = qr_code.get('appId')
  91. uuid = qr_code.get('uuid')
  92. print(f'appId: {app_id}')
  93. print(f'uuid: {uuid}')
  94. wxchat.qrCallback(uuid,base64_string)
  95. while True:
  96. res=wxchat.check_login(token_id,app_id,uuid)
  97. flag=res.get('status')
  98. if flag == 2:
  99. print(res)
  100. login_info=res.get('loginInfo',{})
  101. login_info['appId'] = app_id
  102. login_info['uuid'] = uuid
  103. login_info['tokenId'] = token_id
  104. print(login_info)
  105. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  106. redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
  107. break
  108. time.sleep(3)
  109. # call_back_url="http://xgejpm.natappfree.cc/messages"
  110. # res=wxchat.callback_collect(token_id,call_back_url)
  111. # print(f'设置回调地址:{call_back_url}')
  112. print(token_id)
  113. print(app_id)
  114. contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
  115. friend_wxids=contacts_list['friends'][3:]
  116. print(friend_wxids)
  117. wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
  118. # friends_brief=wxchat.get_brief_info(token_id,app_id,friend_wxids)
  119. # utils.save_contacts_brief_to_redis(wxid,friends_brief)
  120. wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
  121. print(f'{wxid} 登录 {app_id} 成功')
  122. else:
  123. app_id=login_info.get('appId')
  124. token_id=login_info.get('tokenId')
  125. is_online=wxchat.check_online(token_id,app_id)
  126. if is_online:
  127. print("已经登录微信")
  128. else:
  129. # 尝试重连
  130. res=wxchat.reconnection(token_id,app_id)
  131. flag=res.get('ret')
  132. if flag==200:
  133. print(f'重连成功')
  134. else:
  135. # 删除缓存
  136. # redis_helper.redis_helper.delete_hash(hash_key)
  137. # 重新登录
  138. qr_code = wxchat.get_login_qr_code(token_id,app_id)
  139. # print(qr_code)
  140. base64_string = qr_code.get('qrImgBase64')
  141. app_id = qr_code.get('appId')
  142. uuid = qr_code.get('uuid')
  143. print(f'appId: {app_id}')
  144. print(f'uuid: {uuid}')
  145. wxchat.qrCallback(uuid,base64_string)
  146. while True:
  147. res=wxchat.check_login(token_id,app_id,uuid)
  148. flag=res.get('status')
  149. if flag == 2:
  150. print(res)
  151. login_info=res.get('loginInfo',{})
  152. login_info['appId'] = app_id
  153. login_info['uuid'] = uuid
  154. login_info['tokenId'] = token_id
  155. print(login_info)
  156. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  157. redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
  158. break
  159. time.sleep(3)
  160. print('重新登录成功')
  161. print(token_id)
  162. print(app_id)
  163. contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
  164. friend_wxids=contacts_list['friends'][3:]
  165. # friend_wxids=['wxid_95rrm8l6tznb21']
  166. wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
  167. wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
  168. print(f'{wxid} 登录 {app_id} 成功')
  169. #wxchat.post_text(token_id,app_id,'wxid_eigw91zpsl1p22','你好')
  170. def app_run():
  171. flask_app = Flask(__name__)
  172. # @flask_app.route('/silk/<filename>')
  173. # def serve_mp3(filename):
  174. # # 指定 audios 目录的路径
  175. # directory = 'silk'
  176. # # 检查文件是否存在
  177. # if not filename.endswith('.silk') or not os.path.isfile(os.path.join(directory, filename)):
  178. # return 'File not found', 404
  179. # # 使用 send_from_directory 发送文件
  180. # return send_from_directory(directory, filename, as_attachment=False)
  181. # @flask_app.route('/messages', methods=['POST'])
  182. # def gewe_message():
  183. # msg = request.get_json()
  184. # print(msg)
  185. # # PushContent = msg['Data']['PushContent']
  186. # # print(msg)
  187. # # print(PushContent)
  188. # return jsonify({'message': 'PushContent'})
  189. # api = Api(app)
  190. flask_api = Api(flask_app,errors=errors, catch_all_404s=True)
  191. # 设置日志(logger 已在 log.py 中配置)
  192. flask_app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
  193. flask_app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
  194. flask_app.logger.setLevel(logging.DEBUG) # 设置日志级别
  195. # 添加拦截器
  196. flask_app.before_request(before_request)
  197. flask_app.after_request(after_request)
  198. flask_app.register_error_handler(Exception, handle_exception)
  199. # 定义路由
  200. flask_api.add_resource(UserResource, '/user', '/user/<int:user_id>')
  201. flask_api.add_resource(MessagesResource, '/messages')
  202. load_config()
  203. worker()
  204. # channel = channel_factory.create_channel('wx')
  205. # channel.startup()
  206. environment = os.environ.get('environment', 'default') # 默认是生产环境
  207. port=5000
  208. if environment== 'default':
  209. port=80
  210. flask_app.run(debug=False,host='0.0.0.0',port=port)
  211. if __name__ == '__main__':
  212. app_run()