18 // telegramUpdateWaitTimeout is how long one getUpdates call waits for
20 telegramUpdateWaitTimeout = 50 * time.Second
22 // telegramPollSlack is how much longer than telegramUpdateWaitTimeout a
23 // getUpdates call can take before the bot gives it up.
24 telegramPollSlack = 20 * time.Second
26 // telegramPollTimeout is how long one getUpdates call can take.
27 telegramPollTimeout = telegramUpdateWaitTimeout + telegramPollSlack
29 // telegramSendTimeout is how long a sendMessage or sendRichMessage call
30 // can take. A connection that stops without a close, such as after a
31 // network change, then fails the call, and the sender tries again,
32 // instead of a wait until TCP gives up. The client has no timeout of
33 // its own, because the long poll of getUpdates needs a longer limit.
34 telegramSendTimeout = 30 * time.Second
36 // telegramFileLookupTimeout is the longest wait for image file details.
37 telegramFileLookupTimeout = 30 * time.Second
39 // telegramImageDownloadTimeout is the longest wait for image bytes.
40 telegramImageDownloadTimeout = 30 * time.Second
42 // telegramTypingTimeout is the longest wait to show the typing action.
43 telegramTypingTimeout = 30 * time.Second
45 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
46 telegramAnswerBytes = 16 << 20
49 // newTelegramAPI returns the client of the Bot API at base with token.
50 func newTelegramAPI(base, token string) *TelegramAPI {
58 // telegramRetryable tells if a later try of a failed Bot API call can work:
59 // after a network error, HTTP 429, or a server error. It returns the wait that
60 // the Bot API asks for, or 0.
61 func telegramRetryable(err error) (bool, time.Duration) {
62 var network *TelegramNetworkError
64 if errors.As(err, &network) {
68 var answer *TelegramError
70 if errors.As(err, &answer) {
71 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
77 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
78 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
79 // that the method is not there. An error page with no Bot API answer does not
80 // tell this, so it is not a refusal.
81 func telegramRejected(err error) bool {
82 var answer *TelegramError
84 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
87 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
88 // so no error of TelegramAPI holds a URL, a net/http error, or the token.
89 type TelegramAPI struct {
95 // GetUpdates waits for the updates from offset on, up to
96 // telegramUpdateWaitTimeout, and returns them. Telegram forgets each update
97 // before offset. Only new messages are asked for.
98 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
99 var updates []TelegramUpdate
101 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
103 "timeout": int(telegramUpdateWaitTimeout / time.Second),
104 "allowed_updates": []string{"message"},
110 // GetImage downloads a file through the authenticated file endpoint. Errors
111 // never include its token or URL, and the body is limited before storage.
112 func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) {
114 Path string `json:"file_path"`
115 Size int64 `json:"file_size"`
118 err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
120 return nil, fmt.Errorf("get image file: %w", err)
123 if file.Size > imageMaxBytes {
124 return nil, errImageSize
127 if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
128 return nil, errors.New("invalid image file path")
131 ctx, cancel := context.WithTimeout(ctx, telegramImageDownloadTimeout)
134 request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
136 return nil, fmt.Errorf("make image request: %s", b.redact(err))
139 response, err := b.http.Do(request)
141 return nil, b.networkError("image download failed", err, telegramImageDownloadTimeout)
145 closeErr := response.Body.Close()
147 err = errors.Join(err, b.networkError("close image download", closeErr, telegramImageDownloadTimeout))
151 if response.StatusCode != http.StatusOK {
152 return nil, &TelegramError{
153 Status: response.StatusCode,
154 Description: http.StatusText(response.StatusCode),
158 data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1))
160 return nil, b.networkError("image cut off", err, telegramImageDownloadTimeout)
163 if len(data) > imageMaxBytes {
164 return nil, errImageSize
170 // SendMessage sends text to chat with the format of entities, with no parse
171 // mode, so the text needs no escaping. With no entities, the text is plain. A
172 // call that takes longer than telegramSendTimeout fails with a
173 // TelegramNetworkError.
174 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
175 params := map[string]any{
180 if len(entities) > 0 {
181 params["entities"] = entities
184 return b.call(ctx, telegramSendTimeout, "sendMessage", params, nil)
187 // SendRichMessage sends markdown to chat as a rich message, which Telegram
188 // renders itself, tables included. A call that takes longer than
189 // telegramSendTimeout fails with a TelegramNetworkError.
190 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
191 return b.call(ctx, telegramSendTimeout, "sendRichMessage", map[string]any{
193 "rich_message": map[string]any{
194 "markdown": markdown,
199 // SendTyping shows the typing action in chat for about five seconds. A call
200 // that takes longer than telegramTypingTimeout fails with a
201 // TelegramNetworkError.
202 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
203 return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
209 // call sends one call of method with the JSON params and decodes its result
210 // into result, when result is not nil. The call can take up to timeout. Its
211 // errors tell the cause in plain words, with no method name, so that a log line
212 // can say first what the call was for.
213 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
214 ctx, cancel := context.WithTimeout(ctx, timeout)
217 body, err := json.Marshal(params)
219 return fmt.Errorf("%s: encode request: %w", method, err)
222 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
224 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
227 request.Header.Set("Content-Type", "application/json")
229 response, err := b.http.Do(request)
231 return b.networkError("no answer", err, timeout)
234 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
235 err = errors.Join(err, response.Body.Close())
237 return b.networkError("answer cut off", err, timeout)
240 var answer TelegramAnswer
242 err = json.Unmarshal(data, &answer)
243 if err != nil && response.StatusCode != http.StatusOK {
244 return &TelegramError{
245 Status: response.StatusCode,
246 Description: http.StatusText(response.StatusCode),
251 return b.networkError("invalid JSON", err, timeout)
255 return &TelegramError{
256 Status: response.StatusCode,
257 Description: b.redact(errors.New(answer.Description)),
258 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
267 err = json.Unmarshal(answer.Result, result)
269 return b.networkError("invalid result", err, timeout)
275 // networkError returns the TelegramNetworkError of err, which happened at the
276 // step that what names. When the call used all of its time timeout, the cause
277 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
278 // how long the wait was.
279 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
280 if errors.Is(err, context.DeadlineExceeded) {
281 return &TelegramNetworkError{
282 Cause: "no answer in " + timeout.String(),
286 return &TelegramNetworkError{
287 Cause: what + ": " + b.redact(err),
291 // redact returns the text of err without a URL and without the token. A
292 // *url.Error holds the URL of the call, which holds the token, so only its
294 func (b *TelegramAPI) redact(err error) string {
295 var urlError *url.Error
297 if errors.As(err, &urlError) {
301 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
304 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
305 // after a network error. A later call can work. Cause tells why in plain words,
306 // with no URL and no token.
307 type TelegramNetworkError struct {
311 func (e *TelegramNetworkError) Error() string {
315 // TelegramError is an answer of the Bot API that tells of a failure. Its text
316 // gives the HTTP status and the description, such as "502 Bad Gateway".
317 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
318 // tells that the answer is a Bot API answer with ok false, not a page of a
319 // proxy or of a server error.
320 type TelegramError struct {
323 RetryAfter time.Duration
327 func (e *TelegramError) Error() string {
328 return fmt.Sprintf("%d %s", e.Status, e.Description)
331 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
332 // updates that are not a new message.
333 type TelegramUpdate struct {
334 UpdateID int64 `json:"update_id"`
335 Message *TelegramMessage `json:"message"`
338 // TelegramEntity is a message entity of sendMessage: a part of the text with a
339 // format, such as bold or a link. Offset and Length count UTF-16 code units.
340 // URL is the target of a text_link, and Language the language of a pre.
341 type TelegramEntity struct {
342 Type string `json:"type"`
343 Offset int `json:"offset"`
344 Length int `json:"length"`
345 URL string `json:"url,omitempty"`
346 Language string `json:"language,omitempty"`
349 // TelegramAnswer is the envelope of each answer of the Bot API.
350 type TelegramAnswer struct {
352 Result json.RawMessage `json:"result"`
353 ErrorCode int `json:"error_code"`
354 Description string `json:"description"`
356 RetryAfter int `json:"retry_after"`
357 } `json:"parameters"`
360 // TelegramMessage holds the text, caption, and image sizes of a bot message.
361 type TelegramMessage struct {
362 Chat TelegramChat `json:"chat"`
363 From *TelegramUser `json:"from"`
364 Text string `json:"text"`
365 Caption string `json:"caption"`
366 Photo []TelegramPhoto `json:"photo"`
367 Document *TelegramDocument `json:"document"`
370 // TelegramPhoto is one supplied size of a photo.
371 type TelegramPhoto struct {
372 FileID string `json:"file_id"`
373 Width int `json:"width"`
374 Height int `json:"height"`
375 FileSize int64 `json:"file_size"`
378 // TelegramDocument is a file sent without photo compression.
379 type TelegramDocument struct {
380 FileID string `json:"file_id"`
381 MimeType string `json:"mime_type"`
382 FileSize int64 `json:"file_size"`
385 // TelegramChat is the chat of a message. Type is private for a chat with one
387 type TelegramChat struct {
389 Type string `json:"type"`
392 // TelegramUser is the sender of a message.
393 type TelegramUser struct {