]> git.giacomolli.uk - onechat/blob - telegram_api.go
Receive voice notes from both chat services
[onechat] / telegram_api.go
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "mime/multipart"
11 "net/http"
12 "net/url"
13 "path"
14 "strconv"
15 "strings"
16 "time"
17 )
18
19 const (
20 // telegramUpdateWaitTimeout is how long one getUpdates call waits for
21 // an update.
22 telegramUpdateWaitTimeout = 50 * time.Second
23
24 // telegramPollSlack is how much longer than telegramUpdateWaitTimeout a
25 // getUpdates call can take before the bot gives it up.
26 telegramPollSlack = 20 * time.Second
27
28 // telegramPollTimeout is how long one getUpdates call can take.
29 telegramPollTimeout = telegramUpdateWaitTimeout + telegramPollSlack
30
31 // telegramSendTimeout is how long a sendMessage or sendRichMessage call
32 // can take. A connection that stops without a close, such as after a
33 // network change, then fails the call, and the sender tries again,
34 // instead of a wait until TCP gives up. The client has no timeout of
35 // its own, because the long poll of getUpdates needs a longer limit.
36 telegramSendTimeout = 30 * time.Second
37
38 // telegramFileLookupTimeout is the longest wait for media file details.
39 telegramFileLookupTimeout = 30 * time.Second
40
41 // telegramFileDownloadTimeout is the longest wait for image bytes.
42 telegramFileDownloadTimeout = 30 * time.Second
43
44 // telegramTypingTimeout is the longest wait to show the typing action.
45 telegramTypingTimeout = 30 * time.Second
46
47 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
48 telegramAnswerBytes = 16 << 20
49 )
50
51 // newTelegramAPI returns the client of the Bot API at base with token.
52 func newTelegramAPI(base, token string) *TelegramAPI {
53 return &TelegramAPI{
54 base: base,
55 token: token,
56 http: &http.Client{},
57 }
58 }
59
60 // telegramRetryable tells if a later try of a failed Bot API call can work:
61 // after a network error, HTTP 429, or a server error. It returns the wait that
62 // the Bot API asks for, or 0.
63 func telegramRetryable(err error) (bool, time.Duration) {
64 var network *TelegramNetworkError
65
66 if errors.As(err, &network) {
67 return true, 0
68 }
69
70 var answer *TelegramError
71
72 if errors.As(err, &answer) {
73 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
74 }
75
76 return false, 0
77 }
78
79 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
80 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
81 // that the method is not there. An error page with no Bot API answer does not
82 // tell this, so it is not a refusal.
83 func telegramRejected(err error) bool {
84 var answer *TelegramError
85
86 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
87 }
88
89 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
90 // so no error of TelegramAPI holds a URL, a net/http error, or the token.
91 type TelegramAPI struct {
92 base string
93 token string
94 http *http.Client
95 }
96
97 // GetUpdates waits for the updates from offset on, up to
98 // telegramUpdateWaitTimeout, and returns them. Telegram forgets each update
99 // before offset. Only new messages are asked for.
100 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
101 var updates []TelegramUpdate
102
103 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
104 "offset": offset,
105 "timeout": int(telegramUpdateWaitTimeout / time.Second),
106 "allowed_updates": []string{"message"},
107 }, &updates)
108
109 return updates, err
110 }
111
112 // GetFile downloads bounded media through the authenticated file endpoint.
113 // Errors never include its token or URL, and the body is limited before
114 // storage.
115 func (b *TelegramAPI) GetFile(ctx context.Context, id string, limit int64, tooLarge error) (data []byte, err error) {
116 var file struct {
117 Path string `json:"file_path"`
118 Size int64 `json:"file_size"`
119 }
120
121 err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
122 if err != nil {
123 return nil, fmt.Errorf("get media file: %w", err)
124 }
125
126 if file.Size > limit {
127 return nil, tooLarge
128 }
129
130 if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
131 return nil, errors.New("invalid media file path")
132 }
133
134 ctx, cancel := context.WithTimeout(ctx, telegramFileDownloadTimeout)
135 defer cancel()
136
137 request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
138 if err != nil {
139 return nil, fmt.Errorf("make media request: %s", b.redact(err))
140 }
141
142 response, err := b.http.Do(request)
143 if err != nil {
144 return nil, b.networkError("media download failed", err, telegramFileDownloadTimeout)
145 }
146
147 defer func() {
148 closeErr := response.Body.Close()
149 if closeErr != nil {
150 err = errors.Join(err, b.networkError("close media download", closeErr, telegramFileDownloadTimeout))
151 }
152 }()
153
154 if response.StatusCode != http.StatusOK {
155 return nil, &TelegramError{
156 Status: response.StatusCode,
157 Description: http.StatusText(response.StatusCode),
158 }
159 }
160
161 data, err = io.ReadAll(io.LimitReader(response.Body, limit+1))
162 if err != nil {
163 return nil, b.networkError("media cut off", err, telegramFileDownloadTimeout)
164 }
165
166 if int64(len(data)) > limit {
167 return nil, tooLarge
168 }
169
170 return data, nil
171 }
172
173 // SendMessage sends text to chat with the format of entities, with no parse
174 // mode, so the text needs no escaping. With no entities, the text is plain. A
175 // call that takes longer than telegramSendTimeout fails with a
176 // TelegramNetworkError.
177 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
178 params := map[string]any{
179 "chat_id": chat,
180 "text": text,
181 }
182
183 if len(entities) > 0 {
184 params["entities"] = entities
185 }
186
187 return b.call(ctx, telegramSendTimeout, "sendMessage", params, nil)
188 }
189
190 // SendRichMessage sends markdown to chat as a rich message, which Telegram
191 // renders itself, tables included. A call that takes longer than
192 // telegramSendTimeout fails with a TelegramNetworkError.
193 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
194 return b.call(ctx, telegramSendTimeout, "sendRichMessage", map[string]any{
195 "chat_id": chat,
196 "rich_message": map[string]any{
197 "markdown": markdown,
198 },
199 }, nil)
200 }
201
202 // SendImage uploads an image to the owner as a photo, or as a document when the
203 // Bot API refuses the photo. Network failures do not trigger a second send.
204 func (b *TelegramAPI) SendImage(ctx context.Context, chat int64, name string, data []byte, caption string) error {
205 err := b.sendImage(ctx, "sendPhoto", "photo", chat, name, data, caption)
206 if telegramRejected(err) {
207 err = b.sendImage(ctx, "sendDocument", "document", chat, name, data, caption)
208 }
209
210 return err
211 }
212
213 func (b *TelegramAPI) sendImage(ctx context.Context, method, field string, chat int64, name string, data []byte, caption string) error {
214 ctx, cancel := context.WithTimeout(ctx, telegramSendTimeout)
215 defer cancel()
216
217 var body bytes.Buffer
218
219 writer := multipart.NewWriter(&body)
220 err := writer.WriteField("chat_id", strconv.FormatInt(chat, 10))
221 if err != nil {
222 return fmt.Errorf("write image chat: %w", err)
223 }
224
225 err = writer.WriteField("caption", caption)
226 if err != nil {
227 return fmt.Errorf("write image caption: %w", err)
228 }
229
230 part, err := writer.CreateFormFile(field, name)
231 if err != nil {
232 return fmt.Errorf("make image part: %w", err)
233 }
234
235 _, err = part.Write(data)
236 if err != nil {
237 return fmt.Errorf("write image part: %w", err)
238 }
239
240 err = writer.Close()
241 if err != nil {
242 return fmt.Errorf("close image form: %w", err)
243 }
244
245 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, &body)
246 if err != nil {
247 return fmt.Errorf("make image upload: %s", b.redact(err))
248 }
249
250 request.Header.Set("Content-Type", writer.FormDataContentType())
251
252 err = b.answer(request, telegramSendTimeout, nil)
253 if err != nil {
254 return fmt.Errorf("upload image: %w", err)
255 }
256
257 return nil
258 }
259
260 // SendTyping shows the typing action in chat for about five seconds. A call
261 // that takes longer than telegramTypingTimeout fails with a
262 // TelegramNetworkError.
263 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
264 return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
265 "chat_id": chat,
266 "action": "typing",
267 }, nil)
268 }
269
270 // call sends one call of method with the JSON params and decodes its result
271 // into result, when result is not nil. The call can take up to timeout. Its
272 // errors tell the cause in plain words, with no method name, so that a log line
273 // can say first what the call was for.
274 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
275 ctx, cancel := context.WithTimeout(ctx, timeout)
276 defer cancel()
277
278 body, err := json.Marshal(params)
279 if err != nil {
280 return fmt.Errorf("%s: encode request: %w", method, err)
281 }
282
283 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
284 if err != nil {
285 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
286 }
287
288 request.Header.Set("Content-Type", "application/json")
289
290 return b.answer(request, timeout, result)
291 }
292
293 // answer reads the bounded Bot API response without keeping its request URL.
294 func (b *TelegramAPI) answer(request *http.Request, timeout time.Duration, result any) error {
295 response, err := b.http.Do(request)
296 if err != nil {
297 return b.networkError("no answer", err, timeout)
298 }
299
300 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
301 err = errors.Join(err, response.Body.Close())
302 if err != nil {
303 return b.networkError("answer cut off", err, timeout)
304 }
305
306 var answer TelegramAnswer
307
308 err = json.Unmarshal(data, &answer)
309 if err != nil && response.StatusCode != http.StatusOK {
310 return &TelegramError{
311 Status: response.StatusCode,
312 Description: http.StatusText(response.StatusCode),
313 }
314 }
315
316 if err != nil {
317 return b.networkError("invalid JSON", err, timeout)
318 }
319
320 if !answer.OK {
321 return &TelegramError{
322 Status: response.StatusCode,
323 Description: b.redact(errors.New(answer.Description)),
324 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
325 Refused: true,
326 }
327 }
328
329 if result == nil {
330 return nil
331 }
332
333 err = json.Unmarshal(answer.Result, result)
334 if err != nil {
335 return b.networkError("invalid result", err, timeout)
336 }
337
338 return nil
339 }
340
341 // networkError returns the TelegramNetworkError of err, which happened at the
342 // step that what names. When the call used all of its time timeout, the cause
343 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
344 // how long the wait was.
345 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
346 if errors.Is(err, context.DeadlineExceeded) {
347 return &TelegramNetworkError{
348 Cause: "no answer in " + timeout.String(),
349 }
350 }
351
352 return &TelegramNetworkError{
353 Cause: what + ": " + b.redact(err),
354 }
355 }
356
357 // redact returns the text of err without a URL and without the token. A
358 // *url.Error holds the URL of the call, which holds the token, so only its
359 // cause is kept.
360 func (b *TelegramAPI) redact(err error) string {
361 var urlError *url.Error
362
363 if errors.As(err, &urlError) {
364 err = urlError.Err
365 }
366
367 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
368 }
369
370 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
371 // after a network error. A later call can work. Cause tells why in plain words,
372 // with no URL and no token.
373 type TelegramNetworkError struct {
374 Cause string
375 }
376
377 func (e *TelegramNetworkError) Error() string {
378 return e.Cause
379 }
380
381 // TelegramError is an answer of the Bot API that tells of a failure. Its text
382 // gives the HTTP status and the description, such as "502 Bad Gateway".
383 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
384 // tells that the answer is a Bot API answer with ok false, not a page of a
385 // proxy or of a server error.
386 type TelegramError struct {
387 Status int
388 Description string
389 RetryAfter time.Duration
390 Refused bool
391 }
392
393 func (e *TelegramError) Error() string {
394 return fmt.Sprintf("%d %s", e.Status, e.Description)
395 }
396
397 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
398 // updates that are not a new message.
399 type TelegramUpdate struct {
400 UpdateID int64 `json:"update_id"`
401 Message *TelegramMessage `json:"message"`
402 }
403
404 // TelegramEntity is a message entity of sendMessage: a part of the text with a
405 // format, such as bold or a link. Offset and Length count UTF-16 code units.
406 // URL is the target of a text_link, and Language the language of a pre.
407 type TelegramEntity struct {
408 Type string `json:"type"`
409 Offset int `json:"offset"`
410 Length int `json:"length"`
411 URL string `json:"url,omitempty"`
412 Language string `json:"language,omitempty"`
413 }
414
415 // TelegramAnswer is the envelope of each answer of the Bot API.
416 type TelegramAnswer struct {
417 OK bool `json:"ok"`
418 Result json.RawMessage `json:"result"`
419 ErrorCode int `json:"error_code"`
420 Description string `json:"description"`
421 Parameters struct {
422 RetryAfter int `json:"retry_after"`
423 } `json:"parameters"`
424 }
425
426 // TelegramMessage holds the text, caption, and image sizes of a bot message.
427 type TelegramMessage struct {
428 Chat TelegramChat `json:"chat"`
429 From *TelegramUser `json:"from"`
430 Text string `json:"text"`
431 Caption string `json:"caption"`
432 Photo []TelegramPhoto `json:"photo"`
433 Document *TelegramDocument `json:"document"`
434 Voice *TelegramVoice `json:"voice"`
435 }
436
437 // TelegramVoice identifies a voice note in the authenticated file API.
438 type TelegramVoice struct {
439 FileID string `json:"file_id"`
440 FileSize int64 `json:"file_size"`
441 }
442
443 // TelegramPhoto is one supplied size of a photo.
444 type TelegramPhoto struct {
445 FileID string `json:"file_id"`
446 Width int `json:"width"`
447 Height int `json:"height"`
448 FileSize int64 `json:"file_size"`
449 }
450
451 // TelegramDocument is a file sent without photo compression.
452 type TelegramDocument struct {
453 FileID string `json:"file_id"`
454 MimeType string `json:"mime_type"`
455 FileSize int64 `json:"file_size"`
456 }
457
458 // TelegramChat is the chat of a message. Type is private for a chat with one
459 // user.
460 type TelegramChat struct {
461 ID int64 `json:"id"`
462 Type string `json:"type"`
463 }
464
465 // TelegramUser is the sender of a message.
466 type TelegramUser struct {
467 ID int64 `json:"id"`
468 }