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