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