Przeglądaj źródła

配置验证

develop
H Vs 2 miesięcy temu
rodzic
commit
5a18bdc4fa
4 zmienionych plików z 57 dodań i 15 usunięć
  1. +1
    -1
      app.py
  2. +12
    -0
      model/Models.py
  3. +23
    -9
      resources/config_reources.py
  4. +21
    -5
      wechat/biz.py

+ 1
- 1
app.py Wyświetl plik

@@ -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]}') logger.info(f'{nickname} 在 {chatroom_nickname} 群里还没添加的好友有:{[x.get("nickName") for x in remaining_chatroot_members]}')
for m 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}') logger.info(f'{nickname} 向 {chatroom_nickname} 群的 {m.get("nickName")} 发送好友邀请 {msg}')
time.sleep(10) time.sleep(10)
time.sleep(20) time.sleep(20)


+ 12
- 0
model/Models.py Wyświetl plik

@@ -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

+ 23
- 9
resources/config_reources.py Wyświetl plik

@@ -6,6 +6,7 @@ from wechat import gewe_chat
from dataclasses import dataclass, asdict from dataclasses import dataclass, asdict
from typing import List from typing import List
import json import json
from model import Models






@@ -17,16 +18,23 @@ class GetWxchatConfigResource(Resource):
def post(self): def post(self):
req = request.get_json() req = request.get_json()
wxid = req.get("wxid") 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) config=self.wxchat.get_wxchat_config_from_cache(wxid)
return jsonify(config) 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): class SaveWxchatConfigResource(Resource):
def __init__(self): def __init__(self):
@@ -39,16 +47,22 @@ class SaveWxchatConfigResource(Resource):
data = req.get("data") data = req.get("data")
# hash_key="__AI_OPS_WX__:WXCHAT_CONFIG" # hash_key="__AI_OPS_WX__:WXCHAT_CONFIG"
# redis_helper.redis_helper.update_hash_field(hash_key, wxid, json.dumps(data,ensure_ascii=False)) # 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: try:
# 使用 Pydantic 严格校验数据类型和结构 # 使用 Pydantic 严格校验数据类型和结构
validated_config = AgentConfig.model_validate(data)
validated_config = Models.AgentConfig.model_validate(data)
except ValidationError as e: except ValidationError as e:


response=jsonify({'code': 407, 'message': e.errors().__str__()}) response=jsonify({'code': 407, 'message': e.errors().__str__()})
response.status_code = 407 response.status_code = 407
return response return response




self.wxchat.save_wxchat_config(wxid, data) self.wxchat.save_wxchat_config(wxid, data)

+ 21
- 5
wechat/biz.py Wyświetl plik

@@ -9,6 +9,8 @@ from datetime import datetime


from wechat import gewe_chat from wechat import gewe_chat


from model import Models





def wx_messages_process_callback(agent_tel,message): def wx_messages_process_callback(agent_tel,message):
@@ -282,7 +284,7 @@ def start_kafka_consumer_thread():
consumer_thread.start() 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()} 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) redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
wxchat.release_login_lock(token_id) 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 return login_info
else: else:
logger.info(f"登录检查中: {ret}-{msg}-{res}") 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} 成功,联系人已保存') 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}" hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
login_info = redis_helper.redis_helper.get_hash(hash_key) login_info = redis_helper.redis_helper.get_hash(hash_key)


if not login_info: 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: else:
app_id = login_info.get('appId') app_id = login_info.get('appId')
token_id = login_info.get('tokenId') token_id = login_info.get('tokenId')
@@ -386,7 +401,7 @@ def wx_login(wxchat:gewe_chat.GeWeChatCom,tel,token_id,region_id):
else: else:
print("重连失败,重新登录...") 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: if login_info:
fetch_and_save_contacts(wxchat, token_id, login_info.get('appId'), hash_key) 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') tel=content_data.get('tel', '18029274615')
token_id=content_data.get('token_id', 'f828cb3c-1039-489f-b9ae-7494d1778a15') token_id=content_data.get('token_id', 'f828cb3c-1039-489f-b9ae-7494d1778a15')
region_id=content_data.get('region_id', '440000') 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) loginfo=gewe_chat.wxchat.get_login_info_from_cache(tel)
print(loginfo) print(loginfo)
status=loginfo.get('status','0') status=loginfo.get('status','0')
@@ -429,7 +445,7 @@ def ops_messages_process(message):
return return
flag=gewe_chat.wxchat.acquire_login_lock(token_id,800) flag=gewe_chat.wxchat.acquire_login_lock(token_id,800)
if flag: 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.daemon = True
thread.start() thread.start()
else: else:


Ładowanie…
Anuluj
Zapisz