18 // telegramPollSeconds is how long one getUpdates call waits for an
20 telegramPollSeconds = 50
22 // telegramPollSlack is how much longer than telegramPollSeconds 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 = telegramPollSeconds*time.Second + telegramPollSlack
29 // telegramSendTimeout is how long a sendMessage, sendRichMessage, or
30 // sendChatAction call can take. A connection that stops without a
31 // close, such as after a network change, then fails the call, and the
32 // sender tries again, instead of a wait until TCP gives up. The client
33 // has no timeout of its own, because the long poll of getUpdates needs
35 telegramSendTimeout = 30 * time.Second
37 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
38 telegramAnswerBytes = 16 << 20
41 // newTelegramAPI returns the client of the Bot API at base with token.
42 func newTelegramAPI(base, token string) *TelegramAPI {
47 sendTimeout: telegramSendTimeout,
51 // telegramRetryable tells if a later try of a failed Bot API call can work:
52 // after a network error, HTTP 429, or a server error. It returns the wait that
53 // the Bot API asks for, or 0.
54 func telegramRetryable(err error) (bool, time.Duration) {
55 var network *TelegramNetworkError
57 if errors.As(err, &network) {
61 var answer *TelegramError
63 if errors.As(err, &answer) {
64 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
70 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
71 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
72 // that the method is not there. An error page with no Bot API answer does not
73 // tell this, so it is not a refusal.
74 func telegramRejected(err error) bool {
75 var answer *TelegramError
77 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
80 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
81 // so no error of TelegramAPI holds a URL, a net/http error, or the token. Its
82 // sendTimeout field limits each sendMessage, sendRichMessage, and
83 // sendChatAction call.
84 type TelegramAPI struct {
88 sendTimeout time.Duration
91 // GetUpdates waits for the updates from offset on, up to telegramPollSeconds,
92 // and returns them. Telegram forgets each update before offset. Only new
93 // messages are asked for.
94 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
95 var updates []TelegramUpdate
97 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
99 "timeout": telegramPollSeconds,
100 "allowed_updates": []string{"message"},
106 // GetImage downloads a file through the authenticated file endpoint. Errors
107 // never include its token or URL, and the body is limited before storage.
108 func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) {
110 Path string `json:"file_path"`
111 Size int64 `json:"file_size"`
114 err = b.call(ctx, b.sendTimeout, "getFile", map[string]any{"file_id": id}, &file)
116 return nil, fmt.Errorf("get image file: %w", err)
119 if file.Size > imageMaxBytes {
120 return nil, errImageSize
123 if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
124 return nil, errors.New("invalid image file path")
127 ctx, cancel := context.WithTimeout(ctx, b.sendTimeout)
130 request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
132 return nil, fmt.Errorf("make image request: %s", b.redact(err))
135 response, err := b.http.Do(request)
137 return nil, b.networkError("image download failed", err, b.sendTimeout)
141 closeErr := response.Body.Close()
143 err = errors.Join(err, b.networkError("close image download", closeErr, b.sendTimeout))
147 if response.StatusCode != http.StatusOK {
148 return nil, &TelegramError{
149 Status: response.StatusCode,
150 Description: http.StatusText(response.StatusCode),
154 data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1))
156 return nil, b.networkError("image cut off", err, b.sendTimeout)
159 if len(data) > imageMaxBytes {
160 return nil, errImageSize
166 // SendMessage sends text to chat with the format of entities, with no parse
167 // mode, so the text needs no escaping. With no entities, the text is plain. A
168 // call that takes longer than telegramSendTimeout fails with a
169 // TelegramNetworkError.
170 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
171 params := map[string]any{
176 if len(entities) > 0 {
177 params["entities"] = entities
180 return b.call(ctx, b.sendTimeout, "sendMessage", params, nil)
183 // SendRichMessage sends markdown to chat as a rich message, which Telegram
184 // renders itself, tables included. A call that takes longer than
185 // telegramSendTimeout fails with a TelegramNetworkError.
186 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
187 return b.call(ctx, b.sendTimeout, "sendRichMessage", map[string]any{
189 "rich_message": map[string]any{
190 "markdown": markdown,
195 // SendTyping shows the typing action in chat for about five seconds. A call
196 // that takes longer than telegramSendTimeout fails with a TelegramNetworkError.
197 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
198 return b.call(ctx, b.sendTimeout, "sendChatAction", map[string]any{
204 // call sends one call of method with the JSON params and decodes its result
205 // into result, when result is not nil. The call can take up to timeout. Its
206 // errors tell the cause in plain words, with no method name, so that a log line
207 // can say first what the call was for.
208 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
209 ctx, cancel := context.WithTimeout(ctx, timeout)
212 body, err := json.Marshal(params)
214 return fmt.Errorf("%s: encode request: %w", method, err)
217 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
219 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
222 request.Header.Set("Content-Type", "application/json")
224 response, err := b.http.Do(request)
226 return b.networkError("no answer", err, timeout)
229 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
230 err = errors.Join(err, response.Body.Close())
232 return b.networkError("answer cut off", err, timeout)
235 var answer TelegramAnswer
237 err = json.Unmarshal(data, &answer)
238 if err != nil && response.StatusCode != http.StatusOK {
239 return &TelegramError{
240 Status: response.StatusCode,
241 Description: http.StatusText(response.StatusCode),
246 return b.networkError("invalid JSON", err, timeout)
250 return &TelegramError{
251 Status: response.StatusCode,
252 Description: b.redact(errors.New(answer.Description)),
253 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
262 err = json.Unmarshal(answer.Result, result)
264 return b.networkError("invalid result", err, timeout)
270 // networkError returns the TelegramNetworkError of err, which happened at the
271 // step that what names. When the call used all of its time timeout, the cause
272 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
273 // how long the wait was.
274 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
275 if errors.Is(err, context.DeadlineExceeded) {
276 return &TelegramNetworkError{
277 Cause: "no answer in " + timeout.String(),
281 return &TelegramNetworkError{
282 Cause: what + ": " + b.redact(err),
286 // redact returns the text of err without a URL and without the token. A
287 // *url.Error holds the URL of the call, which holds the token, so only its
289 func (b *TelegramAPI) redact(err error) string {
290 var urlError *url.Error
292 if errors.As(err, &urlError) {
296 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
299 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
300 // after a network error. A later call can work. Cause tells why in plain words,
301 // with no URL and no token.
302 type TelegramNetworkError struct {
306 func (e *TelegramNetworkError) Error() string {
310 // TelegramError is an answer of the Bot API that tells of a failure. Its text
311 // gives the HTTP status and the description, such as "502 Bad Gateway".
312 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
313 // tells that the answer is a Bot API answer with ok false, not a page of a
314 // proxy or of a server error.
315 type TelegramError struct {
318 RetryAfter time.Duration
322 func (e *TelegramError) Error() string {
323 return fmt.Sprintf("%d %s", e.Status, e.Description)
326 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
327 // updates that are not a new message.
328 type TelegramUpdate struct {
329 UpdateID int64 `json:"update_id"`
330 Message *TelegramMessage `json:"message"`
333 // TelegramEntity is a message entity of sendMessage: a part of the text with a
334 // format, such as bold or a link. Offset and Length count UTF-16 code units.
335 // URL is the target of a text_link, and Language the language of a pre.
336 type TelegramEntity struct {
337 Type string `json:"type"`
338 Offset int `json:"offset"`
339 Length int `json:"length"`
340 URL string `json:"url,omitempty"`
341 Language string `json:"language,omitempty"`
344 // TelegramAnswer is the envelope of each answer of the Bot API.
345 type TelegramAnswer struct {
347 Result json.RawMessage `json:"result"`
348 ErrorCode int `json:"error_code"`
349 Description string `json:"description"`
351 RetryAfter int `json:"retry_after"`
352 } `json:"parameters"`
355 // TelegramMessage holds the text, caption, and image sizes of a bot message.
356 type TelegramMessage struct {
357 Chat TelegramChat `json:"chat"`
358 From *TelegramUser `json:"from"`
359 Text string `json:"text"`
360 Caption string `json:"caption"`
361 Photo []TelegramPhoto `json:"photo"`
362 Document *TelegramDocument `json:"document"`
365 // TelegramPhoto is one supplied size of a photo.
366 type TelegramPhoto struct {
367 FileID string `json:"file_id"`
368 Width int `json:"width"`
369 Height int `json:"height"`
370 FileSize int64 `json:"file_size"`
373 // TelegramDocument is a file sent without photo compression.
374 type TelegramDocument struct {
375 FileID string `json:"file_id"`
376 MimeType string `json:"mime_type"`
377 FileSize int64 `json:"file_size"`
380 // TelegramChat is the chat of a message. Type is private for a chat with one
382 type TelegramChat struct {
384 Type string `json:"type"`
387 // TelegramUser is the sender of a message.
388 type TelegramUser struct {