|
- from flask import Flask, send_from_directory, request,jsonify
- from flask_restful import Api,got_request_exception
- from resources.user_resource import UserResource
- from resources.messages_resource import MessagesResource
- from common.log import logger, log_exception
- from common.interceptors import before_request, after_request, handle_exception
- import threading
- from common import kafka_helper, redis_helper,utils
-
- import logging
- from config import load_config
-
- from wechat.biz import start_kafka_consumer_thread
-
- from channel import channel_factory
-
- from wechat import gewe_chat
-
- import os,time,json
-
- from voice.ali.ali_voice import AliVoice
-
-
-
- # 自定义错误消息
- errors = {
- 'UserAlreadyExistsError': {
- 'message': "A user with that username already exists.",
- 'status': 409,
- },
- 'ResourceDoesNotExist': {
- 'message': "A resource with that ID no longer exists.",
- 'status': 410,
- 'extra': "Any extra information you want.",
- },
- }
-
- def save_friends_to_redis(wxid, friends):
- # 将联系人信息保存到 Redis,使用一个合适的 key
- hash_key = f"__AI_OPS_WX__:CONTACTS_BRIEF:{wxid}"
- redis_helper.redis_helper.set_hash(hash_key,{"data":json.dumps(friends,ensure_ascii=False)})
-
- # def save_contacts_brief_to_redis(wxid, friends):
- # # 将联系人信息保存到 Redis,使用一个合适的 key
- # hash_key = f"__AI_OPS_WX__:CONTACTS_BRIEF:{wxid}"
-
- # # 获取缓存中的数据,如果缓存不存在则初始化为空列表
- # cache_str = redis_helper.redis_helper.get_hash_field(hash_key, "data")
- # cache = json.loads(cache_str) if cache_str else []
-
- # # 合并联系人信息
- # cache.extend(friends)
-
- # # 将合并后的联系人数据保存回 Redis
- # redis_helper.redis_helper.update_hash_field(hash_key, "data", {
- # "data": json.dumps(cache, ensure_ascii=False)
- # })
-
-
- def worker():
- kafka_helper.start()
- redis_helper.start()
-
- start_wxchat_thread()
- start_kafka_consumer_thread()
-
- def start_wxchat_thread_free():
- gewe_chat.start()
- wxchat=gewe_chat.wxchat
- token_id = wxchat.get_token_id()
- # token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
- print(f'tokenId: {token_id}')
-
- qr_code = wxchat.get_login_qr_code(token_id)
- # print(qr_code)
- base64_string = qr_code.get('qrImgBase64')
- app_id = qr_code.get('appId')
- uuid = qr_code.get('uuid')
- print(f'appId: {app_id}')
- print(f'uuid: {uuid}')
-
- wxchat.qrCallback(uuid,base64_string)
-
- while True:
- res=wxchat.check_login(token_id,app_id,uuid)
- flag=res.get('status')
- if flag == 2:
- break
- time.sleep(3)
-
- print('登录成功')
- call_back_url="http://xgejpm.natappfree.cc/messages"
- res=wxchat.callback_collect(token_id,call_back_url)
- print(f'设置回调地址:{call_back_url}')
- print(token_id)
- print(app_id)
-
- wxchat.fetch_contacts_list(token_id, app_id)
-
- def start_wxchat_thread():
- gewe_chat.start()
- wxchat=gewe_chat.wxchat
- # token_id = wxchat.get_token_id()
- token_id='f828cb3c-1039-489f-b9ae-7494d1778a15'
- tel='18029274615'
- region_id='440000'
- print(f'tokenId: {token_id}')
-
- hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
- login_info=redis_helper.redis_helper.get_hash(hash_key)
- if not login_info:
- qr_code = wxchat.get_login_qr_code(token_id)
- # print(qr_code)
- base64_string = qr_code.get('qrImgBase64')
- app_id = qr_code.get('appId')
- uuid = qr_code.get('uuid')
- print(f'appId: {app_id}')
- print(f'uuid: {uuid}')
- wxchat.qrCallback(uuid,base64_string)
- while True:
- res=wxchat.check_login(token_id,app_id,uuid)
- flag=res.get('status')
- if flag == 2:
- print(res)
- login_info=res.get('loginInfo',{})
- login_info['appId'] = app_id
- login_info['uuid'] = uuid
- login_info['tokenId'] = token_id
- print(login_info)
- cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
- redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
- break
- time.sleep(3)
-
-
- # call_back_url="http://xgejpm.natappfree.cc/messages"
- # res=wxchat.callback_collect(token_id,call_back_url)
- # print(f'设置回调地址:{call_back_url}')
- print(token_id)
- print(app_id)
- contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
-
- friend_wxids=contacts_list['friends'][3:]
- print(friend_wxids)
- wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
- # friends_brief=wxchat.get_brief_info(token_id,app_id,friend_wxids)
- # utils.save_contacts_brief_to_redis(wxid,friends_brief)
- wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
- print(f'{wxid} 登录 {app_id} 成功')
- else:
- app_id=login_info.get('appId')
- token_id=login_info.get('tokenId')
-
- is_online=wxchat.check_online(token_id,app_id)
- if is_online:
- print("已经登录微信")
- else:
- # 尝试重连
- res=wxchat.reconnection(token_id,app_id)
- flag=res.get('ret')
- if flag==200:
- print(f'重连成功')
- else:
- # 删除缓存
- # redis_helper.redis_helper.delete_hash(hash_key)
- # 重新登录
- qr_code = wxchat.get_login_qr_code(token_id,app_id)
- # print(qr_code)
- base64_string = qr_code.get('qrImgBase64')
- app_id = qr_code.get('appId')
- uuid = qr_code.get('uuid')
- print(f'appId: {app_id}')
- print(f'uuid: {uuid}')
- wxchat.qrCallback(uuid,base64_string)
- while True:
- res=wxchat.check_login(token_id,app_id,uuid)
- flag=res.get('status')
- if flag == 2:
- print(res)
- login_info=res.get('loginInfo',{})
- login_info['appId'] = app_id
- login_info['uuid'] = uuid
- login_info['tokenId'] = token_id
- print(login_info)
- cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
- redis_helper.redis_helper.set_hash(hash_key,cleaned_login_info)
- break
- time.sleep(3)
-
- print('重新登录成功')
- print(token_id)
- print(app_id)
-
- contacts_list=wxchat.fetch_contacts_list(token_id, app_id)
- friend_wxids=contacts_list['friends'][3:]
- # friend_wxids=['wxid_95rrm8l6tznb21']
- wxid=redis_helper.redis_helper.get_hash_field(hash_key,'wxid')
- wxchat.save_contacts_brief_to_cache(token_id,app_id,wxid,friend_wxids)
- print(f'{wxid} 登录 {app_id} 成功')
- #wxchat.post_text(token_id,app_id,'wxid_eigw91zpsl1p22','你好')
-
- def app_run():
-
- flask_app = Flask(__name__)
-
- # @flask_app.route('/silk/<filename>')
- # def serve_mp3(filename):
- # # 指定 audios 目录的路径
- # directory = 'silk'
- # # 检查文件是否存在
- # if not filename.endswith('.silk') or not os.path.isfile(os.path.join(directory, filename)):
- # return 'File not found', 404
- # # 使用 send_from_directory 发送文件
- # return send_from_directory(directory, filename, as_attachment=False)
-
- # @flask_app.route('/messages', methods=['POST'])
- # def gewe_message():
- # msg = request.get_json()
- # print(msg)
- # # PushContent = msg['Data']['PushContent']
- # # print(msg)
-
- # # print(PushContent)
-
- # return jsonify({'message': 'PushContent'})
-
- # api = Api(app)
- flask_api = Api(flask_app,errors=errors, catch_all_404s=True)
-
- # 设置日志(logger 已在 log.py 中配置)
- flask_app.logger.handlers.clear() # 清除 Flask 默认的日志处理器
- flask_app.logger.addHandler(logger.handlers[1]) # 使用文件日志处理器
- flask_app.logger.setLevel(logging.DEBUG) # 设置日志级别
-
- # 添加拦截器
- flask_app.before_request(before_request)
- flask_app.after_request(after_request)
- flask_app.register_error_handler(Exception, handle_exception)
-
- # 定义路由
- flask_api.add_resource(UserResource, '/user', '/user/<int:user_id>')
-
- flask_api.add_resource(MessagesResource, '/messages')
-
- load_config()
- worker()
-
- # channel = channel_factory.create_channel('wx')
- # channel.startup()
- environment = os.environ.get('environment', 'default') # 默认是生产环境
- port=5000
- if environment== 'default':
- port=80
- flask_app.run(debug=False,host='0.0.0.0',port=port)
-
- if __name__ == '__main__':
- app_run()
|