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