提交代码调整。
This commit is contained in:
@@ -13,6 +13,7 @@ from db.connection import DBConnectionManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ContactsDBOperator(BaseDBOperator):
|
||||
"""微信联系人数据库操作类"""
|
||||
|
||||
@@ -21,8 +22,6 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
super().__init__(db_manager or DBConnectionManager.get_instance())
|
||||
self.logger = logging.getLogger("ContactsDBOperator")
|
||||
|
||||
# 确保数据库表存在
|
||||
# self._ensure_table_exists()
|
||||
|
||||
def _ensure_table_exists(self):
|
||||
"""确保联系人表存在"""
|
||||
@@ -132,7 +131,8 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
'description': contact.get('description', ''),
|
||||
'card_img_url': contact.get('cardImgUrl', ''),
|
||||
'label_list': contact.get('labelList', ''),
|
||||
'phone_num_list': json.dumps(contact.get('phoneNumList', [])) if contact.get('phoneNumList') else '',
|
||||
'phone_num_list': json.dumps(contact.get('phoneNumList', [])) if contact.get(
|
||||
'phoneNumList') else '',
|
||||
'type': contact_type
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,8 @@ class MessageStorageDB(BaseDBOperator):
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
params = (
|
||||
msg.roomid, now_time, msg.sender, msg.content, msg.msg_type, msg.content, msg.msg_id, msg.msg_source, "")
|
||||
msg.roomid, now_time, msg.sender, msg.content, msg.msg_type, msg.content.xml_content, msg.msg_id,
|
||||
msg.msg_source, "")
|
||||
result = self.execute_update(sql, params)
|
||||
return result
|
||||
|
||||
|
||||
1
gewechat/call_back_message/Gewechat.apifox.json
Normal file
1
gewechat/call_back_message/Gewechat.apifox.json
Normal file
File diff suppressed because one or more lines are too long
4616
gewechat/call_back_message/Gewechat.md
Normal file
4616
gewechat/call_back_message/Gewechat.md
Normal file
File diff suppressed because one or more lines are too long
18
gewechat/client/fetchContactsList.py
Normal file
18
gewechat/client/fetchContactsList.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import requests
|
||||
import json
|
||||
|
||||
url = "/contacts/fetchContactsList"
|
||||
|
||||
base_url="http://192.168.2.240:2531/v2/api"
|
||||
payload = json.dumps({
|
||||
"appId": "wx_3BC6eSHGE5xEm_hH3__7c"
|
||||
})
|
||||
|
||||
headers = {
|
||||
'X-GEWE-TOKEN': 'cb43f52db27e4a56bb6ec7da54373582',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
response = requests.request("POST", base_url+url, headers=headers, data=payload)
|
||||
|
||||
print(response.text)
|
||||
@@ -121,6 +121,3 @@ class MessageUtil:
|
||||
members = {member["wxid"]: member["nickName"] for member in data["data"]["memberList"]}
|
||||
return members
|
||||
|
||||
def download_file_from_url(self, url: str, target_dir: str) -> str:
|
||||
# 根据获取的文件地址,从server 下载 :http://{服务ip}:2532/download/{接口返回的文件路径}
|
||||
return ""
|
||||
|
||||
81
robot.py
81
robot.py
@@ -34,6 +34,8 @@ from xiuren.xiuren_pdf import generate_pdf_from_images
|
||||
from db.connection import DBConnectionManager
|
||||
from message_util import MessageUtil
|
||||
|
||||
from db.contacts_db import ContactsDBOperator
|
||||
|
||||
|
||||
class Robot(Job):
|
||||
"""个性化自己的机器人
|
||||
@@ -104,6 +106,7 @@ class Robot(Job):
|
||||
# 消息存档模块初始化,自动完成入库动作
|
||||
self.message_storage = MessageStorage(self.client)
|
||||
|
||||
self.contacts_db = ContactsDBOperator(self.db_manager)
|
||||
@staticmethod
|
||||
def value_check(args: dict) -> bool:
|
||||
if args:
|
||||
@@ -404,25 +407,56 @@ class Robot(Job):
|
||||
self.LOG.error(f"xiu_ren_pdf_send error:{e}")
|
||||
|
||||
def get_all_contacts(self) -> dict:
|
||||
"""获取所有联系人信息并保存到数据库"""
|
||||
from db.contacts_db import ContactsDBOperator
|
||||
|
||||
"""获取所有联系人信息并返回字典格式 {wxid: nickname}"""
|
||||
try:
|
||||
contacts_dict = {}
|
||||
# 获取所有联系人的wxid列表
|
||||
contacts_wxids = self.client.fetch_contacts_list(self.app_id)
|
||||
self.LOG.info(f"contacts_wxids: {contacts_wxids}")
|
||||
if not contacts_wxids:
|
||||
self.LOG.warning("获取联系人列表为空")
|
||||
# 获取所有联系人列表
|
||||
response = self.client.fetch_contacts_list(self.app_id)
|
||||
self.LOG.info(f"获取联系人列表响应: {response}")
|
||||
|
||||
if not response or response.get("ret") != 200:
|
||||
self.LOG.warning(f"获取联系人列表失败: {response}")
|
||||
return contacts_dict
|
||||
|
||||
# 初始化联系人数据库操作类
|
||||
contacts_db = ContactsDBOperator()
|
||||
# 从响应中提取联系人数据
|
||||
contact_data = response.get("data", {})
|
||||
|
||||
# 处理好友列表
|
||||
friends = contact_data.get("friends", [])
|
||||
for wxid in friends:
|
||||
contacts_dict[wxid] = wxid # 默认使用wxid作为昵称
|
||||
|
||||
# 处理群聊列表
|
||||
chatrooms = contact_data.get("chatrooms", [])
|
||||
for chatroom_id in chatrooms:
|
||||
contacts_dict[chatroom_id] = chatroom_id
|
||||
# 如果是群聊,则获取群成员信息
|
||||
self.update_chatroom_member_details(chatroom_id)
|
||||
|
||||
# 处理公众号列表
|
||||
ghs = contact_data.get("ghs", [])
|
||||
for gh_id in ghs:
|
||||
contacts_dict[gh_id] = gh_id
|
||||
|
||||
# 获取联系人详细信息(昵称等)
|
||||
self.update_contact_details(contacts_dict)
|
||||
|
||||
self.LOG.info(f"成功获取并保存{len(contacts_dict)}个联系人信息")
|
||||
return contacts_dict
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"获取联系人信息失败: {e}")
|
||||
return {}
|
||||
|
||||
def update_contact_details(self, contacts_dict):
|
||||
"""更新联系人详细信息(昵称等)"""
|
||||
try:
|
||||
# 将wxid列表分批处理,每批50个
|
||||
batch_size = 50
|
||||
for i in range(0, len(contacts_wxids), batch_size):
|
||||
batch_wxids = contacts_wxids[i:i + batch_size]
|
||||
wxids = list(contacts_dict.keys())
|
||||
|
||||
for i in range(0, len(wxids), batch_size):
|
||||
batch_wxids = wxids[i:i + batch_size]
|
||||
|
||||
# 批量获取联系人详细信息
|
||||
contact_info = self.client.get_detail_info(self.app_id, batch_wxids)
|
||||
@@ -434,24 +468,22 @@ class Robot(Job):
|
||||
if contact_data:
|
||||
for contact in contact_data:
|
||||
user_name = contact.get("userName")
|
||||
if not user_name:
|
||||
if not user_name or user_name not in contacts_dict:
|
||||
continue
|
||||
|
||||
# 更新昵称
|
||||
contacts_dict[user_name] = contact.get("nickName") or user_name
|
||||
|
||||
try:
|
||||
# 判断联系人类型
|
||||
contact_type = "friends" # 默认为好友类型
|
||||
if user_name.endswith("@chatroom"):
|
||||
contact_type = "chatrooms"
|
||||
# 如果是群聊,则获取群成员信息
|
||||
self.update_chatroom_member_details(user_name)
|
||||
elif user_name.startswith("gh_"):
|
||||
contact_type = "ghs"
|
||||
|
||||
# 保存到数据库
|
||||
contacts_db.save_contacts([contact], contact_type)
|
||||
|
||||
# 添加到返回字典
|
||||
contacts_dict[user_name] = contact.get("nickName") or user_name
|
||||
self.contacts_db.save_contacts([contact], contact_type)
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理联系人 {user_name} 失败: {e}")
|
||||
@@ -459,12 +491,8 @@ class Robot(Job):
|
||||
else:
|
||||
self.LOG.error(f"获取联系人详情失败: {contact_info}")
|
||||
|
||||
self.LOG.info(f"成功获取并保存{len(contacts_dict)}个联系人信息")
|
||||
return contacts_dict
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"获取联系人信息失败: {e}")
|
||||
return {}
|
||||
self.LOG.error(f"更新联系人详细信息失败: {e}")
|
||||
|
||||
def update_chatroom_member_details(self, chatroom_id):
|
||||
"""更新群成员详细信息"""
|
||||
@@ -485,10 +513,7 @@ class Robot(Job):
|
||||
member_wxids # 直接传递列表,不需要转换为集合
|
||||
)
|
||||
|
||||
# 使用ContactsDBOperator处理响应
|
||||
from db.contacts_db import ContactsDBOperator
|
||||
contacts_db = ContactsDBOperator()
|
||||
success = contacts_db.process_chatroom_member_detail_response(chatroom_id, details_response)
|
||||
success = self.contacts_db.process_chatroom_member_detail_response(chatroom_id, details_response)
|
||||
|
||||
if success:
|
||||
self.LOG.info(f"成功更新群聊{chatroom_id}的成员详细信息")
|
||||
|
||||
@@ -234,7 +234,6 @@ class ContactManager:
|
||||
# "province": cnt.get("province", ""),
|
||||
# "city": cnt.get("city", ""),
|
||||
# "gender": gender}
|
||||
self._friends = self.message_util.get_friends()
|
||||
self._logger.info(f"联系人信息已刷新,共 {len(new_contacts)} 个联系人")
|
||||
self._classify_contacts()
|
||||
|
||||
|
||||
@@ -134,19 +134,18 @@ class MessageStorage:
|
||||
# 解析JSON
|
||||
if json and json.get('data') and json['data'].get('fileUrl'):
|
||||
file_url = json['data']['fileUrl']
|
||||
download_path = self.download_file_from_url(file_url, target_dir)
|
||||
if download_path:
|
||||
logger.info(f"使用wcf下载图片成功: {msg.msg_id} -> {download_path}")
|
||||
|
||||
if file_url:
|
||||
logger.info(f"记录gewe服务端图片路径成功: {msg.msg_id} -> {file_url}")
|
||||
# 后续如果需要使用,则去服务器端提取图片
|
||||
# 直接使用下载后的路径更新数据库
|
||||
self.message_db.update_message_image_path(msg.msg_id, download_path)
|
||||
self.message_db.update_message_image_path(msg.msg_id, file_url)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'message_id': msg.msg_id,
|
||||
'roomid': msg.roomid,
|
||||
'sender': msg.sender,
|
||||
'file_path': download_path
|
||||
'file_path': file_url
|
||||
}
|
||||
else:
|
||||
return {
|
||||
@@ -162,7 +161,7 @@ class MessageStorage:
|
||||
'message_id': msg.msg_id,
|
||||
'roomid': msg.roomid,
|
||||
'sender': msg.sender,
|
||||
'error': "WCF实例不存在或消息ID无效"
|
||||
'error': "实例不存在或消息ID无效"
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"图片处理出错: {msg.msg_id}, 错误: {e}")
|
||||
@@ -174,10 +173,6 @@ class MessageStorage:
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def download_file_from_url(self, url: str, target_dir: str) -> str:
|
||||
# TODO 根据获取的文件地址,从server 下载 :http://{服务ip}:2532/download/{接口返回的文件路径}
|
||||
return ""
|
||||
|
||||
def _process_image_callback(self, future):
|
||||
"""处理异步图片处理任务完成后的回调"""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user