]> git.giacomolli.uk - onechat/blob - telegram.go
Find WhatsApp contacts and groups
[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.
149 type TelegramBot struct {
150 api *TelegramAPI
151 owner int64
152 offsetPath string
153 logger *log.Logger
154 minWait time.Duration
155 maxWait time.Duration
156
157 mutex sync.Mutex
158 queue []Event
159 ready chan struct{}
160 }
161
162 // Notify queues event for the chat. It never blocks, so a slow network does not
163 // stop the agent. The WhatsApp batches do not go to the chat: the reply of the
164 // agent tells the user what needs the user.
165 func (b *TelegramBot) Notify(event Event) {
166 switch event.Kind {
167 case "busy", "idle", "reply", "error", "notice", "subagent":
168 case "work":
169 if event.Source == whatsappSource {
170 return
171 }
172 case "user":
173 if event.Source == telegramSource {
174 return
175 }
176 default:
177 return
178 }
179
180 b.mutex.Lock()
181 b.queue = append(b.queue, event)
182 b.mutex.Unlock()
183
184 select {
185 case b.ready <- struct{}{}:
186 default:
187 }
188 }
189
190 // Run polls for the messages of the owner and sends the queued events to the
191 // chat until ctx ends. It returns an error only when a message or the offset
192 // cannot be written, because then the bot would lose or repeat messages.
193 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
194 ctx, cancel := context.WithCancel(ctx)
195 defer cancel()
196
197 var sender sync.WaitGroup
198 sender.Add(1)
199 go func() {
200 defer sender.Done()
201
202 b.send(ctx)
203 }()
204
205 err := b.poll(ctx, l, whatsapp)
206 cancel()
207 sender.Wait()
208
209 return err
210 }
211
212 // send sends each queued event to the chat in order until ctx ends. While a
213 // turn runs, it shows the typing action every telegramTypingInterval and after
214 // each message, because a message ends the action.
215 func (b *TelegramBot) send(ctx context.Context) {
216 ticker := time.NewTicker(telegramTypingInterval)
217 defer ticker.Stop()
218
219 busy := false
220 for ctx.Err() == nil {
221 event, found := b.next()
222 if !found {
223 select {
224 case <-b.ready:
225 case <-ticker.C:
226 if busy {
227 b.typing(ctx)
228 }
229 case <-ctx.Done():
230 }
231
232 continue
233 }
234
235 switch event.Kind {
236 case "busy":
237 busy = true
238 b.typing(ctx)
239 ticker.Reset(telegramTypingInterval)
240 case "idle":
241 busy = false
242 default:
243 b.post(ctx, event)
244
245 if busy {
246 b.typing(ctx)
247 }
248 }
249 }
250 }
251
252 // poll gets the updates from the stored offset on and handles each one, until
253 // ctx ends. Each update is handled to its end also when ctx ends during it, so
254 // a stop does not repeat its message.
255 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
256 offset, err := telegramLoadOffset(b.offsetPath)
257 if err != nil {
258 return err
259 }
260
261 wait := b.minWait
262 for ctx.Err() == nil {
263 updates, err := b.api.GetUpdates(ctx, offset)
264 if ctx.Err() != nil {
265 return nil
266 }
267
268 if err != nil {
269 _, asked := telegramRetryable(err)
270 wait = b.pause(ctx, err, wait, asked)
271
272 continue
273 }
274
275 wait = b.minWait
276 for _, update := range updates {
277 if ctx.Err() != nil {
278 return nil
279 }
280
281 err = b.handle(context.WithoutCancel(ctx), l, whatsapp, update)
282 if err != nil {
283 return err
284 }
285
286 offset = update.UpdateID + 1
287 err = telegramSaveOffset(b.offsetPath, offset)
288 if err != nil {
289 return err
290 }
291 }
292 }
293
294 return nil
295 }
296
297 // next removes the first queued event and returns it.
298 func (b *TelegramBot) next() (Event, bool) {
299 b.mutex.Lock()
300 defer b.mutex.Unlock()
301
302 if len(b.queue) == 0 {
303 return Event{}, false
304 }
305
306 event := b.queue[0]
307 b.queue = b.queue[1:]
308
309 return event, true
310 }
311
312 // typing shows the typing action once. A failure is not logged, because the
313 // next message or poll logs the state of the network.
314 func (b *TelegramBot) typing(ctx context.Context) {
315 _ = b.api.SendTyping(ctx, b.owner)
316 }
317
318 // post sends event to the chat. A reply goes as rich messages of its Markdown,
319 // with each < and & outside code escaped by telegramEscapeTags and then split
320 // with telegramSplitRich, so that the length limit counts the escaped text.
321 // Every other event goes as plain text, split with telegramSplitMessage.
322 func (b *TelegramBot) post(ctx context.Context, event Event) {
323 if event.Kind != "reply" {
324 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
325 b.deliver(ctx, TelegramPart{
326 text: text,
327 })
328 }
329
330 return
331 }
332
333 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
334 b.deliverRich(ctx, markdown)
335 }
336 }
337
338 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
339 // returns the wait of the next failure: twice wait, up to maxWait.
340 func (b *TelegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
341 delay := max(wait, asked)
342 b.logger.Printf("%v (next try in %s)", err, delay)
343
344 timer := time.NewTimer(delay)
345 defer timer.Stop()
346
347 select {
348 case <-timer.C:
349 case <-ctx.Done():
350 }
351
352 return min(2*wait, b.maxWait)
353 }
354
355 // handle runs one update. A text message of the owner in the private chat goes
356 // to the agent, and handle returns when it is durable in the log. The line
357 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
358 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
359 // answers go to the chat only. Any other message of the owner gets the answer
360 // that only text is supported. Every other update is ignored, and its content
361 // is not logged.
362 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
363 message := update.Message
364 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
365 b.logger.Print("update ignored: not a message of the owner in the private chat")
366 return nil
367 }
368
369 name, stop := stopSubagentName(message.Text)
370 args, isWhatsApp := whatsappCommandArgs(message.Text)
371 switch {
372 case message.Text == "":
373 b.notice(telegramTextOnly)
374 case strings.TrimSpace(message.Text) == stopCommand:
375 if !l.Interrupt() {
376 b.notice("No turn runs.")
377 }
378 case stop:
379 found, err := l.StopSubagent(name)
380 if err != nil {
381 return fmt.Errorf("stop subagent %s: %w", name, err)
382 }
383
384 if !found {
385 b.notice("No subagent " + name + " runs.")
386 }
387 case isWhatsApp:
388 whatsapp.Command(args, b.notice)
389 default:
390 _, err := l.Submit(telegramSource, message.Text)
391 if err != nil {
392 return err
393 }
394
395 err = l.Flush(ctx)
396 if err != nil {
397 return fmt.Errorf("flush the message from Telegram: %w", err)
398 }
399 }
400
401 return nil
402 }
403
404 // deliver sends part to the chat. When Telegram refuses a part with entities
405 // (HTTP 400), it sends the text of the part again once with no entities, so a
406 // reply is not lost to a bad entity. It tries again after each failure that a
407 // later try can fix, until ctx ends. It drops the part after any other failure.
408 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
409 wait := b.minWait
410 for {
411 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
412 if err == nil || ctx.Err() != nil {
413 return
414 }
415
416 var answer *TelegramError
417 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
418 b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
419 part.entities = nil
420
421 continue
422 }
423
424 retry, asked := telegramRetryable(err)
425 if !retry {
426 b.logger.Printf("message dropped: %v", err)
427 return
428 }
429
430 wait = b.pause(ctx, err, wait, asked)
431 }
432 }
433
434 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
435 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
436 // was not sent, so deliverRich sends the text of the part once with message
437 // entities, and the reply is not lost and does not repeat. Message entities
438 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
439 // the model wrote it. It tries again after each failure that a later try can
440 // fix, until ctx ends. It drops the message after any other failure.
441 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
442 wait := b.minWait
443 for {
444 err := b.api.SendRichMessage(ctx, b.owner, markdown)
445 if err == nil || ctx.Err() != nil {
446 return
447 }
448
449 if telegramRejected(err) {
450 b.logger.Printf("rich message refused, the reply goes with entities: %v", err)
451 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
452 b.deliver(ctx, part)
453 }
454
455 return
456 }
457
458 retry, asked := telegramRetryable(err)
459 if !retry {
460 b.logger.Printf("message dropped: %v", err)
461 return
462 }
463
464 wait = b.pause(ctx, err, wait, asked)
465 }
466 }
467
468 // notice queues a short answer of the bot for the chat.
469 func (b *TelegramBot) notice(text string) {
470 b.Notify(Event{
471 Kind: "notice",
472 Text: text,
473 })
474 }
475
476 // TelegramPart is the text of one message to the chat, at most
477 // telegramMessageUnits long, and its entities.
478 type TelegramPart struct {
479 text string
480 entities []TelegramEntity
481 }
482
483 // TelegramOffsetFile is the content of the offset file.
484 type TelegramOffsetFile struct {
485 Offset int64 `json:"offset"`
486 }
487
488 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
489 // which asks for every update that Telegram keeps.
490 func telegramLoadOffset(path string) (int64, error) {
491 data, err := os.ReadFile(path)
492 if errors.Is(err, os.ErrNotExist) {
493 return 0, nil
494 }
495
496 if err != nil {
497 return 0, fmt.Errorf("read update offset: %w", err)
498 }
499
500 var file TelegramOffsetFile
501 err = json.Unmarshal(data, &file)
502 if err != nil {
503 return 0, fmt.Errorf("%s: %w", path, err)
504 }
505
506 return file.Offset, nil
507 }
508
509 // telegramSaveOffset replaces the update offset at path.
510 func telegramSaveOffset(path string, offset int64) error {
511 data, err := json.Marshal(TelegramOffsetFile{
512 Offset: offset,
513 })
514 if err != nil {
515 return fmt.Errorf("encode update offset: %w", err)
516 }
517
518 err = writeFileAtomic(path, append(data, '\n'))
519 if err != nil {
520 return fmt.Errorf("write update offset: %w", err)
521 }
522
523 return nil
524 }
525
526 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
527 // the unit of the Telegram message limit. It cuts after the last line break or
528 // space of a part when one is in its second half, and else at the limit. It
529 // never cuts a character.
530 func telegramSplitMessage(text string, limit int) []string {
531 var parts []string
532 for {
533 end := telegramPrefixEnd(text, limit)
534 if end == len(text) {
535 return append(parts, text)
536 }
537
538 cut := strings.LastIndexByte(text[:end], '\n') + 1
539 if cut <= end/2 {
540 cut = strings.LastIndexByte(text[:end], ' ') + 1
541 }
542
543 if cut <= end/2 {
544 cut = end
545 }
546
547 parts = append(parts, text[:cut])
548 text = text[cut:]
549 }
550 }
551
552 // telegramText returns the text of event for the chat. A user message of
553 // another client has its source as a mark. A subagent shows only its start and
554 // how its run ended, because the reply of the agent carries the content of the
555 // report.
556 func telegramText(event Event) string {
557 switch event.Kind {
558 case "user":
559 return "[" + event.Source + "] " + event.Text
560 case "subagent":
561 return "[" + event.Text + "] started"
562 case "work":
563 return "[" + event.Source + "] " + event.Status
564 case "error":
565 return "Error: " + event.Text
566 default:
567 return event.Text
568 }
569 }
570
571 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
572 // bytes. It cuts after a blank line outside a code block, so a table, a code
573 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
574 // after the last line break outside a code block, then after the last line
575 // break in a code block, which it closes at the end of the part and opens again
576 // in the next part with the same fence line. A line longer than limit is cut at
577 // the limit, or before an & in the four bytes before the limit, so that it does
578 // not cut an entity of telegramEscapeTags. It never cuts a character.
579 func telegramSplitRich(markdown string, limit int) []string {
580 var parts []string
581 for len(markdown) > limit {
582 cut, fence, opening := telegramRichCut(markdown, limit)
583 if fence == "" {
584 parts = append(parts, markdown[:cut])
585 markdown = markdown[cut:]
586
587 continue
588 }
589
590 parts = append(parts, markdown[:cut]+fence+"\n")
591 markdown = opening + "\n" + markdown[cut:]
592 }
593
594 return append(parts, markdown)
595 }
596
597 // telegramReplyParts returns the messages of the Markdown of a reply with
598 // message entities. A reply that has no text left after the conversion, such as
599 // an empty code block, goes as its Markdown.
600 func telegramReplyParts(markdown string) []TelegramPart {
601 text, entities := telegramMarkdownEntities(markdown)
602 if strings.TrimSpace(text) == "" {
603 text, entities = markdown, nil
604 }
605
606 return telegramSplitEntities(text, entities, telegramMessageUnits)
607 }
608
609 // telegramPrefixEnd returns the byte length of the longest prefix of text with
610 // at most limit UTF-16 code units.
611 func telegramPrefixEnd(text string, limit int) int {
612 units := 0
613 for index, char := range text {
614 size := 1
615 if char > 0xFFFF {
616 size = 2
617 }
618
619 if units+size > limit {
620 return index
621 }
622
623 units += size
624 }
625
626 return len(text)
627 }
628
629 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
630 // longer than limit. For a cut in a code block, it also returns the fence that
631 // closes the block and the line that opens it. Each part before a cut holds
632 // text other than space, and a cut in a code block leaves room for the fence,
633 // so each cut makes the rest shorter.
634 func telegramRichCut(markdown string, limit int) (int, string, string) {
635 blank, line, code := 0, 0, 0
636 var fence, opening, inFence, inOpening string
637 for start := 0; start < limit; {
638 end := strings.IndexByte(markdown[start:], '\n')
639 if end < 0 || start+end+1 > limit {
640 break
641 }
642
643 end += start + 1
644 text := strings.TrimRight(markdown[start:end], "\r\n")
645 _, opens := telegramCodeFence(text)
646 switch {
647 case fence != "":
648 if telegramClosesFence(text, fence) {
649 fence = ""
650 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
651 code, inFence, inOpening = end, fence, opening
652 }
653 case opens != "":
654 fence, opening = opens, text
655 case strings.TrimSpace(markdown[:end]) == "":
656 case strings.TrimSpace(text) == "":
657 blank = end
658 }
659
660 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
661 line = end
662 }
663
664 start = end
665 }
666
667 switch {
668 case blank > 0:
669 return blank, "", ""
670 case line > 0:
671 return line, "", ""
672 case code > 0:
673 return code, inFence, inOpening
674 }
675
676 cut := limit
677 for !utf8.RuneStart(markdown[cut]) {
678 cut--
679 }
680
681 start := max(cut-len("&amp;")+1, 0)
682 entity := strings.LastIndexByte(markdown[start:cut], '&')
683 if entity >= 0 && start+entity > 0 {
684 cut = start + entity
685 }
686
687 return cut, "", ""
688 }
689
690 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
691 // gives each part the entities in it, with offsets from the start of the part.
692 // An entity that crosses a cut becomes one entity in each part.
693 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
694 var parts []TelegramPart
695 start := 0
696 for _, part := range telegramSplitMessage(text, limit) {
697 end := start + telegramUTF16Units(part)
698 var kept []TelegramEntity
699 for _, entity := range entities {
700 from := max(entity.Offset, start)
701 to := min(entity.Offset+entity.Length, end)
702 if to <= from {
703 continue
704 }
705
706 entity.Offset = from - start
707 entity.Length = to - from
708 kept = append(kept, entity)
709 }
710
711 parts = append(parts, TelegramPart{
712 text: part,
713 entities: kept,
714 })
715
716 start = end
717 }
718
719 return parts
720 }