优化微信文本消息发送:支持长文本分块发送

This commit is contained in:
Dean 2024-07-11 20:30:09 +08:00
parent 19165eff75
commit d90e3c29a5
2 changed files with 46 additions and 16 deletions

3
.gitignore vendored
View File

@ -16,4 +16,5 @@ config/sites/**
*.pyc *.pyc
*.log *.log
.vscode .vscode
venv venv
.DS_Store

View File

@ -100,28 +100,57 @@ class WeChat:
""" """
message_url = self._send_msg_url % self.__get_access_token() message_url = self._send_msg_url % self.__get_access_token()
if text: if text:
conent = "%s\n%s" % (title, text.replace("\n\n", "\n")) content = "%s\n%s" % (title, text.replace("\n\n", "\n"))
else: else:
conent = title content = title
if link: if link:
conent = f"{conent}\n点击查看:{link}" content = f"{content}\n点击查看:{link}"
if not userid: if not userid:
userid = "@all" userid = "@all"
req_json = { # Check if content exceeds 2048 bytes and split if necessary
"touser": userid, if len(content.encode('utf-8')) > 2048:
"msgtype": "text", content_chunks = []
"agentid": self._appid, current_chunk = ""
"text": { for line in content.splitlines():
"content": conent if len(current_chunk.encode('utf-8')) + len(line.encode('utf-8')) > 2048:
}, content_chunks.append(current_chunk.strip())
"safe": 0, current_chunk = ""
"enable_id_trans": 0, current_chunk += line + "\n"
"enable_duplicate_check": 0 if current_chunk:
} content_chunks.append(current_chunk.strip())
return self.__post_request(message_url, req_json)
# Send each chunk as a separate message
for chunk in content_chunks:
req_json = {
"touser": userid,
"msgtype": "text",
"agentid": self._appid,
"text": {
"content": chunk
},
"safe": 0,
"enable_id_trans": 0,
"enable_duplicate_check": 0
}
result = self.__post_request(message_url, req_json)
else:
req_json = {
"touser": userid,
"msgtype": "text",
"agentid": self._appid,
"text": {
"content": content
},
"safe": 0,
"enable_id_trans": 0,
"enable_duplicate_check": 0
}
return self.__post_request(message_url, req_json)
return result
def __send_image_message(self, title: str, text: str, image_url: str, def __send_image_message(self, title: str, text: str, image_url: str,
userid: str = None, link: str = None) -> Optional[bool]: userid: str = None, link: str = None) -> Optional[bool]: