优化一下message

This commit is contained in:
liuwei
2025-04-22 17:47:52 +08:00
parent 089fcdefd7
commit 2e4a426dcf
2 changed files with 41 additions and 27 deletions

View File

@@ -60,29 +60,28 @@ class MessageContent:
def __post_init__(self):
"""处理XML内容和清理发信人信息"""
# 处理XML内容
# 清理发信人信息
self.clean_content = self.clean_sender_info(self.raw_content)
if self.clean_content.startswith('<?xml') or self.clean_content.startswith('<msg'):
# 处理XML内容
if self.clean_content and (self.clean_content.startswith('<?xml') or self.clean_content.startswith('<msg')):
try:
self.xml_content = self.clean_content
except ET.ParseError:
self.xml_content = ""
pass
def clean_sender_info(self, content: str) -> str:
"""清理内容中的发信人信息"""
if not content:
return ""
import re
# 如果有发信人信息,优先使用发信人信息进行清理
if self.sender:
# 尝试移除发信人前缀包括昵称和wxid两种情况
patterns = [
f"^{self.sender}[:]\\s*\\n", # wxid格式
f"^[^\\n]+?\\({self.sender}\\)[:]\\s*\\n", # 昵称(wxid)格式
f"^[^\\n]+?<{self.sender}>[:]\\s*\\n", # 昵称<wxid>格式
f"^{re.escape(self.sender)}[:]\\s*\\n", # wxid格式
f"^[^\\n]+?\\({re.escape(self.sender)}\\)[:]\\s*\\n", # 昵称(wxid)格式
f"^[^\\n]+?<{re.escape(self.sender)}>[:]\\s*\\n", # 昵称<wxid>格式
]
for pattern in patterns:
content = re.sub(pattern, '', content)
@@ -148,7 +147,7 @@ class WxMessage:
msg_id: int
sender: str
to_user: str
roomid: str # 新增room_id属性
roomid: str # 群聊ID
msg_type: MessageType
content: MessageContent
create_time: int
@@ -175,7 +174,6 @@ class WxMessage:
actual_sender = from_user
if is_group_chat and content_str:
# 从消息内容中提取真正的发送人
# 简化逻辑:直接通过冒号分割获取发送人
parts = content_str.split(':', 1) # 只分割第一个冒号
if len(parts) > 1:
# 提取发送人ID冒号前的部分
@@ -195,7 +193,7 @@ class WxMessage:
msg_id=data.get("MsgId", 0),
sender=actual_sender, # 使用提取出的实际发送人
to_user=to_user, # 群聊时接收者为群ID
roomid=to_user if is_group_chat else "", # 如果是群聊roomid就是from_user
roomid=from_user if is_group_chat else "", # 如果是群聊roomid就是from_user
msg_type=MessageType(data.get("MsgType", 0)),
content=message_content,
create_time=data.get("CreateTime", 0),
@@ -288,6 +286,7 @@ class WxMessage:
return self.sender == self.wxid
def from_group(self) -> bool:
"""判断是否是群聊消息"""
return self.to_user.endswith("@chatroom")
def is_at(self, wxid) -> bool:
@@ -298,7 +297,7 @@ class WxMessage:
if not re.findall(f"<atuserlist>[\s|\S]*({wxid})[\s|\S]*</atuserlist>", self.msg_source):
return False # 不在 @ 清单里
if re.findall(r"@(?:所有人|all|All)", self.content):
if re.findall(r"@(?:所有人|all|All)", self.content.clean_content):
return False # 排除 @ 所有人
return True
@@ -309,11 +308,11 @@ class WxMessage:
return None
try:
appmsg = self.content.xml_content.find('.//appmsg')
appmsg = ET.fromstring(self.content.xml_content).find('.//appmsg')
if appmsg is not None:
type_value = int(appmsg.find('type').text)
return AppMessageType(type_value)
except (AttributeError, ValueError):
except (AttributeError, ValueError, ET.ParseError):
pass
return None
@@ -323,7 +322,7 @@ class WxMessage:
return None
try:
img = self.content.xml_content.find('img')
img = ET.fromstring(self.content.xml_content).find('img')
if img is not None:
return ImageContent(
aes_key=img.get('aeskey', ''),
@@ -332,7 +331,7 @@ class WxMessage:
md5=img.get('md5', ''),
thumb_base64=self.raw_data.get("Data", {}).get("ImgBuf", {}).get("buffer")
)
except (AttributeError, ValueError):
except (AttributeError, ValueError, ET.ParseError):
pass
return None
@@ -342,7 +341,7 @@ class WxMessage:
return None
try:
voice = self.content.xml_content.find('.//voicemsg')
voice = ET.fromstring(self.content.xml_content).find('.//voicemsg')
if voice is not None:
return VoiceContent(
voice_length=int(voice.get('voicelength', 0)),
@@ -350,7 +349,7 @@ class WxMessage:
url=voice.get('voiceurl', ''),
voice_base64=self.raw_data.get("Data", {}).get("ImgBuf", {}).get("buffer")
)
except (AttributeError, ValueError):
except (AttributeError, ValueError, ET.ParseError):
pass
return None
@@ -360,7 +359,7 @@ class WxMessage:
return None
try:
video = self.content.xml_content.find('.//videomsg')
video = ET.fromstring(self.content.xml_content).find('.//videomsg')
if video is not None:
return VideoContent(
aes_key=video.get('aeskey', ''),
@@ -369,7 +368,7 @@ class WxMessage:
length=int(video.get('length', 0)),
play_length=int(video.get('playlength', 0))
)
except (AttributeError, ValueError):
except (AttributeError, ValueError, ET.ParseError):
pass
return None
@@ -379,7 +378,7 @@ class WxMessage:
return None
try:
location = self.content.xml_content.find('location')
location = ET.fromstring(self.content.xml_content).find('location')
if location is not None:
return LocationContent(
x=float(location.get('x', 0)),
@@ -387,7 +386,7 @@ class WxMessage:
label=location.get('label', ''),
poi_name=location.get('poiname')
)
except (AttributeError, ValueError):
except (AttributeError, ValueError, ET.ParseError):
pass
return None
@@ -397,4 +396,4 @@ if __name__ == '__main__':
content = MessageContent(content_str, sender="Jyunere")
print(content.raw_content)
print(content.xml_content)
print(content.clean_content)
print(content.clean_content)

View File

@@ -1,25 +1,40 @@
import requests
import json
base_url = "http://192.168.2.240:2531/v2/api"
headers = {
'X-GEWE-TOKEN': 'cb43f52db27e4a56bb6ec7da54373582',
'Content-Type': 'application/json'
}
def get_chatroom_members():
url = "/group/getChatroomMemberList"
base_url = "http://192.168.2.240:2531/v2/api"
payload = json.dumps({
"appId": "wx_3BC6eSHGE5xEm_hH3__7c",
"chatroomId": "52418238895@chatroom"
})
headers = {
'X-GEWE-TOKEN': 'cb43f52db27e4a56bb6ec7da54373582',
'Content-Type': 'application/json'
}
response = requests.request("POST", base_url + url, headers=headers, data=payload)
print(response.text)
def revoke_msg():
url = "/message/revokeMsg"
payload = json.dumps({
"appId": "{{appid}}",
"toWxid": "34757816141@chatroom",
"msgId": "769533801",
"newMsgId": "5271007655758710001",
"createTime": "1704163145"
})
response = requests.request("POST", base_url+url, headers=headers, data=payload)
print(response.text)
if __name__ == '__main__':
get_chatroom_members()