From 5a18bdc4fa51fbf293acf4f35af5cc425484e9ef Mon Sep 17 00:00:00 2001 From: H Vs Date: Mon, 24 Feb 2025 10:20:04 +0800 Subject: [PATCH] =?UTF-8?q?=E9=85=8D=E7=BD=AE=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 2 +- model/Models.py | 12 ++++++++++++ resources/config_reources.py | 32 +++++++++++++++++++++++--------- wechat/biz.py | 26 +++++++++++++++++++++----- 4 files changed, 57 insertions(+), 15 deletions(-) create mode 100644 model/Models.py diff --git a/app.py b/app.py index ec6d2d5..51f3814 100644 --- a/app.py +++ b/app.py @@ -139,7 +139,7 @@ def process_add_contacts_from_groups(wxchat:gewe_chat.GeWeChatCom,status, nickna logger.info(f'{nickname} 在 {chatroom_nickname} 群里还没添加的好友有:{[x.get("nickName") for x in remaining_chatroot_members]}') for m in remaining_chatroot_members: - ret, msg, data = wxchat.add_group_member_as_friend(token_id, app_id, chatroom_id, m.get('wxid'), f'您好,我是来自 {chatroom_nickname} 群的 {nickname}') + ret, msg, data = wxchat.add_group_member_as_friend(token_id, app_id, chatroom_id, m.get('wxid'), f'我是群聊"{chatroom_nickname}"群的{nickname}') logger.info(f'{nickname} 向 {chatroom_nickname} 群的 {m.get("nickName")} 发送好友邀请 {msg}') time.sleep(10) time.sleep(20) diff --git a/model/Models.py b/model/Models.py new file mode 100644 index 0000000..077269c --- /dev/null +++ b/model/Models.py @@ -0,0 +1,12 @@ +from pydantic import BaseModel, ValidationError +from dataclasses import dataclass, asdict +from typing import List + + +@dataclass +class AgentConfig(BaseModel): + chatroomIdWhiteList: List[str] = [] + agentTokenId: str + agentEnabled: bool + addContactsFromChatroomIdWhiteList: List[str] = [] + chatWaitingMsgEnabled: bool \ No newline at end of file diff --git a/resources/config_reources.py b/resources/config_reources.py index d845367..febb081 100644 --- a/resources/config_reources.py +++ b/resources/config_reources.py @@ -6,6 +6,7 @@ from wechat import gewe_chat from dataclasses import dataclass, asdict from typing import List import json +from model import Models @@ -17,16 +18,23 @@ class GetWxchatConfigResource(Resource): def post(self): req = request.get_json() wxid = req.get("wxid") + + k,loginfo=utils.get_login_info_by_wxid(wxid) + if not k: + response=jsonify({"code": 404, "message": f"{wxid} 没有对应的登录信息"}) + response.status_code = 404 + return response + config=self.wxchat.get_wxchat_config_from_cache(wxid) return jsonify(config) -@dataclass -class AgentConfig(BaseModel): - chatroomIdWhiteList: List[str] = [] - agentTokenId: str - agentEnabled: bool - addContactsFromChatroomIdWhiteList: List[str] = [] - chatWaitingMsgEnabled: bool +# @dataclass +# class AgentConfig(BaseModel): +# chatroomIdWhiteList: List[str] = [] +# agentTokenId: str +# agentEnabled: bool +# addContactsFromChatroomIdWhiteList: List[str] = [] +# chatWaitingMsgEnabled: bool class SaveWxchatConfigResource(Resource): def __init__(self): @@ -39,16 +47,22 @@ class SaveWxchatConfigResource(Resource): data = req.get("data") # hash_key="__AI_OPS_WX__:WXCHAT_CONFIG" # redis_helper.redis_helper.update_hash_field(hash_key, wxid, json.dumps(data,ensure_ascii=False)) - + k,loginfo=utils.get_login_info_by_wxid(wxid) + if not k: + response=jsonify({"code": 404, "message": f"{wxid} 没有对应的登录信息"}) + response.status_code = 404 + return response try: # 使用 Pydantic 严格校验数据类型和结构 - validated_config = AgentConfig.model_validate(data) + validated_config = Models.AgentConfig.model_validate(data) except ValidationError as e: response=jsonify({'code': 407, 'message': e.errors().__str__()}) response.status_code = 407 return response + + self.wxchat.save_wxchat_config(wxid, data) diff --git a/wechat/biz.py b/wechat/biz.py index e3c6db6..335754f 100644 --- a/wechat/biz.py +++ b/wechat/biz.py @@ -9,6 +9,8 @@ from datetime import datetime from wechat import gewe_chat +from model import Models + def wx_messages_process_callback(agent_tel,message): @@ -282,7 +284,7 @@ def start_kafka_consumer_thread(): consumer_thread.start() -def login_or_reconnect(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, region_id,hash_key, is_reconnect=False, max_retries=5): +def login_or_reconnect(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, region_id,agent_token_id,hash_key, is_reconnect=False, max_retries=5): """ 封装微信登录或重连的逻辑 """ @@ -342,6 +344,19 @@ def login_or_reconnect(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, region_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) wxchat.release_login_lock(token_id) + # 默认配置 + + config=Models.AgentConfig.model_validate({ + "chatroomIdWhiteList": [], + "agentTokenId": agent_token_id, + "agentEnabled": True, + "addContactsFromChatroomIdWhiteList": [], + "chatWaitingMsgEnabled": True + }) + + config_dict=config.model_dump() + + wxchat.save_wxchat_config(agent_tel,config_dict) return login_info else: logger.info(f"登录检查中: {ret}-{msg}-{res}") @@ -363,12 +378,12 @@ def fetch_and_save_contacts(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, hash print(f'微信ID {wxid} 登录APPID {app_id} 成功,联系人已保存') -def wx_login(wxchat:gewe_chat.GeWeChatCom,tel,token_id,region_id): +def wx_login(wxchat:gewe_chat.GeWeChatCom,tel,token_id,region_id,agent_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, '', region_id,hash_key) + login_info = login_or_reconnect(wxchat, token_id, '', region_id,agent_token_id,hash_key) else: app_id = login_info.get('appId') token_id = login_info.get('tokenId') @@ -386,7 +401,7 @@ def wx_login(wxchat:gewe_chat.GeWeChatCom,tel,token_id,region_id): else: print("重连失败,重新登录...") - login_info = login_or_reconnect(wxchat, token_id, app_id, region_id,hash_key, is_reconnect=True) + login_info = login_or_reconnect(wxchat, token_id, app_id, region_id,agent_token_id,hash_key, is_reconnect=True) if login_info: fetch_and_save_contacts(wxchat, token_id, login_info.get('appId'), hash_key) @@ -420,6 +435,7 @@ def ops_messages_process(message): tel=content_data.get('tel', '18029274615') token_id=content_data.get('token_id', 'f828cb3c-1039-489f-b9ae-7494d1778a15') region_id=content_data.get('region_id', '440000') + agent_token_id=content_data.get('agent_token_id', '') loginfo=gewe_chat.wxchat.get_login_info_from_cache(tel) print(loginfo) status=loginfo.get('status','0') @@ -429,7 +445,7 @@ def ops_messages_process(message): return flag=gewe_chat.wxchat.acquire_login_lock(token_id,800) if flag: - thread = threading.Thread(target=wx_login, args=(wxchat,tel,token_id,region_id)) + thread = threading.Thread(target=wx_login, args=(wxchat,tel,token_id,region_id,agent_token_id)) thread.daemon = True thread.start() else: