ソースを参照

配置验证

develop
H Vs 2ヶ月前
コミット
5a18bdc4fa
4個のファイルの変更57行の追加15行の削除
  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 ファイルの表示

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


+ 12
- 0
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

+ 23
- 9
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)

+ 21
- 5
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:


読み込み中…
キャンセル
保存