]> git.giacomolli.uk - onechat/blobdiff - telegram_api.go
Require consent and review for autosquash
[onechat] / telegram_api.go
index 8f78387d096b3215de9a0246ec7213f338d1f601..ce4e0e0d5c0522e48b603e31151621dd15476508 100644 (file)
@@ -7,9 +7,11 @@ import (
        "errors"
        "fmt"
        "io"
        "errors"
        "fmt"
        "io"
+       "mime/multipart"
        "net/http"
        "net/url"
        "path"
        "net/http"
        "net/url"
        "path"
+       "strconv"
        "strings"
        "time"
 )
        "strings"
        "time"
 )
@@ -33,11 +35,12 @@ const (
        // its own, because the long poll of getUpdates needs a longer limit.
        telegramSendTimeout = 30 * time.Second
 
        // its own, because the long poll of getUpdates needs a longer limit.
        telegramSendTimeout = 30 * time.Second
 
-       // telegramFileLookupTimeout is the longest wait for image file details.
+       // telegramFileLookupTimeout is the longest wait for media file details.
        telegramFileLookupTimeout = 30 * time.Second
 
        telegramFileLookupTimeout = 30 * time.Second
 
-       // telegramImageDownloadTimeout is the longest wait for image bytes.
-       telegramImageDownloadTimeout = 30 * time.Second
+       // telegramFileDownloadTimeout is the longest wait for downloaded media
+       // bytes.
+       telegramFileDownloadTimeout = 30 * time.Second
 
        // telegramTypingTimeout is the longest wait to show the typing action.
        telegramTypingTimeout = 30 * time.Second
 
        // telegramTypingTimeout is the longest wait to show the typing action.
        telegramTypingTimeout = 30 * time.Second
@@ -46,50 +49,113 @@ const (
        telegramAnswerBytes = 16 << 20
 )
 
        telegramAnswerBytes = 16 << 20
 )
 
-// newTelegramAPI returns the client of the Bot API at base with token.
-func newTelegramAPI(base, token string) *TelegramAPI {
-       return &TelegramAPI{
-               base:  base,
-               token: token,
-               http:  &http.Client{},
-       }
+// TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
+// so no error of TelegramAPI holds a URL, a net/http error, or the token.
+type TelegramAPI struct {
+       base  string
+       token string
+       http  *http.Client
 }
 
 }
 
-// telegramRetryable tells if a later try of a failed Bot API call can work:
-// after a network error, HTTP 429, or a server error. It returns the wait that
-// the Bot API asks for, or 0.
-func telegramRetryable(err error) (bool, time.Duration) {
-       var network *TelegramNetworkError
+// TelegramNetworkError tells that a Bot API call got no valid answer, such as
+// after a network error. A later call can work. Cause tells why in plain words,
+// with no URL and no token.
+type TelegramNetworkError struct {
+       Cause string
+}
 
 
-       if errors.As(err, &network) {
-               return true, 0
-       }
+// TelegramError is an answer of the Bot API that tells of a failure. Its text
+// gives the HTTP status and the description, such as "502 Bad Gateway".
+// RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
+// tells that the answer is a Bot API answer with ok false, not a page of a
+// proxy or of a server error.
+type TelegramError struct {
+       Status      int
+       Description string
+       RetryAfter  time.Duration
+       Refused     bool
+}
 
 
-       var answer *TelegramError
+// TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
+// updates that are not a new message.
+type TelegramUpdate struct {
+       UpdateID int64            `json:"update_id"`
+       Message  *TelegramMessage `json:"message"`
+}
 
 
-       if errors.As(err, &answer) {
-               return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
-       }
+// TelegramEntity is a message entity of sendMessage: a part of the text with a
+// format, such as bold or a link. Offset and Length count UTF-16 code units.
+// URL is the target of a text_link, and Language the language of a pre.
+type TelegramEntity struct {
+       Type     string `json:"type"`
+       Offset   int    `json:"offset"`
+       Length   int    `json:"length"`
+       URL      string `json:"url,omitempty"`
+       Language string `json:"language,omitempty"`
+}
 
 
-       return false, 0
+// TelegramAnswer is the envelope of each answer of the Bot API.
+type TelegramAnswer struct {
+       OK          bool            `json:"ok"`
+       Result      json.RawMessage `json:"result"`
+       ErrorCode   int             `json:"error_code"`
+       Description string          `json:"description"`
+       Parameters  struct {
+               RetryAfter int `json:"retry_after"`
+       } `json:"parameters"`
 }
 
 }
 
-// telegramRejected tells if the Bot API refused a call with ok false and HTTP
-// 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
-// that the method is not there. An error page with no Bot API answer does not
-// tell this, so it is not a refusal.
-func telegramRejected(err error) bool {
-       var answer *TelegramError
+// TelegramMessage holds text and supported media metadata of a bot message.
+type TelegramMessage struct {
+       Chat     TelegramChat      `json:"chat"`
+       From     *TelegramUser     `json:"from"`
+       Text     string            `json:"text"`
+       Caption  string            `json:"caption"`
+       Photo    []TelegramPhoto   `json:"photo"`
+       Document *TelegramDocument `json:"document"`
+       Voice    *TelegramVoice    `json:"voice"`
+}
 
 
-       return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
+// TelegramVoice identifies a voice note in the authenticated file API.
+type TelegramVoice struct {
+       FileID   string `json:"file_id"`
+       FileSize int64  `json:"file_size"`
 }
 
 }
 
-// TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
-// so no error of TelegramAPI holds a URL, a net/http error, or the token.
-type TelegramAPI struct {
-       base  string
-       token string
-       http  *http.Client
+// TelegramPhoto is one supplied size of a photo.
+type TelegramPhoto struct {
+       FileID   string `json:"file_id"`
+       Width    int    `json:"width"`
+       Height   int    `json:"height"`
+       FileSize int64  `json:"file_size"`
+}
+
+// TelegramDocument is a file sent without photo compression.
+type TelegramDocument struct {
+       FileID   string `json:"file_id"`
+       MimeType string `json:"mime_type"`
+       FileSize int64  `json:"file_size"`
+}
+
+// TelegramChat is the chat of a message. Type is private for a chat with one
+// user.
+type TelegramChat struct {
+       ID   int64  `json:"id"`
+       Type string `json:"type"`
+}
+
+// TelegramUser is the sender of a message.
+type TelegramUser struct {
+       ID int64 `json:"id"`
+}
+
+// newTelegramAPI returns the client of the Bot API at base with token.
+func newTelegramAPI(base, token string) *TelegramAPI {
+       return &TelegramAPI{
+               base:  base,
+               token: token,
+               http:  &http.Client{},
+       }
 }
 
 // GetUpdates waits for the updates from offset on, up to
 }
 
 // GetUpdates waits for the updates from offset on, up to
@@ -107,9 +173,110 @@ func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramU
        return updates, err
 }
 
        return updates, err
 }
 
-// GetImage downloads a file through the authenticated file endpoint. Errors
-// never include its token or URL, and the body is limited before storage.
-func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) {
+// call sends one call of method with the JSON params and decodes its result
+// into result, when result is not nil. The call can take up to timeout. Its
+// request setup errors name the method. Network and answer errors give a safe
+// cause, so the caller can add the operation without exposing the request URL.
+func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
+       ctx, cancel := context.WithTimeout(ctx, timeout)
+       defer cancel()
+
+       body, err := json.Marshal(params)
+       if err != nil {
+               return fmt.Errorf("%s: encode request: %w", method, err)
+       }
+
+       request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
+       if err != nil {
+               return fmt.Errorf("%s: make request: %s", method, b.redact(err))
+       }
+
+       request.Header.Set("Content-Type", "application/json")
+
+       return b.answer(request, timeout, result)
+}
+
+// redact returns the text of err without a URL and without the token. A
+// *url.Error holds the URL of the call, which holds the token, so only its
+// cause is kept.
+func (b *TelegramAPI) redact(err error) string {
+       var urlError *url.Error
+
+       if errors.As(err, &urlError) {
+               err = urlError.Err
+       }
+
+       return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
+}
+
+// answer reads the bounded Bot API response without keeping its request URL.
+func (b *TelegramAPI) answer(request *http.Request, timeout time.Duration, result any) error {
+       response, err := b.http.Do(request)
+       if err != nil {
+               return b.networkError("no answer", err, timeout)
+       }
+
+       data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
+       err = errors.Join(err, response.Body.Close())
+       if err != nil {
+               return b.networkError("answer cut off", err, timeout)
+       }
+
+       var answer TelegramAnswer
+
+       err = json.Unmarshal(data, &answer)
+       if err != nil && response.StatusCode != http.StatusOK {
+               return &TelegramError{
+                       Status:      response.StatusCode,
+                       Description: http.StatusText(response.StatusCode),
+               }
+       }
+
+       if err != nil {
+               return b.networkError("invalid JSON", err, timeout)
+       }
+
+       if !answer.OK {
+               return &TelegramError{
+                       Status:      response.StatusCode,
+                       Description: b.redact(errors.New(answer.Description)),
+                       RetryAfter:  time.Duration(answer.Parameters.RetryAfter) * time.Second,
+                       Refused:     true,
+               }
+       }
+
+       if result == nil {
+               return nil
+       }
+
+       err = json.Unmarshal(answer.Result, result)
+       if err != nil {
+               return b.networkError("invalid result", err, timeout)
+       }
+
+       return nil
+}
+
+// networkError returns the TelegramNetworkError of err, which happened at the
+// step that what names. When the call used all of its time timeout, the cause
+// is "no answer in TIMEOUT", because the Go text of a deadline does not tell
+// how long the wait was.
+func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
+       if errors.Is(err, context.DeadlineExceeded) {
+               return &TelegramNetworkError{
+                       Cause: "no answer in " + timeout.String(),
+               }
+       }
+
+       return &TelegramNetworkError{
+               Cause: what + ": " + b.redact(err),
+       }
+}
+
+// GetFile downloads bounded media through the authenticated file endpoint.
+// Errors never include its token or URL, and the body is limited before
+// storage.
+func (b *TelegramAPI) GetFile(ctx context.Context, id string, limit int64, tooLarge error) (data []byte, err error) {
        var file struct {
                Path string `json:"file_path"`
                Size int64  `json:"file_size"`
        var file struct {
                Path string `json:"file_path"`
                Size int64  `json:"file_size"`
@@ -117,34 +284,34 @@ func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err
 
        err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
        if err != nil {
 
        err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
        if err != nil {
-               return nil, fmt.Errorf("get image file: %w", err)
+               return nil, fmt.Errorf("get media file: %w", err)
        }
 
        }
 
-       if file.Size > imageMaxBytes {
-               return nil, errImageSize
+       if file.Size > limit {
+               return nil, tooLarge
        }
 
        if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
        }
 
        if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
-               return nil, errors.New("invalid image file path")
+               return nil, errors.New("invalid media file path")
        }
 
        }
 
-       ctx, cancel := context.WithTimeout(ctx, telegramImageDownloadTimeout)
+       ctx, cancel := context.WithTimeout(ctx, telegramFileDownloadTimeout)
        defer cancel()
 
        request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
        if err != nil {
        defer cancel()
 
        request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
        if err != nil {
-               return nil, fmt.Errorf("make image request: %s", b.redact(err))
+               return nil, fmt.Errorf("make media request: %s", b.redact(err))
        }
 
        response, err := b.http.Do(request)
        if err != nil {
        }
 
        response, err := b.http.Do(request)
        if err != nil {
-               return nil, b.networkError("image download failed", err, telegramImageDownloadTimeout)
+               return nil, b.networkError("media download failed", err, telegramFileDownloadTimeout)
        }
 
        defer func() {
                closeErr := response.Body.Close()
                if closeErr != nil {
        }
 
        defer func() {
                closeErr := response.Body.Close()
                if closeErr != nil {
-                       err = errors.Join(err, b.networkError("close image download", closeErr, telegramImageDownloadTimeout))
+                       err = errors.Join(err, b.networkError("close media download", closeErr, telegramFileDownloadTimeout))
                }
        }()
 
                }
        }()
 
@@ -155,13 +322,13 @@ func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err
                }
        }
 
                }
        }
 
-       data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1))
+       data, err = io.ReadAll(io.LimitReader(response.Body, limit+1))
        if err != nil {
        if err != nil {
-               return nil, b.networkError("image cut off", err, telegramImageDownloadTimeout)
+               return nil, b.networkError("media cut off", err, telegramFileDownloadTimeout)
        }
 
        }
 
-       if len(data) > imageMaxBytes {
-               return nil, errImageSize
+       if int64(len(data)) > limit {
+               return nil, tooLarge
        }
 
        return data, nil
        }
 
        return data, nil
@@ -196,200 +363,107 @@ func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown
        }, nil)
 }
 
        }, nil)
 }
 
-// SendTyping shows the typing action in chat for about five seconds. A call
-// that takes longer than telegramTypingTimeout fails with a
-// TelegramNetworkError.
-func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
-       return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
-               "chat_id": chat,
-               "action":  "typing",
-       }, nil)
+// SendImage uploads an image to the owner as a photo, or as a document when the
+// Bot API refuses the photo. Network failures do not trigger a second send.
+func (b *TelegramAPI) SendImage(ctx context.Context, chat int64, name string, data []byte, caption string) error {
+       err := b.sendImage(ctx, "sendPhoto", "photo", chat, name, data, caption)
+       if telegramRejected(err) {
+               err = b.sendImage(ctx, "sendDocument", "document", chat, name, data, caption)
+       }
+
+       return err
 }
 
 }
 
-// call sends one call of method with the JSON params and decodes its result
-// into result, when result is not nil. The call can take up to timeout. Its
-// errors tell the cause in plain words, with no method name, so that a log line
-// can say first what the call was for.
-func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
-       ctx, cancel := context.WithTimeout(ctx, timeout)
+func (b *TelegramAPI) sendImage(ctx context.Context, method, field string, chat int64, name string, data []byte, caption string) error {
+       ctx, cancel := context.WithTimeout(ctx, telegramSendTimeout)
        defer cancel()
 
        defer cancel()
 
-       body, err := json.Marshal(params)
-       if err != nil {
-               return fmt.Errorf("%s: encode request: %w", method, err)
-       }
+       var body bytes.Buffer
 
 
-       request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
+       writer := multipart.NewWriter(&body)
+       err := writer.WriteField("chat_id", strconv.FormatInt(chat, 10))
        if err != nil {
        if err != nil {
-               return fmt.Errorf("%s: make request: %s", method, b.redact(err))
+               return fmt.Errorf("write image chat: %w", err)
        }
 
        }
 
-       request.Header.Set("Content-Type", "application/json")
-
-       response, err := b.http.Do(request)
+       err = writer.WriteField("caption", caption)
        if err != nil {
        if err != nil {
-               return b.networkError("no answer", err, timeout)
+               return fmt.Errorf("write image caption: %w", err)
        }
 
        }
 
-       data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
-       err = errors.Join(err, response.Body.Close())
+       part, err := writer.CreateFormFile(field, name)
        if err != nil {
        if err != nil {
-               return b.networkError("answer cut off", err, timeout)
+               return fmt.Errorf("make image part: %w", err)
        }
 
        }
 
-       var answer TelegramAnswer
-
-       err = json.Unmarshal(data, &answer)
-       if err != nil && response.StatusCode != http.StatusOK {
-               return &TelegramError{
-                       Status:      response.StatusCode,
-                       Description: http.StatusText(response.StatusCode),
-               }
+       _, err = part.Write(data)
+       if err != nil {
+               return fmt.Errorf("write image part: %w", err)
        }
 
        }
 
+       err = writer.Close()
        if err != nil {
        if err != nil {
-               return b.networkError("invalid JSON", err, timeout)
+               return fmt.Errorf("close image form: %w", err)
        }
 
        }
 
-       if !answer.OK {
-               return &TelegramError{
-                       Status:      response.StatusCode,
-                       Description: b.redact(errors.New(answer.Description)),
-                       RetryAfter:  time.Duration(answer.Parameters.RetryAfter) * time.Second,
-                       Refused:     true,
-               }
+       request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, &body)
+       if err != nil {
+               return fmt.Errorf("make image upload: %s", b.redact(err))
        }
 
        }
 
-       if result == nil {
-               return nil
-       }
+       request.Header.Set("Content-Type", writer.FormDataContentType())
 
 
-       err = json.Unmarshal(answer.Result, result)
+       err = b.answer(request, telegramSendTimeout, nil)
        if err != nil {
        if err != nil {
-               return b.networkError("invalid result", err, timeout)
+               return fmt.Errorf("upload image: %w", err)
        }
 
        return nil
 }
 
        }
 
        return nil
 }
 
-// networkError returns the TelegramNetworkError of err, which happened at the
-// step that what names. When the call used all of its time timeout, the cause
-// is "no answer in TIMEOUT", because the Go text of a deadline does not tell
-// how long the wait was.
-func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
-       if errors.Is(err, context.DeadlineExceeded) {
-               return &TelegramNetworkError{
-                       Cause: "no answer in " + timeout.String(),
-               }
-       }
-
-       return &TelegramNetworkError{
-               Cause: what + ": " + b.redact(err),
-       }
-}
-
-// redact returns the text of err without a URL and without the token. A
-// *url.Error holds the URL of the call, which holds the token, so only its
-// cause is kept.
-func (b *TelegramAPI) redact(err error) string {
-       var urlError *url.Error
-
-       if errors.As(err, &urlError) {
-               err = urlError.Err
-       }
-
-       return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
-}
-
-// TelegramNetworkError tells that a Bot API call got no valid answer, such as
-// after a network error. A later call can work. Cause tells why in plain words,
-// with no URL and no token.
-type TelegramNetworkError struct {
-       Cause string
+// SendTyping shows the typing action in chat for about five seconds. A call
+// that takes longer than telegramTypingTimeout fails with a
+// TelegramNetworkError.
+func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
+       return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
+               "chat_id": chat,
+               "action":  "typing",
+       }, nil)
 }
 
 func (e *TelegramNetworkError) Error() string {
        return e.Cause
 }
 
 }
 
 func (e *TelegramNetworkError) Error() string {
        return e.Cause
 }
 
-// TelegramError is an answer of the Bot API that tells of a failure. Its text
-// gives the HTTP status and the description, such as "502 Bad Gateway".
-// RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
-// tells that the answer is a Bot API answer with ok false, not a page of a
-// proxy or of a server error.
-type TelegramError struct {
-       Status      int
-       Description string
-       RetryAfter  time.Duration
-       Refused     bool
-}
-
 func (e *TelegramError) Error() string {
        return fmt.Sprintf("%d %s", e.Status, e.Description)
 }
 
 func (e *TelegramError) Error() string {
        return fmt.Sprintf("%d %s", e.Status, e.Description)
 }
 
-// TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
-// updates that are not a new message.
-type TelegramUpdate struct {
-       UpdateID int64            `json:"update_id"`
-       Message  *TelegramMessage `json:"message"`
-}
-
-// TelegramEntity is a message entity of sendMessage: a part of the text with a
-// format, such as bold or a link. Offset and Length count UTF-16 code units.
-// URL is the target of a text_link, and Language the language of a pre.
-type TelegramEntity struct {
-       Type     string `json:"type"`
-       Offset   int    `json:"offset"`
-       Length   int    `json:"length"`
-       URL      string `json:"url,omitempty"`
-       Language string `json:"language,omitempty"`
-}
+// telegramRejected tells if the Bot API refused a call with ok false and HTTP
+// 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
+// that the method is not there. An error page with no Bot API answer does not
+// tell this, so it is not a refusal.
+func telegramRejected(err error) bool {
+       var answer *TelegramError
 
 
-// TelegramAnswer is the envelope of each answer of the Bot API.
-type TelegramAnswer struct {
-       OK          bool            `json:"ok"`
-       Result      json.RawMessage `json:"result"`
-       ErrorCode   int             `json:"error_code"`
-       Description string          `json:"description"`
-       Parameters  struct {
-               RetryAfter int `json:"retry_after"`
-       } `json:"parameters"`
+       return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
 }
 
 }
 
-// TelegramMessage holds the text, caption, and image sizes of a bot message.
-type TelegramMessage struct {
-       Chat     TelegramChat      `json:"chat"`
-       From     *TelegramUser     `json:"from"`
-       Text     string            `json:"text"`
-       Caption  string            `json:"caption"`
-       Photo    []TelegramPhoto   `json:"photo"`
-       Document *TelegramDocument `json:"document"`
-}
+// telegramRetryable tells if a later try of a failed Bot API call can work:
+// after a network error, HTTP 429, or a server error. It returns the wait that
+// the Bot API asks for, or 0.
+func telegramRetryable(err error) (bool, time.Duration) {
+       var network *TelegramNetworkError
 
 
-// TelegramPhoto is one supplied size of a photo.
-type TelegramPhoto struct {
-       FileID   string `json:"file_id"`
-       Width    int    `json:"width"`
-       Height   int    `json:"height"`
-       FileSize int64  `json:"file_size"`
-}
+       if errors.As(err, &network) {
+               return true, 0
+       }
 
 
-// TelegramDocument is a file sent without photo compression.
-type TelegramDocument struct {
-       FileID   string `json:"file_id"`
-       MimeType string `json:"mime_type"`
-       FileSize int64  `json:"file_size"`
-}
+       var answer *TelegramError
 
 
-// TelegramChat is the chat of a message. Type is private for a chat with one
-// user.
-type TelegramChat struct {
-       ID   int64  `json:"id"`
-       Type string `json:"type"`
-}
+       if errors.As(err, &answer) {
+               return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
+       }
 
 
-// TelegramUser is the sender of a message.
-type TelegramUser struct {
-       ID int64 `json:"id"`
+       return false, 0
 }
 }