// Package telegramtext holds the one rule both Telegram senders share: the Bot // API accepts at most MaxLen UTF-16 code units in one message, so anything // longer goes out as several messages, in order. package telegramtext import ( "unicode/utf8" ) // MaxLen is Telegram's limit on one message's text, in UTF-16 code units. A // rune outside the basic plane, an emoji for instance, counts as two. const MaxLen = 4096 // Split cuts text into parts of at most max UTF-16 code units each, so the // parts joined back together are the text it was given. It breaks on a blank // line first, then on a line break, so a part ends where the author meant to // pause, and never inside a character. func Split(text string, max int) []string { if max <= 0 { max = MaxLen } if Units(text) <= max { return []string{text} } var parts []string for Units(text) > max { cut := cutAt(text, max) parts = append(parts, text[:cut]) text = text[cut:] } return append(parts, text) } // cutAt returns the byte index to cut s at, in preference order: after the last // blank line that fits in max units, after the last line break that fits, or // after the last character that fits. func cutAt(s string, max int) int { var ( used, after int blank, line = -1, -1 ) for i, r := range s { n := 1 if r > 0xFFFF { n = 2 } if used+n > max { break } used += n after = i + utf8.RuneLen(r) if r != '\n' { continue } if i > 0 && s[i-1] == '\n' { blank = after } else { line = after } } switch { case blank > 0: return blank case line > 0: return line case after > 0: return after } // max is too small to hold one character; cut it anyway rather than spin. _, size := utf8.DecodeRuneInString(s) return size } // Units is the length Telegram measures: UTF-16 code units, not runes. func Units(s string) int { n := 0 for _, r := range s { if r > 0xFFFF { n += 2 continue } n++ } return n }