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

3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 worker():
  33. kafka_helper.start()
  34. redis_helper.start()
  35. start_wxchat_thread()
  36. start_kafka_consumer_thread()
  37. def start_wxchat_thread_free():
  38. gewe_chat.start()
  39. wxchat=gewe_chat.wxchat
  40. token_id = wxchat.get_token_id()
  41. # token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
  42. print(f'tokenId: {token_id}')
  43. qr_code = wxchat.get_login_qr_code(token_id)
  44. # print(qr_code)
  45. base64_string = qr_code.get('qrImgBase64')
  46. app_id = qr_code.get('appId')
  47. uuid = qr_code.get('uuid')
  48. print(f'appId: {app_id}')
  49. print(f'uuid: {uuid}')
  50. wxchat.qrCallback(uuid,base64_string)
  51. while True:
  52. res=wxchat.check_login(token_id,app_id,uuid)
  53. flag=res.get('status')
  54. if flag == 2:
  55. break
  56. time.sleep(3)
  57. print('登录成功')
  58. call_back_url="http://xgejpm.natappfree.cc/messages"
  59. res=wxchat.callback_collect(token_id,call_back_url)
  60. print(f'设置回调地址:{call_back_url}')
  61. print(token_id)
  62. print(app_id)
  63. wxchat.fetch_contacts_list(token_id, app_id)
  64. # def start_wxchat_thread():
  65. # gewe_chat.start()
  66. # wxchat=gewe_chat.wxchat
  67. # # token_id = wxchat.get_token_id()
  68. # token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
  69. # tel='18029274615'
  70. # region_id='440000'
  71. # print(f'tokenId: {token_id}')
  72. # hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
  73. # login_info=redis_helper.redis_helper.get_hash(hash_key)
  74. # if not login_info:
  75. # qr_code = wxchat.get_login_qr_code(token_id)
  76. # # print(qr_code)
  77. # base64_string = qr_code.get('qrImgBase64')
  78. # app_id = qr_code.get('appId')
  79. # uuid = qr_code.get('uuid')
  80. # # print(f'appId: {app_id}')
  81. # # print(f'uuid: {uuid}')
  82. # wxchat.qrCallback(uuid,base64_string)
  83. # while True:
  84. # res=wxchat.check_login(token_id,app_id,uuid)
  85. # flag=res.get('status')
  86. # if flag == 2:
  87. # print(res)
  88. # login_info=res.get('loginInfo',{})
  89. # login_info['appId'] = app_id
  90. # login_info['uuid'] = uuid
  91. # login_info['tokenId'] = token_id
  92. # print(login_info)
  93. # cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  94. # redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
  95. # break
  96. # time.sleep(3)
  97. # # call_back_url="http://xgejpm.natappfree.cc/messages"
  98. # # res=wxchat.callback_collect(token_id,call_back_url)
  99. # # print(f'设置回调地址:{call_back_url}')
  100. # print(token_id)
  101. # print(app_id)
  102. # contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
  103. # friend_wxids=contacts_list['friends'][3:]
  104. # print(friend_wxids)
  105. # wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
  106. # # friends_brief=wxchat.get_brief_info(token_id,app_id,friend_wxids)
  107. # # utils.save_contacts_brief_to_redis(wxid,friends_brief)
  108. # wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
  109. # print(f'{wxid} 登录 {app_id} 成功')
  110. # else:
  111. # app_id=login_info.get('appId')
  112. # token_id=login_info.get('tokenId')
  113. # is_online=wxchat.check_online(token_id,app_id)
  114. # if is_online:
  115. # print("已经登录微信")
  116. # else:
  117. # # 尝试重连
  118. # res=wxchat.reconnection(token_id,app_id)
  119. # flag=res.get('ret')
  120. # if flag==200:
  121. # print(f'重连成功')
  122. # else:
  123. # # 删除缓存
  124. # # redis_helper.redis_helper.delete_hash(hash_key)
  125. # # 重新登录
  126. # qr_code = wxchat.get_login_qr_code(token_id,app_id)
  127. # # print(qr_code)
  128. # base64_string = qr_code.get('qrImgBase64')
  129. # app_id = qr_code.get('appId')
  130. # uuid = qr_code.get('uuid')
  131. # print(f'appId: {app_id}')
  132. # print(f'uuid: {uuid}')
  133. # wxchat.qrCallback(uuid,base64_string)
  134. # while True:
  135. # res=wxchat.check_login(token_id,app_id,uuid)
  136. # flag=res.get('status')
  137. # if flag == 2:
  138. # print(res)
  139. # login_info=res.get('loginInfo',{})
  140. # login_info['appId'] = app_id
  141. # login_info['uuid'] = uuid
  142. # login_info['tokenId'] = token_id
  143. # print(login_info)
  144. # cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  145. # redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
  146. # break
  147. # time.sleep(3)
  148. # print('重新登录成功')
  149. # print(token_id)
  150. # print(app_id)
  151. # contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
  152. # friend_wxids=contacts_list['friends'][3:]
  153. # # friend_wxids=['wxid_95rrm8l6tznb21']
  154. # wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
  155. # wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
  156. # print(f'{wxid} 登录 {app_id} 成功')
  157. # # wxchat.fetch_contacts_list(token_id,app_id)
  158. # # wxchat.get_detail_info(token_id,app_id,["wxid_qycp69orck8412"])
  159. def login_or_reconnect(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, hash_key, is_reconnect=False):
  160. """
  161. 封装微信登录或重连的逻辑
  162. """
  163. if is_reconnect:
  164. print("尝试重连...")
  165. else:
  166. print("获取二维码进行登录...")
  167. qr_code = wxchat.get_login_qr_code(token_id, app_id)
  168. base64_string = qr_code.get('qrImgBase64')
  169. uuid = qr_code.get('uuid')
  170. app_id = app_id or qr_code.get('appId')
  171. wxchat.qrCallback(uuid, base64_string)
  172. while True:
  173. res = wxchat.check_login(token_id, app_id, uuid)
  174. flag = res.get('status')
  175. if flag == 2:
  176. print(f"登录成功: {res}")
  177. login_info = res.get('loginInfo', {})
  178. login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id})
  179. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  180. redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
  181. return login_info
  182. time.sleep(3)
  183. def fetch_and_save_contacts(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, hash_key):
  184. """
  185. 获取联系人列表并保存到缓存
  186. """
  187. contacts_list = wxchat.fetch_contacts_list(token_id, app_id)
  188. friend_wxids = contacts_list['friends'][3:] # 可以调整截取范围
  189. wxid = redis_helper.redis_helper.get_hash_field(hash_key, 'wxid')
  190. wxchat.save_contacts_brief_to_cache(token_id, app_id, wxid, friend_wxids)
  191. print(f'微信ID {wxid} 登录APPID {app_id} 成功,联系人已保存')
  192. def start_wxchat_thread():
  193. gewe_chat.start()
  194. wxchat = gewe_chat.wxchat
  195. # token_id = 'f828cb3c-1039-489f-b9ae-7494d1778a15'
  196. # tel = '18029274615'
  197. tel=os.environ.get('tel', '18029274615')
  198. token_id=os.environ.get('tokenId', 'f828cb3c-1039-489f-b9ae-7494d1778a15')
  199. # tel=os.environ.get('tel', '19200137635')
  200. # token_id=os.environ.get('tokenId', '9ba29f73-e46a-40b5-873d-795490f732e3')
  201. # region_id = '440000'
  202. # print(f'tokenId: {token_id}')
  203. hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
  204. login_info = redis_helper.redis_helper.get_hash(hash_key)
  205. if not login_info:
  206. login_info = login_or_reconnect(wxchat, token_id, '', hash_key)
  207. else:
  208. app_id = login_info.get('appId')
  209. token_id = login_info.get('tokenId')
  210. wxid= login_info.get('wxid')
  211. # 检查是否已经登录
  212. is_online = wxchat.check_online(token_id, app_id)
  213. if is_online:
  214. logger.info(f'微信ID {wxid} 在APPID {app_id} 已经在线')
  215. else:
  216. # 尝试重连
  217. res = wxchat.reconnection(token_id, app_id)
  218. if res.get('ret') == 200:
  219. logger.info(f'微信ID {wxid} 在APPID {app_id} 重连成功')
  220. else:
  221. print("重连失败,重新登录...")
  222. login_info = login_or_reconnect(wxchat, token_id, app_id, hash_key, is_reconnect=True)
  223. fetch_and_save_contacts(wxchat, token_id, login_info.get('appId'), hash_key)
  224. def app_run():
  225. flask_app = Flask(__name__)
  226. # api = Api(app)
  227. flask_api = Api(flask_app,errors=errors, catch_all_404s=True)
  228. # 设置日志(logger 已在 log.py 中配置)
  229. flask_app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
  230. flask_app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
  231. flask_app.logger.setLevel(logging.DEBUG) # 设置日志级别
  232. # 添加拦截器
  233. flask_app.before_request(before_request)
  234. flask_app.after_request(after_request)
  235. flask_app.register_error_handler(Exception, handle_exception)
  236. # 定义路由
  237. flask_api.add_resource(UserResource, '/user', '/user/<int:user_id>')
  238. flask_api.add_resource(MessagesResource, '/messages')
  239. load_config()
  240. worker()
  241. # channel = channel_factory.create_channel('wx')
  242. # channel.startup()
  243. environment = os.environ.get('environment', 'default')
  244. port=5000
  245. if environment== 'default':
  246. port=80
  247. flask_app.run(debug=False,host='0.0.0.0',port=port)
  248. if __name__ == '__main__':
  249. app_run()