]> git.giacomolli.uk - onechat/blob - telegram_api.go
Manage source routes with root tools
[onechat] / telegram_api.go
1 package main
2
3 import (
4         "bytes"
5         "context"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "io"
10         "net/http"
11         "net/url"
12         "strings"
13         "time"
14 )
15
16 const (
17         // telegramPollSeconds is how long one getUpdates call waits for an
18         // update.
19         telegramPollSeconds = 50
20
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
24
25         // telegramPollTimeout is how long one getUpdates call can take.
26         telegramPollTimeout = telegramPollSeconds*time.Second + telegramPollSlack
27
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
33         // a longer limit.
34         telegramSendTimeout = 30 * time.Second
35
36         // telegramAnswerBytes is the most bytes of one answer of the Bot API.
37         telegramAnswerBytes = 16 << 20
38 )
39
40 // newTelegramAPI returns the client of the Bot API at base with token.
41 func newTelegramAPI(base, token string) *TelegramAPI {
42         return &TelegramAPI{
43                 base:        base,
44                 token:       token,
45                 http:        &http.Client{},
46                 sendTimeout: telegramSendTimeout,
47         }
48 }
49
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
56         if errors.As(err, &network) {
57                 return true, 0
58         }
59
60         var answer *TelegramError
61
62         if errors.As(err, &answer) {
63                 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
64         }
65
66         return false, 0
67 }
68
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
75
76         return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
77 }
78
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 {
84         base        string
85         token       string
86         http        *http.Client
87         sendTimeout time.Duration
88 }
89
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
95
96         err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
97                 "offset":          offset,
98                 "timeout":         telegramPollSeconds,
99                 "allowed_updates": []string{"message"},
100         }, &updates)
101
102         return updates, err
103 }
104
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{
111                 "chat_id": chat,
112                 "text":    text,
113         }
114
115         if len(entities) > 0 {
116                 params["entities"] = entities
117         }
118
119         return b.call(ctx, b.sendTimeout, "sendMessage", params, nil)
120 }
121
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{
127                 "chat_id": chat,
128                 "rich_message": map[string]any{
129                         "markdown": markdown,
130                 },
131         }, nil)
132 }
133
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{
138                 "chat_id": chat,
139                 "action":  "typing",
140         }, nil)
141 }
142
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)
149         defer cancel()
150
151         body, err := json.Marshal(params)
152         if err != nil {
153                 return fmt.Errorf("%s: encode request: %w", method, err)
154         }
155
156         request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
157         if err != nil {
158                 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
159         }
160
161         request.Header.Set("Content-Type", "application/json")
162
163         response, err := b.http.Do(request)
164         if err != nil {
165                 return b.networkError("no answer", err, timeout)
166         }
167
168         data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
169         err = errors.Join(err, response.Body.Close())
170         if err != nil {
171                 return b.networkError("answer cut off", err, timeout)
172         }
173
174         var answer TelegramAnswer
175
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),
181                 }
182         }
183
184         if err != nil {
185                 return b.networkError("invalid JSON", err, timeout)
186         }
187
188         if !answer.OK {
189                 return &TelegramError{
190                         Status:      response.StatusCode,
191                         Description: b.redact(errors.New(answer.Description)),
192                         RetryAfter:  time.Duration(answer.Parameters.RetryAfter) * time.Second,
193                         Refused:     true,
194                 }
195         }
196
197         if result == nil {
198                 return nil
199         }
200
201         err = json.Unmarshal(answer.Result, result)
202         if err != nil {
203                 return b.networkError("invalid result", err, timeout)
204         }
205
206         return nil
207 }
208
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(),
217                 }
218         }
219
220         return &TelegramNetworkError{
221                 Cause: what + ": " + b.redact(err),
222         }
223 }
224
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
227 // cause is kept.
228 func (b *TelegramAPI) redact(err error) string {
229         var urlError *url.Error
230
231         if errors.As(err, &urlError) {
232                 err = urlError.Err
233         }
234
235         return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
236 }
237
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 {
242         Cause string
243 }
244
245 func (e *TelegramNetworkError) Error() string {
246         return e.Cause
247 }
248
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 {
255         Status      int
256         Description string
257         RetryAfter  time.Duration
258         Refused     bool
259 }
260
261 func (e *TelegramError) Error() string {
262         return fmt.Sprintf("%d %s", e.Status, e.Description)
263 }
264
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"`
270 }
271
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"`
281 }
282
283 // TelegramAnswer is the envelope of each answer of the Bot API.
284 type TelegramAnswer struct {
285         OK          bool            `json:"ok"`
286         Result      json.RawMessage `json:"result"`
287         ErrorCode   int             `json:"error_code"`
288         Description string          `json:"description"`
289         Parameters  struct {
290                 RetryAfter int `json:"retry_after"`
291         } `json:"parameters"`
292 }
293
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"`
300 }
301
302 // TelegramChat is the chat of a message. Type is private for a chat with one
303 // user.
304 type TelegramChat struct {
305         ID   int64  `json:"id"`
306         Type string `json:"type"`
307 }
308
309 // TelegramUser is the sender of a message.
310 type TelegramUser struct {
311         ID int64 `json:"id"`
312 }