|
| 1 | +import { TELEGRAM_MAX_LENGTH } from "../const.js"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Splits long messages into chunks that fit within Telegram's character limit |
| 5 | + * @param {string} text - The text to split |
| 6 | + * @param {number} maxLength - Maximum length per chunk (default: 4096) |
| 7 | + * @returns {string[]} Array of message chunks |
| 8 | + */ |
| 9 | +export function splitMessage(text, maxLength = TELEGRAM_MAX_LENGTH) { |
| 10 | + if (text.length <= maxLength) { |
| 11 | + return [text]; |
| 12 | + } |
| 13 | + |
| 14 | + const chunks = []; |
| 15 | + let currentChunk = ""; |
| 16 | + |
| 17 | + // Split by paragraphs first (double newline) |
| 18 | + const paragraphs = text.split("\n\n"); |
| 19 | + |
| 20 | + for (const paragraph of paragraphs) { |
| 21 | + // If adding this paragraph would exceed the limit |
| 22 | + if (currentChunk.length + paragraph.length + 2 > maxLength) { |
| 23 | + // If current chunk has content, push it |
| 24 | + if (currentChunk) { |
| 25 | + chunks.push(currentChunk.trim()); |
| 26 | + currentChunk = ""; |
| 27 | + } |
| 28 | + |
| 29 | + // If the paragraph itself is too long, split by sentences |
| 30 | + if (paragraph.length > maxLength) { |
| 31 | + const sentences = paragraph.match(/[^.!?]+[.!?]+/g) || [paragraph]; |
| 32 | + for (const sentence of sentences) { |
| 33 | + if (currentChunk.length + sentence.length > maxLength) { |
| 34 | + if (currentChunk) { |
| 35 | + chunks.push(currentChunk.trim()); |
| 36 | + currentChunk = ""; |
| 37 | + } |
| 38 | + // If even a single sentence is too long, split by words |
| 39 | + if (sentence.length > maxLength) { |
| 40 | + const words = sentence.split(" "); |
| 41 | + for (const word of words) { |
| 42 | + if (currentChunk.length + word.length + 1 > maxLength) { |
| 43 | + chunks.push(currentChunk.trim()); |
| 44 | + currentChunk = word + " "; |
| 45 | + } else { |
| 46 | + currentChunk += word + " "; |
| 47 | + } |
| 48 | + } |
| 49 | + } else { |
| 50 | + currentChunk = sentence; |
| 51 | + } |
| 52 | + } else { |
| 53 | + currentChunk += sentence; |
| 54 | + } |
| 55 | + } |
| 56 | + } else { |
| 57 | + currentChunk = paragraph + "\n\n"; |
| 58 | + } |
| 59 | + } else { |
| 60 | + currentChunk += paragraph + "\n\n"; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // Push any remaining content |
| 65 | + if (currentChunk.trim()) { |
| 66 | + chunks.push(currentChunk.trim()); |
| 67 | + } |
| 68 | + |
| 69 | + return chunks; |
| 70 | +} |
0 commit comments