prepareForTelegram function
Prepare text for sending to Telegram.
- Parses console_markdown and converts to MarkdownV2
- Truncates at line ending if too long
- Handles single long line case
Implementation
TelegramPreparedMessage prepareForTelegram(String text, {int maxChars = 4000}) {
// Convert to Telegram MarkdownV2
final converted = toTelegramMarkdownV2(text);
// Check if truncation needed
if (converted.length <= maxChars) {
return TelegramPreparedMessage(text: converted);
}
// Find last newline before limit for clean truncation
final lastNewline = converted.lastIndexOf('\n', maxChars);
// If no good newline found, it might be a single long line
if (lastNewline < maxChars ~/ 2) {
if (!converted.contains('\n') || converted.indexOf('\n') > maxChars) {
return TelegramPreparedMessage(
text: '\\(Line too long \\- sent as attachment\\)',
wasTruncated: true,
isSingleLongLine: true,
remainingChars: converted.length,
);
}
}
// Truncate at last newline
final cutPoint = lastNewline > 0 ? lastNewline : maxChars;
final truncated = converted.substring(0, cutPoint);
final remaining = converted.length - cutPoint;
return TelegramPreparedMessage(
text: '$truncated\n\n\\.\\.\\. \\[$remaining more chars\\]',
wasTruncated: true,
remainingChars: remaining,
);
}