17 // telegramPollSeconds is how long one getUpdates call waits for an
19 telegramPollSeconds = 50
21 // telegramPollSlack is how much longer than telegramPollSeconds a
22 // getUpdates call can take before the bot gives it up.
23 telegramPollSlack = 20 * time.Second
25 // telegramPollTimeout is how long one getUpdates call can take.
26 telegramPollTimeout = telegramPollSeconds*time.Second + telegramPollSlack
28 // telegramSendTimeout is how long a sendMessage, sendRichMessage, or
29 // sendChatAction call can take. A connection that stops without a
30 // close, such as after a network change, then fails the call, and the
31 // sender tries again, instead of a wait until TCP gives up. The client
32 // has no timeout of its own, because the long poll of getUpdates needs
34 telegramSendTimeout = 30 * time.Second
36 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
37 telegramAnswerBytes = 16 << 20
40 // newTelegramAPI returns the client of the Bot API at base with token.
41 func newTelegramAPI(base, token string) *TelegramAPI {
46 sendTimeout: telegramSendTimeout,
50 // telegramRetryable tells if a later try of a failed Bot API call can work:
51 // after a network error, HTTP 429, or a server error. It returns the wait that
52 // the Bot API asks for, or 0.
53 func telegramRetryable(err error) (bool, time.Duration) {
54 var network *TelegramNetworkError
56 if errors.As(err, &network) {
60 var answer *TelegramError
62 if errors.As(err, &answer) {
63 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
69 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
70 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
71 // that the method is not there. An error page with no Bot API answer does not
72 // tell this, so it is not a refusal.
73 func telegramRejected(err error) bool {
74 var answer *TelegramError
76 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
79 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
80 // so no error of TelegramAPI holds a URL, a net/http error, or the token. Its
81 // sendTimeout field limits each sendMessage, sendRichMessage, and
82 // sendChatAction call.
83 type TelegramAPI struct {
87 sendTimeout time.Duration
90 // GetUpdates waits for the updates from offset on, up to telegramPollSeconds,
91 // and returns them. Telegram forgets each update before offset. Only new
92 // messages are asked for.
93 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
94 var updates []TelegramUpdate
96 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
98 "timeout": telegramPollSeconds,
99 "allowed_updates": []string{"message"},
105 // SendMessage sends text to chat with the format of entities, with no parse
106 // mode, so the text needs no escaping. With no entities, the text is plain. A
107 // call that takes longer than telegramSendTimeout fails with a
108 // TelegramNetworkError.
109 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
110 params := map[string]any{
115 if len(entities) > 0 {
116 params["entities"] = entities
119 return b.call(ctx, b.sendTimeout, "sendMessage", params, nil)
122 // SendRichMessage sends markdown to chat as a rich message, which Telegram
123 // renders itself, tables included. A call that takes longer than
124 // telegramSendTimeout fails with a TelegramNetworkError.
125 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
126 return b.call(ctx, b.sendTimeout, "sendRichMessage", map[string]any{
128 "rich_message": map[string]any{
129 "markdown": markdown,
134 // SendTyping shows the typing action in chat for about five seconds. A call
135 // that takes longer than telegramSendTimeout fails with a TelegramNetworkError.
136 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
137 return b.call(ctx, b.sendTimeout, "sendChatAction", map[string]any{
143 // call sends one call of method with the JSON params and decodes its result
144 // into result, when result is not nil. The call can take up to timeout. Its
145 // errors tell the cause in plain words, with no method name, so that a log line
146 // can say first what the call was for.
147 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
148 ctx, cancel := context.WithTimeout(ctx, timeout)
151 body, err := json.Marshal(params)
153 return fmt.Errorf("%s: encode request: %w", method, err)
156 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
158 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
161 request.Header.Set("Content-Type", "application/json")
163 response, err := b.http.Do(request)
165 return b.networkError("no answer", err, timeout)
168 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
169 err = errors.Join(err, response.Body.Close())
171 return b.networkError("answer cut off", err, timeout)
174 var answer TelegramAnswer
176 err = json.Unmarshal(data, &answer)
177 if err != nil && response.StatusCode != http.StatusOK {
178 return &TelegramError{
179 Status: response.StatusCode,
180 Description: http.StatusText(response.StatusCode),
185 return b.networkError("invalid JSON", err, timeout)
189 return &TelegramError{
190 Status: response.StatusCode,
191 Description: b.redact(errors.New(answer.Description)),
192 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
201 err = json.Unmarshal(answer.Result, result)
203 return b.networkError("invalid result", err, timeout)
209 // networkError returns the TelegramNetworkError of err, which happened at the
210 // step that what names. When the call used all of its time timeout, the cause
211 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
212 // how long the wait was.
213 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
214 if errors.Is(err, context.DeadlineExceeded) {
215 return &TelegramNetworkError{
216 Cause: "no answer in " + timeout.String(),
220 return &TelegramNetworkError{
221 Cause: what + ": " + b.redact(err),
225 // redact returns the text of err without a URL and without the token. A
226 // *url.Error holds the URL of the call, which holds the token, so only its
228 func (b *TelegramAPI) redact(err error) string {
229 var urlError *url.Error
231 if errors.As(err, &urlError) {
235 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
238 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
239 // after a network error. A later call can work. Cause tells why in plain words,
240 // with no URL and no token.
241 type TelegramNetworkError struct {
245 func (e *TelegramNetworkError) Error() string {
249 // TelegramError is an answer of the Bot API that tells of a failure. Its text
250 // gives the HTTP status and the description, such as "502 Bad Gateway".
251 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
252 // tells that the answer is a Bot API answer with ok false, not a page of a
253 // proxy or of a server error.
254 type TelegramError struct {
257 RetryAfter time.Duration
261 func (e *TelegramError) Error() string {
262 return fmt.Sprintf("%d %s", e.Status, e.Description)
265 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
266 // updates that are not a new message.
267 type TelegramUpdate struct {
268 UpdateID int64 `json:"update_id"`
269 Message *TelegramMessage `json:"message"`
272 // TelegramEntity is a message entity of sendMessage: a part of the text with a
273 // format, such as bold or a link. Offset and Length count UTF-16 code units.
274 // URL is the target of a text_link, and Language the language of a pre.
275 type TelegramEntity struct {
276 Type string `json:"type"`
277 Offset int `json:"offset"`
278 Length int `json:"length"`
279 URL string `json:"url,omitempty"`
280 Language string `json:"language,omitempty"`
283 // TelegramAnswer is the envelope of each answer of the Bot API.
284 type TelegramAnswer struct {
286 Result json.RawMessage `json:"result"`
287 ErrorCode int `json:"error_code"`
288 Description string `json:"description"`
290 RetryAfter int `json:"retry_after"`
291 } `json:"parameters"`
294 // TelegramMessage is a message to the bot. Text is empty for a message that is
295 // not text, such as a photo.
296 type TelegramMessage struct {
297 Chat TelegramChat `json:"chat"`
298 From *TelegramUser `json:"from"`
299 Text string `json:"text"`
302 // TelegramChat is the chat of a message. Type is private for a chat with one
304 type TelegramChat struct {
306 Type string `json:"type"`
309 // TelegramUser is the sender of a message.
310 type TelegramUser struct {