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 // telegramSendTimeout is how long a sendMessage, sendRichMessage, or
26 // sendChatAction call can take. A connection that stops without a
27 // close, such as after a network change, then fails the call, and the
28 // sender tries again, instead of a wait until TCP gives up. The client
29 // has no timeout of its own, because the long poll of getUpdates needs
31 telegramSendTimeout = 30 * time.Second
33 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
34 telegramAnswerBytes = 16 << 20
37 // errTelegramNetwork tells that a Bot API call got no valid answer, such as
38 // after a network error. A later call can work.
39 var errTelegramNetwork = errors.New("no valid answer from the Bot API")
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 if errors.Is(err, errTelegramNetwork) {
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.
78 // SendTimeout limits each sendMessage, sendRichMessage, and sendChatAction
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 ctx, cancel := context.WithTimeout(ctx, telegramPollSeconds*time.Second+telegramPollSlack)
94 var updates []TelegramUpdate
95 err := b.call(ctx, "getUpdates", map[string]any{
97 "timeout": telegramPollSeconds,
98 "allowed_updates": []string{"message"},
104 // SendMessage sends text to chat with the format of entities, with no parse
105 // mode, so the text needs no escaping. With no entities, the text is plain. A
106 // call that takes longer than telegramSendTimeout fails with
107 // errTelegramNetwork.
108 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
109 ctx, cancel := context.WithTimeout(ctx, b.sendTimeout)
112 params := map[string]any{
117 if len(entities) > 0 {
118 params["entities"] = entities
121 return b.call(ctx, "sendMessage", params, nil)
124 // SendRichMessage sends markdown to chat as a rich message, which Telegram
125 // renders itself, tables included. A call that takes longer than
126 // telegramSendTimeout fails with errTelegramNetwork.
127 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
128 ctx, cancel := context.WithTimeout(ctx, b.sendTimeout)
131 return b.call(ctx, "sendRichMessage", map[string]any{
133 "rich_message": map[string]any{
134 "markdown": markdown,
139 // SendTyping shows the typing action in chat for about five seconds. A call
140 // that takes longer than telegramSendTimeout fails with errTelegramNetwork.
141 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
142 ctx, cancel := context.WithTimeout(ctx, b.sendTimeout)
145 return b.call(ctx, "sendChatAction", map[string]any{
151 // call sends one call of method with the JSON params and decodes its result
152 // into result, when result is not nil.
153 func (b *TelegramAPI) call(ctx context.Context, method string, params, result any) error {
154 body, err := json.Marshal(params)
156 return fmt.Errorf("%s: encode request: %w", method, err)
159 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
161 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
164 request.Header.Set("Content-Type", "application/json")
165 response, err := b.http.Do(request)
167 return fmt.Errorf("%s: %w: %s", method, errTelegramNetwork, b.redact(err))
170 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
171 err = errors.Join(err, response.Body.Close())
173 return fmt.Errorf("%s: %w: read answer: %s", method, errTelegramNetwork, b.redact(err))
176 var answer TelegramAnswer
177 err = json.Unmarshal(data, &answer)
178 if err != nil && response.StatusCode != http.StatusOK {
179 return &TelegramError{
181 Status: response.StatusCode,
182 Description: http.StatusText(response.StatusCode),
187 return fmt.Errorf("%s: %w: decode answer: %s", method, errTelegramNetwork, b.redact(err))
191 return &TelegramError{
193 Status: response.StatusCode,
194 Description: b.redact(errors.New(answer.Description)),
195 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
204 err = json.Unmarshal(answer.Result, result)
206 return fmt.Errorf("%s: %w: decode result: %s", method, errTelegramNetwork, b.redact(err))
212 // redact returns the text of err without a URL and without the token. A
213 // *url.Error holds the URL of the call, which holds the token, so only its
215 func (b *TelegramAPI) redact(err error) string {
216 var urlError *url.Error
217 if errors.As(err, &urlError) {
221 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
224 // TelegramError is an answer of the Bot API that tells of a failure. RetryAfter
225 // is the wait that the Bot API asks for after HTTP 429. Refused tells that the
226 // answer is a Bot API answer with ok false, not a page of a proxy or of a
228 type TelegramError struct {
232 RetryAfter time.Duration
236 func (e *TelegramError) Error() string {
237 return fmt.Sprintf("%s: Bot API answered %d: %s", e.Method, e.Status, e.Description)
240 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
241 // updates that are not a new message.
242 type TelegramUpdate struct {
243 UpdateID int64 `json:"update_id"`
244 Message *TelegramMessage `json:"message"`
247 // TelegramEntity is a message entity of sendMessage: a part of the text with a
248 // format, such as bold or a link. Offset and Length count UTF-16 code units.
249 // URL is the target of a text_link, and Language the language of a pre.
250 type TelegramEntity struct {
251 Type string `json:"type"`
252 Offset int `json:"offset"`
253 Length int `json:"length"`
254 URL string `json:"url,omitempty"`
255 Language string `json:"language,omitempty"`
258 // TelegramAnswer is the envelope of each answer of the Bot API.
259 type TelegramAnswer struct {
261 Result json.RawMessage `json:"result"`
262 ErrorCode int `json:"error_code"`
263 Description string `json:"description"`
265 RetryAfter int `json:"retry_after"`
266 } `json:"parameters"`
269 // TelegramMessage is a message to the bot. Text is empty for a message that is
270 // not text, such as a photo.
271 type TelegramMessage struct {
272 Chat TelegramChat `json:"chat"`
273 From *TelegramUser `json:"from"`
274 Text string `json:"text"`
277 // TelegramChat is the chat of a message. Type is private for a chat with one
279 type TelegramChat struct {
281 Type string `json:"type"`
284 // TelegramUser is the sender of a message.
285 type TelegramUser struct {