From 7cefe2d82530d4d2d9f05c8eccd89d2e3558a16e Mon Sep 17 00:00:00 2001 From: lanvent Date: Fri, 21 Apr 2023 21:03:38 +0800 Subject: [PATCH] fix: split long text messages into multiple parts in wechatmp_service --- channel/wechatmp/common.py | 2 +- channel/wechatmp/wechatmp_channel.py | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/channel/wechatmp/common.py b/channel/wechatmp/common.py index 5481eae..712c5f3 100644 --- a/channel/wechatmp/common.py +++ b/channel/wechatmp/common.py @@ -51,7 +51,7 @@ def split_string_by_utf8_length(string, max_length, max_split=0): if max_split > 0 and len(result) >= max_split: result.append(encoded[start:].decode("utf-8")) break - end = start + max_length + end = min(start + max_length, len(encoded)) # 如果当前字节不是 UTF-8 编码的开始字节,则向前查找直到找到开始字节为止 while end < len(encoded) and (encoded[end] & 0b11000000) == 0b10000000: end -= 1 diff --git a/channel/wechatmp/wechatmp_channel.py b/channel/wechatmp/wechatmp_channel.py index 1768475..e59cd7e 100644 --- a/channel/wechatmp/wechatmp_channel.py +++ b/channel/wechatmp/wechatmp_channel.py @@ -130,7 +130,11 @@ class WechatMPChannel(ChatChannel): else: if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR: reply_text = reply.content - self.client.message.send_text(receiver, reply_text) + texts = split_string_by_utf8_length(reply_text, MAX_UTF8_LEN) + if len(texts)>1: + logger.info("[wechatmp] text too long, split into {} parts".format(len(texts))) + for text in texts: + self.client.message.send_text(receiver, text) logger.info("[wechatmp] Do send text to {}: {}".format(receiver, reply_text)) elif reply.type == ReplyType.VOICE: try: