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