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