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
55 if errors.As(err, &network) {
59 var answer *TelegramError
60 if errors.As(err, &answer) {
61 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
67 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
68 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
69 // that the method is not there. An error page with no Bot API answer does not
70 // tell this, so it is not a refusal.
71 func telegramRejected(err error) bool {
72 var answer *TelegramError
73 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
76 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
77 // so no error of TelegramAPI holds a URL, a net/http error, or the token. Its
78 // sendTimeout field limits each sendMessage, sendRichMessage, and
79 // sendChatAction call.
80 type TelegramAPI struct {
84 sendTimeout time.Duration
87 // GetUpdates waits for the updates from offset on, up to telegramPollSeconds,
88 // and returns them. Telegram forgets each update before offset. Only new
89 // messages are asked for.
90 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
91 var updates []TelegramUpdate
92 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
94 "timeout": telegramPollSeconds,
95 "allowed_updates": []string{"message"},
101 // SendMessage sends text to chat with the format of entities, with no parse
102 // mode, so the text needs no escaping. With no entities, the text is plain. A
103 // call that takes longer than telegramSendTimeout fails with a
104 // TelegramNetworkError.
105 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
106 params := map[string]any{
111 if len(entities) > 0 {
112 params["entities"] = entities
115 return b.call(ctx, b.sendTimeout, "sendMessage", params, nil)
118 // SendRichMessage sends markdown to chat as a rich message, which Telegram
119 // renders itself, tables included. A call that takes longer than
120 // telegramSendTimeout fails with a TelegramNetworkError.
121 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
122 return b.call(ctx, b.sendTimeout, "sendRichMessage", map[string]any{
124 "rich_message": map[string]any{
125 "markdown": markdown,
130 // SendTyping shows the typing action in chat for about five seconds. A call
131 // that takes longer than telegramSendTimeout fails with a TelegramNetworkError.
132 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
133 return b.call(ctx, b.sendTimeout, "sendChatAction", map[string]any{
139 // call sends one call of method with the JSON params and decodes its result
140 // into result, when result is not nil. The call can take up to timeout. Its
141 // errors tell the cause in plain words, with no method name, so that a log line
142 // can say first what the call was for.
143 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
144 ctx, cancel := context.WithTimeout(ctx, timeout)
147 body, err := json.Marshal(params)
149 return fmt.Errorf("%s: encode request: %w", method, err)
152 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
154 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
157 request.Header.Set("Content-Type", "application/json")
158 response, err := b.http.Do(request)
160 return b.networkError("no answer", err, timeout)
163 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
164 err = errors.Join(err, response.Body.Close())
166 return b.networkError("answer cut off", err, timeout)
169 var answer TelegramAnswer
170 err = json.Unmarshal(data, &answer)
171 if err != nil && response.StatusCode != http.StatusOK {
172 return &TelegramError{
173 Status: response.StatusCode,
174 Description: http.StatusText(response.StatusCode),
179 return b.networkError("invalid JSON", err, timeout)
183 return &TelegramError{
184 Status: response.StatusCode,
185 Description: b.redact(errors.New(answer.Description)),
186 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
195 err = json.Unmarshal(answer.Result, result)
197 return b.networkError("invalid result", err, timeout)
203 // networkError returns the TelegramNetworkError of err, which happened at the
204 // step that what names. When the call used all of its time timeout, the cause
205 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
206 // how long the wait was.
207 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
208 if errors.Is(err, context.DeadlineExceeded) {
209 return &TelegramNetworkError{
210 Cause: "no answer in " + timeout.String(),
214 return &TelegramNetworkError{
215 Cause: what + ": " + b.redact(err),
219 // redact returns the text of err without a URL and without the token. A
220 // *url.Error holds the URL of the call, which holds the token, so only its
222 func (b *TelegramAPI) redact(err error) string {
223 var urlError *url.Error
224 if errors.As(err, &urlError) {
228 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
231 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
232 // after a network error. A later call can work. Cause tells why in plain words,
233 // with no URL and no token.
234 type TelegramNetworkError struct {
238 func (e *TelegramNetworkError) Error() string {
242 // TelegramError is an answer of the Bot API that tells of a failure. Its text
243 // gives the HTTP status and the description, such as "502 Bad Gateway".
244 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
245 // tells that the answer is a Bot API answer with ok false, not a page of a
246 // proxy or of a server error.
247 type TelegramError struct {
250 RetryAfter time.Duration
254 func (e *TelegramError) Error() string {
255 return fmt.Sprintf("%d %s", e.Status, e.Description)
258 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
259 // updates that are not a new message.
260 type TelegramUpdate struct {
261 UpdateID int64 `json:"update_id"`
262 Message *TelegramMessage `json:"message"`
265 // TelegramEntity is a message entity of sendMessage: a part of the text with a
266 // format, such as bold or a link. Offset and Length count UTF-16 code units.
267 // URL is the target of a text_link, and Language the language of a pre.
268 type TelegramEntity struct {
269 Type string `json:"type"`
270 Offset int `json:"offset"`
271 Length int `json:"length"`
272 URL string `json:"url,omitempty"`
273 Language string `json:"language,omitempty"`
276 // TelegramAnswer is the envelope of each answer of the Bot API.
277 type TelegramAnswer struct {
279 Result json.RawMessage `json:"result"`
280 ErrorCode int `json:"error_code"`
281 Description string `json:"description"`
283 RetryAfter int `json:"retry_after"`
284 } `json:"parameters"`
287 // TelegramMessage is a message to the bot. Text is empty for a message that is
288 // not text, such as a photo.
289 type TelegramMessage struct {
290 Chat TelegramChat `json:"chat"`
291 From *TelegramUser `json:"from"`
292 Text string `json:"text"`
295 // TelegramChat is the chat of a message. Type is private for a chat with one
297 type TelegramChat struct {
299 Type string `json:"type"`
302 // TelegramUser is the sender of a message.
303 type TelegramUser struct {