20 // telegramUpdateWaitTimeout is how long one getUpdates call waits for
22 telegramUpdateWaitTimeout = 50 * time.Second
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
28 // telegramPollTimeout is how long one getUpdates call can take.
29 telegramPollTimeout = telegramUpdateWaitTimeout + telegramPollSlack
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
38 // telegramFileLookupTimeout is the longest wait for media file details.
39 telegramFileLookupTimeout = 30 * time.Second
41 // telegramFileDownloadTimeout is the longest wait for downloaded media
43 telegramFileDownloadTimeout = 30 * time.Second
45 // telegramTypingTimeout is the longest wait to show the typing action.
46 telegramTypingTimeout = 30 * time.Second
48 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
49 telegramAnswerBytes = 16 << 20
52 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
53 // so no error of TelegramAPI holds a URL, a net/http error, or the token.
54 type TelegramAPI struct {
60 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
61 // after a network error. A later call can work. Cause tells why in plain words,
62 // with no URL and no token.
63 type TelegramNetworkError struct {
67 // TelegramError is an answer of the Bot API that tells of a failure. Its text
68 // gives the HTTP status and the description, such as "502 Bad Gateway".
69 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
70 // tells that the answer is a Bot API answer with ok false, not a page of a
71 // proxy or of a server error.
72 type TelegramError struct {
75 RetryAfter time.Duration
79 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
80 // updates that are not a new message.
81 type TelegramUpdate struct {
82 UpdateID int64 `json:"update_id"`
83 Message *TelegramMessage `json:"message"`
86 // TelegramEntity is a message entity of sendMessage: a part of the text with a
87 // format, such as bold or a link. Offset and Length count UTF-16 code units.
88 // URL is the target of a text_link, and Language the language of a pre.
89 type TelegramEntity struct {
90 Type string `json:"type"`
91 Offset int `json:"offset"`
92 Length int `json:"length"`
93 URL string `json:"url,omitempty"`
94 Language string `json:"language,omitempty"`
97 // TelegramAnswer is the envelope of each answer of the Bot API.
98 type TelegramAnswer struct {
100 Result json.RawMessage `json:"result"`
101 ErrorCode int `json:"error_code"`
102 Description string `json:"description"`
104 RetryAfter int `json:"retry_after"`
105 } `json:"parameters"`
108 // TelegramMessage holds text and supported media metadata of a bot message.
109 type TelegramMessage struct {
110 Chat TelegramChat `json:"chat"`
111 From *TelegramUser `json:"from"`
112 Text string `json:"text"`
113 Caption string `json:"caption"`
114 Photo []TelegramPhoto `json:"photo"`
115 Document *TelegramDocument `json:"document"`
116 Voice *TelegramVoice `json:"voice"`
119 // TelegramVoice identifies a voice note in the authenticated file API.
120 type TelegramVoice struct {
121 FileID string `json:"file_id"`
122 FileSize int64 `json:"file_size"`
125 // TelegramPhoto is one supplied size of a photo.
126 type TelegramPhoto struct {
127 FileID string `json:"file_id"`
128 Width int `json:"width"`
129 Height int `json:"height"`
130 FileSize int64 `json:"file_size"`
133 // TelegramDocument is a file sent without photo compression.
134 type TelegramDocument struct {
135 FileID string `json:"file_id"`
136 MimeType string `json:"mime_type"`
137 FileSize int64 `json:"file_size"`
140 // TelegramChat is the chat of a message. Type is private for a chat with one
142 type TelegramChat struct {
144 Type string `json:"type"`
147 // TelegramUser is the sender of a message.
148 type TelegramUser struct {
152 // newTelegramAPI returns the client of the Bot API at base with token.
153 func newTelegramAPI(base, token string) *TelegramAPI {
157 http: &http.Client{},
161 // GetUpdates waits for the updates from offset on, up to
162 // telegramUpdateWaitTimeout, and returns them. Telegram forgets each update
163 // before offset. Only new messages are asked for.
164 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
165 var updates []TelegramUpdate
167 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
169 "timeout": int(telegramUpdateWaitTimeout / time.Second),
170 "allowed_updates": []string{"message"},
176 // GetFile downloads bounded media through the authenticated file endpoint.
177 // Errors never include its token or URL, and the body is limited before
179 func (b *TelegramAPI) GetFile(ctx context.Context, id string, limit int64, tooLarge error) (data []byte, err error) {
181 Path string `json:"file_path"`
182 Size int64 `json:"file_size"`
185 err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
187 return nil, fmt.Errorf("get media file: %w", err)
190 if file.Size > limit {
194 if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
195 return nil, errors.New("invalid media file path")
198 ctx, cancel := context.WithTimeout(ctx, telegramFileDownloadTimeout)
201 request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
203 return nil, fmt.Errorf("make media request: %s", b.redact(err))
206 response, err := b.http.Do(request)
208 return nil, b.networkError("media download failed", err, telegramFileDownloadTimeout)
212 closeErr := response.Body.Close()
214 err = errors.Join(err, b.networkError("close media download", closeErr, telegramFileDownloadTimeout))
218 if response.StatusCode != http.StatusOK {
219 return nil, &TelegramError{
220 Status: response.StatusCode,
221 Description: http.StatusText(response.StatusCode),
225 data, err = io.ReadAll(io.LimitReader(response.Body, limit+1))
227 return nil, b.networkError("media cut off", err, telegramFileDownloadTimeout)
230 if int64(len(data)) > limit {
237 // SendMessage sends text to chat with the format of entities, with no parse
238 // mode, so the text needs no escaping. With no entities, the text is plain. A
239 // call that takes longer than telegramSendTimeout fails with a
240 // TelegramNetworkError.
241 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
242 params := map[string]any{
247 if len(entities) > 0 {
248 params["entities"] = entities
251 return b.call(ctx, telegramSendTimeout, "sendMessage", params, nil)
254 // SendRichMessage sends markdown to chat as a rich message, which Telegram
255 // renders itself, tables included. A call that takes longer than
256 // telegramSendTimeout fails with a TelegramNetworkError.
257 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
258 return b.call(ctx, telegramSendTimeout, "sendRichMessage", map[string]any{
260 "rich_message": map[string]any{
261 "markdown": markdown,
266 // SendImage uploads an image to the owner as a photo, or as a document when the
267 // Bot API refuses the photo. Network failures do not trigger a second send.
268 func (b *TelegramAPI) SendImage(ctx context.Context, chat int64, name string, data []byte, caption string) error {
269 err := b.sendImage(ctx, "sendPhoto", "photo", chat, name, data, caption)
270 if telegramRejected(err) {
271 err = b.sendImage(ctx, "sendDocument", "document", chat, name, data, caption)
277 func (b *TelegramAPI) sendImage(ctx context.Context, method, field string, chat int64, name string, data []byte, caption string) error {
278 ctx, cancel := context.WithTimeout(ctx, telegramSendTimeout)
281 var body bytes.Buffer
283 writer := multipart.NewWriter(&body)
284 err := writer.WriteField("chat_id", strconv.FormatInt(chat, 10))
286 return fmt.Errorf("write image chat: %w", err)
289 err = writer.WriteField("caption", caption)
291 return fmt.Errorf("write image caption: %w", err)
294 part, err := writer.CreateFormFile(field, name)
296 return fmt.Errorf("make image part: %w", err)
299 _, err = part.Write(data)
301 return fmt.Errorf("write image part: %w", err)
306 return fmt.Errorf("close image form: %w", err)
309 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, &body)
311 return fmt.Errorf("make image upload: %s", b.redact(err))
314 request.Header.Set("Content-Type", writer.FormDataContentType())
316 err = b.answer(request, telegramSendTimeout, nil)
318 return fmt.Errorf("upload image: %w", err)
324 // SendTyping shows the typing action in chat for about five seconds. A call
325 // that takes longer than telegramTypingTimeout fails with a
326 // TelegramNetworkError.
327 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
328 return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
334 // call sends one call of method with the JSON params and decodes its result
335 // into result, when result is not nil. The call can take up to timeout. Its
336 // errors tell the cause in plain words, with no method name, so that a log line
337 // can say first what the call was for.
338 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
339 ctx, cancel := context.WithTimeout(ctx, timeout)
342 body, err := json.Marshal(params)
344 return fmt.Errorf("%s: encode request: %w", method, err)
347 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
349 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
352 request.Header.Set("Content-Type", "application/json")
354 return b.answer(request, timeout, result)
357 // answer reads the bounded Bot API response without keeping its request URL.
358 func (b *TelegramAPI) answer(request *http.Request, timeout time.Duration, result any) error {
359 response, err := b.http.Do(request)
361 return b.networkError("no answer", err, timeout)
364 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
365 err = errors.Join(err, response.Body.Close())
367 return b.networkError("answer cut off", err, timeout)
370 var answer TelegramAnswer
372 err = json.Unmarshal(data, &answer)
373 if err != nil && response.StatusCode != http.StatusOK {
374 return &TelegramError{
375 Status: response.StatusCode,
376 Description: http.StatusText(response.StatusCode),
381 return b.networkError("invalid JSON", err, timeout)
385 return &TelegramError{
386 Status: response.StatusCode,
387 Description: b.redact(errors.New(answer.Description)),
388 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
397 err = json.Unmarshal(answer.Result, result)
399 return b.networkError("invalid result", err, timeout)
405 // networkError returns the TelegramNetworkError of err, which happened at the
406 // step that what names. When the call used all of its time timeout, the cause
407 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
408 // how long the wait was.
409 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
410 if errors.Is(err, context.DeadlineExceeded) {
411 return &TelegramNetworkError{
412 Cause: "no answer in " + timeout.String(),
416 return &TelegramNetworkError{
417 Cause: what + ": " + b.redact(err),
421 // redact returns the text of err without a URL and without the token. A
422 // *url.Error holds the URL of the call, which holds the token, so only its
424 func (b *TelegramAPI) redact(err error) string {
425 var urlError *url.Error
427 if errors.As(err, &urlError) {
431 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
434 func (e *TelegramNetworkError) Error() string {
438 func (e *TelegramError) Error() string {
439 return fmt.Sprintf("%d %s", e.Status, e.Description)
442 // telegramRetryable tells if a later try of a failed Bot API call can work:
443 // after a network error, HTTP 429, or a server error. It returns the wait that
444 // the Bot API asks for, or 0.
445 func telegramRetryable(err error) (bool, time.Duration) {
446 var network *TelegramNetworkError
448 if errors.As(err, &network) {
452 var answer *TelegramError
454 if errors.As(err, &answer) {
455 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
461 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
462 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
463 // that the method is not there. An error page with no Bot API answer does not
464 // tell this, so it is not a refusal.
465 func telegramRejected(err error) bool {
466 var answer *TelegramError
468 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)