]> git.giacomolli.uk - onechat/blob - telegram.go
Log each schedule run by its ID
[onechat] / telegram.go
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "log"
11 "net/http"
12 "os"
13 "path/filepath"
14 "strings"
15 "sync"
16 "time"
17 "unicode/utf8"
18 )
19
20 const (
21 // telegramAPIURL is the Telegram Bot API service.
22 telegramAPIURL = "https://api.telegram.org"
23
24 // telegramConfigFileName is the bot config in the data directory. The
25 // daemon runs the bot only when the file exists.
26 telegramConfigFileName = "telegram.json"
27
28 // telegramOffsetFileName is the update offset of the bot in the agent
29 // directory.
30 telegramOffsetFileName = "telegram-offset.json"
31
32 // telegramSource is the source of the user messages from Telegram.
33 telegramSource = "telegram"
34
35 // telegramMessageUnits is the most UTF-16 code units of one Telegram
36 // message.
37 telegramMessageUnits = 4096
38
39 // telegramRichBytes is the most bytes of the Markdown of one rich
40 // message. The Bot API allows 32768 characters of rendered text, and
41 // the Markdown of a text has at least as many bytes as the text has
42 // characters.
43 telegramRichBytes = 32768
44
45 // telegramTypingInterval is how often the bot shows the typing action
46 // while a turn runs. Telegram shows the action for about five seconds.
47 telegramTypingInterval = 4 * time.Second
48
49 // telegramTextOnly is the answer to a message that is not text.
50 telegramTextOnly = "Only text messages are supported."
51 )
52
53 // loadTelegramConfig reads telegram.json in dir. It returns false when the file
54 // does not exist. An error never holds the token.
55 func loadTelegramConfig(dir string) (TelegramConfig, bool, error) {
56 path := filepath.Join(dir, telegramConfigFileName)
57 info, err := os.Stat(path)
58 if errors.Is(err, os.ErrNotExist) {
59 return TelegramConfig{}, false, nil
60 }
61
62 if err != nil {
63 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
64 }
65
66 if info.Mode().Perm()&0o077 != 0 {
67 return TelegramConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", telegramConfigFileName)
68 }
69
70 data, err := os.ReadFile(path)
71 if err != nil {
72 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
73 }
74
75 var config TelegramConfig
76 decoder := json.NewDecoder(bytes.NewReader(data))
77 decoder.DisallowUnknownFields()
78 err = decoder.Decode(&config)
79 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
80 err = errors.New("data after the JSON object")
81 }
82
83 if err != nil {
84 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
85 }
86
87 err = config.validate()
88 if err != nil {
89 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
90 }
91
92 return config, true, nil
93 }
94
95 // newTelegramBot returns the bot of owner on api. The offset file is at
96 // offsetPath, and logger gets the failures. No log line holds the text of a
97 // message.
98 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *log.Logger) *TelegramBot {
99 return &TelegramBot{
100 api: api,
101 owner: owner,
102 offsetPath: offsetPath,
103 logger: logger,
104 minWait: time.Second,
105 maxWait: time.Minute,
106 ready: make(chan struct{}, 1),
107 }
108 }
109
110 // TelegramConfig holds the settings of telegram.json: the bot token and the
111 // user ID of the owner. The token is a secret, so the file must have mode 0600.
112 type TelegramConfig struct {
113 Token string `json:"token"`
114 Owner int64 `json:"owner"`
115 }
116
117 // validate makes sure that the token has the form of a bot token and that the
118 // owner is a user ID. The token goes into a URL path, so it can only hold the
119 // characters of a bot token.
120 func (c TelegramConfig) validate() error {
121 id, secret, found := strings.Cut(c.Token, ":")
122 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
123 return errors.New("token does not have the form of a bot token from BotFather")
124 }
125
126 if c.Owner <= 0 {
127 return errors.New("owner must be the numeric Telegram user ID of the owner")
128 }
129
130 return nil
131 }
132
133 // TelegramBot connects the private chat of the owner with the agent. It polls
134 // the Bot API for new messages and sends each text message of the owner to the
135 // agent. It ignores every other update. Its sender sends the replies, the
136 // errors, the notices of the bot, and the user messages of the other clients to
137 // the chat, and shows the typing action while a turn runs. Only the replies
138 // have a format: their Markdown goes as rich messages, which Telegram renders
139 // itself, and as message entities only when Telegram refuses a rich message.
140 // The rest is plain text. Tool calls do not go to the chat.
141 //
142 // The offset file holds the ID of the next update. It moves past an update
143 // only after the message of the update is durable in the log, so a restart
144 // does not lose a message. A crash between the flush and the offset write
145 // makes Telegram send the update again, and the message repeats once.
146 //
147 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
148 // as long as the Bot API asks. It never stops the agent. A TelegramOutage logs
149 // the first failure and the end of each run of failures, and the retries
150 // between them log nothing.
151 type TelegramBot struct {
152 api *TelegramAPI
153 owner int64
154 offsetPath string
155 logger *log.Logger
156 minWait time.Duration
157 maxWait time.Duration
158
159 mutex sync.Mutex
160 queue []Event
161 ready chan struct{}
162 }
163
164 // Notify queues event for the chat. It never blocks, so a slow network does not
165 // stop the agent. The WhatsApp batches and the runs of the schedules do not go
166 // to the chat: the reply of the agent tells the user what needs the user.
167 func (b *TelegramBot) Notify(event Event) {
168 switch event.Kind {
169 case "busy", "idle", "reply", "error", "notice", "subagent":
170 case "work":
171 if event.Source == whatsappSource || event.Source == scheduleSource {
172 return
173 }
174 case "user":
175 if event.Source == telegramSource {
176 return
177 }
178 default:
179 return
180 }
181
182 b.mutex.Lock()
183 b.queue = append(b.queue, event)
184 b.mutex.Unlock()
185
186 select {
187 case b.ready <- struct{}{}:
188 default:
189 }
190 }
191
192 // Run polls for the messages of the owner and sends the queued events to the
193 // chat until ctx ends. It returns an error only when a message or the offset
194 // cannot be written, because then the bot would lose or repeat messages.
195 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
196 ctx, cancel := context.WithCancel(ctx)
197 defer cancel()
198
199 var sender sync.WaitGroup
200 sender.Add(1)
201 go func() {
202 defer sender.Done()
203
204 b.send(ctx)
205 }()
206
207 err := b.poll(ctx, l, whatsapp)
208 cancel()
209 sender.Wait()
210
211 return err
212 }
213
214 // send sends each queued event to the chat in order until ctx ends. While a
215 // turn runs, it shows the typing action every telegramTypingInterval and after
216 // each message, because a message ends the action.
217 func (b *TelegramBot) send(ctx context.Context) {
218 ticker := time.NewTicker(telegramTypingInterval)
219 defer ticker.Stop()
220
221 busy := false
222 for ctx.Err() == nil {
223 event, found := b.next()
224 if !found {
225 select {
226 case <-b.ready:
227 case <-ticker.C:
228 if busy {
229 b.typing(ctx)
230 }
231 case <-ctx.Done():
232 }
233
234 continue
235 }
236
237 switch event.Kind {
238 case "busy":
239 busy = true
240 b.typing(ctx)
241 ticker.Reset(telegramTypingInterval)
242 case "idle":
243 busy = false
244 default:
245 b.post(ctx, event)
246
247 if busy {
248 b.typing(ctx)
249 }
250 }
251 }
252 }
253
254 // poll gets the updates from the stored offset on and handles each one, until
255 // ctx ends. Each update is handled to its end also when ctx ends during it, so
256 // a stop does not repeat its message.
257 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
258 offset, err := telegramLoadOffset(b.offsetPath)
259 if err != nil {
260 return err
261 }
262
263 outage := &TelegramOutage{
264 logger: b.logger,
265 loss: "cannot get messages from Telegram",
266 back: "messages from Telegram come again",
267 }
268
269 wait := b.minWait
270 for ctx.Err() == nil {
271 updates, err := b.api.GetUpdates(ctx, offset)
272 if ctx.Err() != nil {
273 return nil
274 }
275
276 if err != nil {
277 _, asked := telegramRetryable(err)
278 wait = b.pause(ctx, outage, err, wait, asked)
279
280 continue
281 }
282
283 outage.End()
284 wait = b.minWait
285 for _, update := range updates {
286 if ctx.Err() != nil {
287 return nil
288 }
289
290 err = b.handle(context.WithoutCancel(ctx), l, whatsapp, update)
291 if err != nil {
292 return err
293 }
294
295 offset = update.UpdateID + 1
296 err = telegramSaveOffset(b.offsetPath, offset)
297 if err != nil {
298 return err
299 }
300 }
301 }
302
303 return nil
304 }
305
306 // next removes the first queued event and returns it.
307 func (b *TelegramBot) next() (Event, bool) {
308 b.mutex.Lock()
309 defer b.mutex.Unlock()
310
311 if len(b.queue) == 0 {
312 return Event{}, false
313 }
314
315 event := b.queue[0]
316 b.queue = b.queue[1:]
317
318 return event, true
319 }
320
321 // typing shows the typing action once. A failure is not logged, because the
322 // next message or poll logs the state of the network.
323 func (b *TelegramBot) typing(ctx context.Context) {
324 _ = b.api.SendTyping(ctx, b.owner)
325 }
326
327 // post sends event to the chat. A reply goes as rich messages of its Markdown,
328 // with each < and & outside code escaped by telegramEscapeTags and then split
329 // with telegramSplitRich, so that the length limit counts the escaped text.
330 // Every other event goes as plain text, split with telegramSplitMessage.
331 func (b *TelegramBot) post(ctx context.Context, event Event) {
332 if event.Kind != "reply" {
333 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
334 b.deliver(ctx, TelegramPart{
335 text: text,
336 })
337 }
338
339 return
340 }
341
342 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
343 b.deliverRich(ctx, markdown)
344 }
345 }
346
347 // pause gives err to outage and waits the longer of wait and asked, or until
348 // ctx ends. It returns the wait of the next failure: twice wait, up to maxWait.
349 func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
350 delay := max(wait, asked)
351 outage.Fail(err, delay)
352
353 timer := time.NewTimer(delay)
354 defer timer.Stop()
355
356 select {
357 case <-timer.C:
358 case <-ctx.Done():
359 }
360
361 return min(2*wait, b.maxWait)
362 }
363
364 // handle runs one update. A text message of the owner in the private chat goes
365 // to the agent, and handle returns when it is durable in the log. The line
366 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
367 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
368 // answers go to the chat only. Any other message of the owner gets the answer
369 // that only text is supported. Every other update is ignored, and its content
370 // is not logged.
371 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
372 message := update.Message
373 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
374 b.logger.Print("a Telegram message is ignored, because it is not from the owner in the private chat")
375 return nil
376 }
377
378 name, stop := stopSubagentName(message.Text)
379 args, isWhatsApp := whatsappCommandArgs(message.Text)
380 switch {
381 case message.Text == "":
382 b.notice(telegramTextOnly)
383 case strings.TrimSpace(message.Text) == stopCommand:
384 if !l.Interrupt() {
385 b.notice("No turn runs.")
386 }
387 case stop:
388 found, err := l.StopSubagent(name)
389 if err != nil {
390 return fmt.Errorf("stop subagent %s: %w", name, err)
391 }
392
393 if !found {
394 b.notice("No subagent " + name + " runs.")
395 }
396 case isWhatsApp:
397 whatsapp.Command(args, b.notice)
398 default:
399 _, err := l.Submit(telegramSource, message.Text)
400 if err != nil {
401 return err
402 }
403
404 err = l.Flush(ctx)
405 if err != nil {
406 return fmt.Errorf("flush the message from Telegram: %w", err)
407 }
408 }
409
410 return nil
411 }
412
413 // deliver sends part to the chat. When Telegram refuses a part with entities
414 // (HTTP 400), it sends the text of the part again once with no entities, so a
415 // reply is not lost to a bad entity. It tries again after each failure that a
416 // later try can fix, until ctx ends. It drops the part after any other failure.
417 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
418 outage := b.sendOutage()
419 wait := b.minWait
420 for {
421 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
422 retry, asked := telegramRetryable(err)
423 if !retry {
424 outage.End()
425 }
426
427 if err == nil || ctx.Err() != nil {
428 return
429 }
430
431 var answer *TelegramError
432 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
433 b.logger.Printf("a reply goes as plain text, because Telegram refused its formatting: %v", err)
434 part.entities = nil
435
436 continue
437 }
438
439 if !retry {
440 b.logger.Printf("a reply to Telegram is lost: %v", err)
441 return
442 }
443
444 wait = b.pause(ctx, outage, err, wait, asked)
445 }
446 }
447
448 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
449 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
450 // was not sent, so deliverRich sends the text of the part once with message
451 // entities, and the reply is not lost and does not repeat. Message entities
452 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
453 // the model wrote it. It tries again after each failure that a later try can
454 // fix, until ctx ends. It drops the message after any other failure.
455 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
456 outage := b.sendOutage()
457 wait := b.minWait
458 for {
459 err := b.api.SendRichMessage(ctx, b.owner, markdown)
460 retry, asked := telegramRetryable(err)
461 if !retry {
462 outage.End()
463 }
464
465 if err == nil || ctx.Err() != nil {
466 return
467 }
468
469 if telegramRejected(err) {
470 b.logger.Printf("a reply goes with simpler formatting, because Telegram refused its full formatting: %v", err)
471 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
472 b.deliver(ctx, part)
473 }
474
475 return
476 }
477
478 if !retry {
479 b.logger.Printf("a reply to Telegram is lost: %v", err)
480 return
481 }
482
483 wait = b.pause(ctx, outage, err, wait, asked)
484 }
485 }
486
487 // sendOutage returns a new outage of the messages to the chat.
488 func (b *TelegramBot) sendOutage() *TelegramOutage {
489 return &TelegramOutage{
490 logger: b.logger,
491 loss: "cannot send replies to Telegram",
492 back: "replies go to Telegram again",
493 }
494 }
495
496 // notice queues a short answer of the bot for the chat.
497 func (b *TelegramBot) notice(text string) {
498 b.Notify(Event{
499 Kind: "notice",
500 Text: text,
501 })
502 }
503
504 // TelegramOutage is one run of failures of a kind of Bot API call. The first
505 // failure logs loss, its cause, and the wait of the next try. The retries log
506 // nothing. The next answer of Telegram logs back and the length of the outage.
507 // loss and back say what the user loses and gets again.
508 type TelegramOutage struct {
509 logger *log.Logger
510 loss string
511 back string
512 start time.Time
513 }
514
515 // Fail logs the start of an outage with err and delay, unless an outage runs.
516 func (o *TelegramOutage) Fail(err error, delay time.Duration) {
517 if !o.start.IsZero() {
518 return
519 }
520
521 o.start = time.Now()
522 o.logger.Printf("%s: %v (next try in %s)", o.loss, err, durationText(delay))
523 }
524
525 // End logs the end of the outage that runs, with its length.
526 func (o *TelegramOutage) End() {
527 if o.start.IsZero() {
528 return
529 }
530
531 o.logger.Printf("%s, after %s", o.back, durationText(time.Since(o.start)))
532 o.start = time.Time{}
533 }
534
535 // TelegramPart is the text of one message to the chat, at most
536 // telegramMessageUnits long, and its entities.
537 type TelegramPart struct {
538 text string
539 entities []TelegramEntity
540 }
541
542 // TelegramOffsetFile is the content of the offset file.
543 type TelegramOffsetFile struct {
544 Offset int64 `json:"offset"`
545 }
546
547 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
548 // which asks for every update that Telegram keeps.
549 func telegramLoadOffset(path string) (int64, error) {
550 data, err := os.ReadFile(path)
551 if errors.Is(err, os.ErrNotExist) {
552 return 0, nil
553 }
554
555 if err != nil {
556 return 0, fmt.Errorf("read update offset: %w", err)
557 }
558
559 var file TelegramOffsetFile
560 err = json.Unmarshal(data, &file)
561 if err != nil {
562 return 0, fmt.Errorf("%s: %w", path, err)
563 }
564
565 return file.Offset, nil
566 }
567
568 // telegramSaveOffset replaces the update offset at path.
569 func telegramSaveOffset(path string, offset int64) error {
570 data, err := json.Marshal(TelegramOffsetFile{
571 Offset: offset,
572 })
573 if err != nil {
574 return fmt.Errorf("encode update offset: %w", err)
575 }
576
577 err = writeFileAtomic(path, append(data, '\n'))
578 if err != nil {
579 return fmt.Errorf("write update offset: %w", err)
580 }
581
582 return nil
583 }
584
585 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
586 // the unit of the Telegram message limit. It cuts after the last line break or
587 // space of a part when one is in its second half, and else at the limit. It
588 // never cuts a character.
589 func telegramSplitMessage(text string, limit int) []string {
590 var parts []string
591 for {
592 end := telegramPrefixEnd(text, limit)
593 if end == len(text) {
594 return append(parts, text)
595 }
596
597 cut := strings.LastIndexByte(text[:end], '\n') + 1
598 if cut <= end/2 {
599 cut = strings.LastIndexByte(text[:end], ' ') + 1
600 }
601
602 if cut <= end/2 {
603 cut = end
604 }
605
606 parts = append(parts, text[:cut])
607 text = text[cut:]
608 }
609 }
610
611 // telegramText returns the text of event for the chat. A user message of
612 // another client has its source as a mark. A subagent shows only its start and
613 // how its run ended, because the reply of the agent carries the content of the
614 // report.
615 func telegramText(event Event) string {
616 switch event.Kind {
617 case "user":
618 return "[" + event.Source + "] " + event.Text
619 case "subagent":
620 return "[" + event.Text + "] started"
621 case "work":
622 return "[" + event.Source + "] " + event.Status
623 case "error":
624 return "Error: " + event.Text
625 default:
626 return event.Text
627 }
628 }
629
630 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
631 // bytes. It cuts after a blank line outside a code block, so a table, a code
632 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
633 // after the last line break outside a code block, then after the last line
634 // break in a code block, which it closes at the end of the part and opens again
635 // in the next part with the same fence line. A line longer than limit is cut at
636 // the limit, or before an & in the four bytes before the limit, so that it does
637 // not cut an entity of telegramEscapeTags. It never cuts a character.
638 func telegramSplitRich(markdown string, limit int) []string {
639 var parts []string
640 for len(markdown) > limit {
641 cut, fence, opening := telegramRichCut(markdown, limit)
642 if fence == "" {
643 parts = append(parts, markdown[:cut])
644 markdown = markdown[cut:]
645
646 continue
647 }
648
649 parts = append(parts, markdown[:cut]+fence+"\n")
650 markdown = opening + "\n" + markdown[cut:]
651 }
652
653 return append(parts, markdown)
654 }
655
656 // telegramReplyParts returns the messages of the Markdown of a reply with
657 // message entities. A reply that has no text left after the conversion, such as
658 // an empty code block, goes as its Markdown.
659 func telegramReplyParts(markdown string) []TelegramPart {
660 text, entities := telegramMarkdownEntities(markdown)
661 if strings.TrimSpace(text) == "" {
662 text, entities = markdown, nil
663 }
664
665 return telegramSplitEntities(text, entities, telegramMessageUnits)
666 }
667
668 // telegramPrefixEnd returns the byte length of the longest prefix of text with
669 // at most limit UTF-16 code units.
670 func telegramPrefixEnd(text string, limit int) int {
671 units := 0
672 for index, char := range text {
673 size := 1
674 if char > 0xFFFF {
675 size = 2
676 }
677
678 if units+size > limit {
679 return index
680 }
681
682 units += size
683 }
684
685 return len(text)
686 }
687
688 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
689 // longer than limit. For a cut in a code block, it also returns the fence that
690 // closes the block and the line that opens it. Each part before a cut holds
691 // text other than space, and a cut in a code block leaves room for the fence,
692 // so each cut makes the rest shorter.
693 func telegramRichCut(markdown string, limit int) (int, string, string) {
694 blank, line, code := 0, 0, 0
695 var fence, opening, inFence, inOpening string
696 for start := 0; start < limit; {
697 end := strings.IndexByte(markdown[start:], '\n')
698 if end < 0 || start+end+1 > limit {
699 break
700 }
701
702 end += start + 1
703 text := strings.TrimRight(markdown[start:end], "\r\n")
704 _, opens := telegramCodeFence(text)
705 switch {
706 case fence != "":
707 if telegramClosesFence(text, fence) {
708 fence = ""
709 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
710 code, inFence, inOpening = end, fence, opening
711 }
712 case opens != "":
713 fence, opening = opens, text
714 case strings.TrimSpace(markdown[:end]) == "":
715 case strings.TrimSpace(text) == "":
716 blank = end
717 }
718
719 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
720 line = end
721 }
722
723 start = end
724 }
725
726 switch {
727 case blank > 0:
728 return blank, "", ""
729 case line > 0:
730 return line, "", ""
731 case code > 0:
732 return code, inFence, inOpening
733 }
734
735 cut := limit
736 for !utf8.RuneStart(markdown[cut]) {
737 cut--
738 }
739
740 start := max(cut-len("&amp;")+1, 0)
741 entity := strings.LastIndexByte(markdown[start:cut], '&')
742 if entity >= 0 && start+entity > 0 {
743 cut = start + entity
744 }
745
746 return cut, "", ""
747 }
748
749 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
750 // gives each part the entities in it, with offsets from the start of the part.
751 // An entity that crosses a cut becomes one entity in each part.
752 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
753 var parts []TelegramPart
754 start := 0
755 for _, part := range telegramSplitMessage(text, limit) {
756 end := start + telegramUTF16Units(part)
757 var kept []TelegramEntity
758 for _, entity := range entities {
759 from := max(entity.Offset, start)
760 to := min(entity.Offset+entity.Length, end)
761 if to <= from {
762 continue
763 }
764
765 entity.Offset = from - start
766 entity.Length = to - from
767 kept = append(kept, entity)
768 }
769
770 parts = append(parts, TelegramPart{
771 text: part,
772 entities: kept,
773 })
774
775 start = end
776 }
777
778 return parts
779 }