|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- 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 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.fetch_contacts_list(token_id,app_id)
-
- # # wxchat.get_detail_info(token_id,app_id,["wxid_qycp69orck8412"])
-
- def login_or_reconnect(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, hash_key, is_reconnect=False):
- """
- 封装微信登录或重连的逻辑
- """
- if is_reconnect:
- print("尝试重连...")
- else:
- print("获取二维码进行登录...")
-
- qr_code = wxchat.get_login_qr_code(token_id, app_id)
- base64_string = qr_code.get('qrImgBase64')
- uuid = qr_code.get('uuid')
-
- app_id = app_id or qr_code.get('appId')
-
- wxchat.qrCallback(uuid, base64_string)
-
- while True:
- res = wxchat.check_login(token_id, app_id, uuid)
- flag = res.get('status')
- if flag == 2:
- print(f"登录成功: {res}")
- login_info = res.get('loginInfo', {})
- login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id})
-
- 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)
- return login_info
- time.sleep(3)
-
- def fetch_and_save_contacts(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, hash_key):
- """
- 获取联系人列表并保存到缓存
- """
- contacts_list = wxchat.fetch_contacts_list(token_id, app_id)
- friend_wxids = contacts_list['friends'][3:] # 可以调整截取范围
- 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'微信ID {wxid} 登录APPID {app_id} 成功,联系人已保存')
-
- def start_wxchat_thread():
- gewe_chat.start()
- wxchat = gewe_chat.wxchat
- # token_id = 'f828cb3c-1039-489f-b9ae-7494d1778a15'
- # tel = '18029274615'
- tel=os.environ.get('tel', '18029274615')
- token_id=os.environ.get('tokenId', 'f828cb3c-1039-489f-b9ae-7494d1778a15')
-
-
- # tel=os.environ.get('tel', '19200137635')
- # token_id=os.environ.get('tokenId', '9ba29f73-e46a-40b5-873d-795490f732e3')
-
- # 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:
- login_info = login_or_reconnect(wxchat, token_id, '', hash_key)
- else:
- app_id = login_info.get('appId')
- token_id = login_info.get('tokenId')
- wxid= login_info.get('wxid')
- # 检查是否已经登录
- is_online = wxchat.check_online(token_id, app_id)
- if is_online:
- logger.info(f'微信ID {wxid} 在APPID {app_id} 已经在线')
- else:
- # 尝试重连
- res = wxchat.reconnection(token_id, app_id)
- if res.get('ret') == 200:
- logger.info(f'微信ID {wxid} 在APPID {app_id} 重连成功')
- else:
- print("重连失败,重新登录...")
- login_info = login_or_reconnect(wxchat, token_id, app_id, hash_key, is_reconnect=True)
-
- fetch_and_save_contacts(wxchat, token_id, login_info.get('appId'), hash_key)
-
-
- def app_run():
-
- flask_app = Flask(__name__)
-
- # 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()
|