mirror of
https://github.com/yshtcn/ServerChanPush2TelegramBot.git
synced 2025-12-14 02:00:26 +08:00
解决消息过长的问题
This commit is contained in:
parent
3a4c7c80a5
commit
77274c1248
@ -163,30 +163,46 @@ def send_telegram_message(bot_id, chat_id, title, desp=None, url=None):
|
|||||||
text = escape(text) # 处理 HTML 标签
|
text = escape(text) # 处理 HTML 标签
|
||||||
text = re.sub(r'<[^>]+>', '', text) # 移除所有 HTML 标签
|
text = re.sub(r'<[^>]+>', '', text) # 移除所有 HTML 标签
|
||||||
|
|
||||||
|
# 添加对消息长度的检查和拆分
|
||||||
|
max_length = 4096 # Telegram 允许的最大消息长度
|
||||||
|
messages = []
|
||||||
|
while len(text) > max_length:
|
||||||
|
part = text[:max_length]
|
||||||
|
last_space = part.rfind(' ')
|
||||||
|
if last_space != -1:
|
||||||
|
part = part[:last_space]
|
||||||
|
messages.append(part)
|
||||||
|
text = text[len(part):].strip()
|
||||||
|
messages.append(text)
|
||||||
|
|
||||||
if url:
|
if url:
|
||||||
text += f"\n\n<a href=\"{url}\">详情:</a>"
|
for i in range(len(messages)):
|
||||||
text += f"{url}"
|
if i == len(messages) - 1:
|
||||||
text = unescape_url(text)
|
messages[i] += f"\n\n<a href=\"{url}\">详情:</a>{url}"
|
||||||
|
messages[i] = unescape_url(messages[i])
|
||||||
|
|
||||||
payload = {
|
success = True
|
||||||
'chat_id': chat_id,
|
for msg in messages:
|
||||||
'text': text,
|
payload = {
|
||||||
'parse_mode': 'HTML',
|
'chat_id': chat_id,
|
||||||
'disable_web_page_preview': False
|
'text': msg,
|
||||||
}
|
'parse_mode': 'HTML',
|
||||||
|
'disable_web_page_preview': False
|
||||||
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.post(api_url, data=payload, proxies=proxies, timeout=2)
|
response = requests.post(api_url, data=payload, proxies=proxies, timeout=2)
|
||||||
logging.info(f"response: {response.text}")
|
logging.info(f"response: {response.text}")
|
||||||
if response.status_code == 200 and response.json().get("ok"):
|
if response.status_code == 200 and response.json().get("ok"):
|
||||||
converted_sent_data = convert_str_gbk_to_utf8(str(payload))
|
converted_sent_data = convert_str_gbk_to_utf8(str(payload))
|
||||||
save_sent_data(api_url, converted_sent_data)
|
save_sent_data(api_url, converted_sent_data)
|
||||||
return True, response.json()
|
else:
|
||||||
else:
|
success = False
|
||||||
return False, response.json()
|
except requests.RequestException as e:
|
||||||
except requests.RequestException as e:
|
logging.error(f"Failed to send message: {e}")
|
||||||
logging.error(f"Failed to send message: {e}")
|
success = False
|
||||||
return False, None
|
|
||||||
|
return success, None if success else {"error": "Failed to send all parts of the message"}
|
||||||
|
|
||||||
|
|
||||||
@app.route('/', methods=['GET', 'POST'])
|
@app.route('/', methods=['GET', 'POST'])
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user