* Split text into chunks respecting Telegram's message length limit. * Tries to split at paragraph boundaries.
(text: string)
| 235 | * Tries to split at paragraph boundaries. |
| 236 | */ |
| 237 | private splitMessage(text: string): string[] { |
| 238 | if (text.length <= MAX_MESSAGE_LENGTH) { |
| 239 | return [text]; |
| 240 | } |
| 241 | |
| 242 | const chunks: string[] = []; |
| 243 | let remaining = text; |
| 244 | |
| 245 | while (remaining.length > 0) { |
| 246 | if (remaining.length <= MAX_MESSAGE_LENGTH) { |
| 247 | chunks.push(remaining); |
| 248 | break; |
| 249 | } |
| 250 | |
| 251 | // Find a good split point (paragraph break, then line break, then space) |
| 252 | let splitAt = remaining.lastIndexOf("\n\n", MAX_MESSAGE_LENGTH); |
| 253 | if (splitAt < MAX_MESSAGE_LENGTH * 0.5) { |
| 254 | splitAt = remaining.lastIndexOf("\n", MAX_MESSAGE_LENGTH); |
| 255 | } |
| 256 | if (splitAt < MAX_MESSAGE_LENGTH * 0.3) { |
| 257 | splitAt = remaining.lastIndexOf(" ", MAX_MESSAGE_LENGTH); |
| 258 | } |
| 259 | if (splitAt < 1) { |
| 260 | splitAt = MAX_MESSAGE_LENGTH; |
| 261 | } |
| 262 | |
| 263 | chunks.push(remaining.slice(0, splitAt)); |
| 264 | remaining = remaining.slice(splitAt).trimStart(); |
| 265 | } |
| 266 | |
| 267 | return chunks; |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * Send a message with automatic retry on 429 (rate limit). |