Проблема заключается в том, что при разделении длинного сообщения на части фиксированной длины мы можем разорвать HTML-теги, что приводит к ошибкам при разборе Markdown или HTML в Telegram.
Решение состоит в том, чтобы разбивать сообщение на части, сохраняя целостность тегов. Для этого можно токенизировать сообщение на текст и теги, а затем собирать части сообщения, следя за открывающими и закрывающими тегами.
Вот изменённая функция:
import re
def tokenize(message):
tokens = []
pos = 0
length = len(message)
while pos < length:
if message[pos] == '<':
# Это тег
end_tag_pos = message.find('>', pos)
if end_tag_pos == -1:
# Неполный тег, считаем остальное текстом
tokens.append(('text', message[pos:]))
break
else:
token_content = message[pos+1:end_tag_pos]
# Проверяем, является ли это закрывающим тегом
if token_content.startswith('/'):
tag_name = token_content[1:].split()[0]
tokens.append(('end_tag', tag_name, '<'+token_content+'>'))
else:
# Тег может содержать атрибуты
tag_name = token_content.split()[0]
tokens.append(('start_tag', tag_name, '<'+token_content+'>'))
pos = end_tag_pos + 1
else:
# Это текст
next_tag_pos = message.find('<', pos)
if next_tag_pos == -1:
# Больше нет тегов
tokens.append(('text', message[pos:]))
break
else:
tokens.append(('text', message[pos:next_tag_pos]))
pos = next_tag_pos
return tokens
def generate_closing_tags(open_tags):
closing_tags = ''
for start_tag in reversed(open_tags):
# Получаем имя тега из стартового тега
tag_content = start_tag[1:-1].strip()
if ' ' in tag_content:
tag_name = tag_content.split(' ',1)[0]
else:
tag_name = tag_content
closing_tags += '</{}>'.format(tag_name)
return closing_tags
async def send_large_message(message, update):
MAX_MESSAGE_LENGTH = 4000
tokens = tokenize(message)
open_tags = []
current_part = ''
current_length = 0
parts = []
for token in tokens:
if token[0] == 'start_tag':
tag_name = token[1]
tag_string = token[2]
token_length = len(tag_string)
if current_length + token_length > MAX_MESSAGE_LENGTH:
# Закрываем теги и начинаем новую часть
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Открываем теги снова
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
current_part += tag_string
current_length += token_length
open_tags.append(tag_string)
elif token[0] == 'end_tag':
tag_name = token[1]
tag_string = token[2]
token_length = len(tag_string)
if current_length + token_length > MAX_MESSAGE_LENGTH:
# Закрываем теги и начинаем новую часть
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Открываем теги снова
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
current_part += tag_string
current_length += token_length
if open_tags:
open_tags.pop()
elif token[0] == 'text':
text_content = token[1]
text_length = len(text_content)
pos = 0
while pos < text_length:
remaining_space = MAX_MESSAGE_LENGTH - current_length
if remaining_space <= 0:
# Закрываем теги и начинаем новую часть
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Открываем теги снова
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
remaining_space = MAX_MESSAGE_LENGTH - current_length
take_length = min(remaining_space, text_length - pos)
current_part += text_content[pos:pos+take_length]
current_length += take_length
pos += take_length
else:
pass
# Закрываем оставшиеся открытые теги и добавляем последнюю часть
if open_tags:
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
if current_part:
parts.append(current_part)
# Отправляем части сообщения
for part in parts:
await update.message.reply_text(part, parse_mode='HTML')
Эта функция токенизирует сообщение на текстовые и теговые части, затем аккуратно разделяет сообщение на части, не превышающие максимальную длину, следя за тем, чтобы теги были правильно открыты и закрыты в каждой части.