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