]> git.giacomolli.uk - onechat/blob - telegram_api.go
Check test assertions with testifylint
[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 if errors.As(err, &network) {
56 return true, 0
57 }
58
59 var answer *TelegramError
60 if errors.As(err, &answer) {
61 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
62 }
63
64 return false, 0
65 }
66
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)
74 }
75
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 {
81 base string
82 token string
83 http *http.Client
84 sendTimeout time.Duration
85 }
86
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{
93 "offset": offset,
94 "timeout": telegramPollSeconds,
95 "allowed_updates": []string{"message"},
96 }, &updates)
97
98 return updates, err
99 }
100
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{
107 "chat_id": chat,
108 "text": text,
109 }
110
111 if len(entities) > 0 {
112 params["entities"] = entities
113 }
114
115 return b.call(ctx, b.sendTimeout, "sendMessage", params, nil)
116 }
117
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{
123 "chat_id": chat,
124 "rich_message": map[string]any{
125 "markdown": markdown,
126 },
127 }, nil)
128 }
129
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{
134 "chat_id": chat,
135 "action": "typing",
136 }, nil)
137 }
138
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)
145 defer cancel()
146
147 body, err := json.Marshal(params)
148 if err != nil {
149 return fmt.Errorf("%s: encode request: %w", method, err)
150 }
151
152 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
153 if err != nil {
154 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
155 }
156
157 request.Header.Set("Content-Type", "application/json")
158 response, err := b.http.Do(request)
159 if err != nil {
160 return b.networkError("no answer", err, timeout)
161 }
162
163 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
164 err = errors.Join(err, response.Body.Close())
165 if err != nil {
166 return b.networkError("answer cut off", err, timeout)
167 }
168
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),
175 }
176 }
177
178 if err != nil {
179 return b.networkError("invalid JSON", err, timeout)
180 }
181
182 if !answer.OK {
183 return &TelegramError{
184 Status: response.StatusCode,
185 Description: b.redact(errors.New(answer.Description)),
186 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
187 Refused: true,
188 }
189 }
190
191 if result == nil {
192 return nil
193 }
194
195 err = json.Unmarshal(answer.Result, result)
196 if err != nil {
197 return b.networkError("invalid result", err, timeout)
198 }
199
200 return nil
201 }
202
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(),
211 }
212 }
213
214 return &TelegramNetworkError{
215 Cause: what + ": " + b.redact(err),
216 }
217 }
218
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
221 // cause is kept.
222 func (b *TelegramAPI) redact(err error) string {
223 var urlError *url.Error
224 if errors.As(err, &urlError) {
225 err = urlError.Err
226 }
227
228 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
229 }
230
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 {
235 Cause string
236 }
237
238 func (e *TelegramNetworkError) Error() string {
239 return e.Cause
240 }
241
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 {
248 Status int
249 Description string
250 RetryAfter time.Duration
251 Refused bool
252 }
253
254 func (e *TelegramError) Error() string {
255 return fmt.Sprintf("%d %s", e.Status, e.Description)
256 }
257
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"`
263 }
264
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"`
274 }
275
276 // TelegramAnswer is the envelope of each answer of the Bot API.
277 type TelegramAnswer struct {
278 OK bool `json:"ok"`
279 Result json.RawMessage `json:"result"`
280 ErrorCode int `json:"error_code"`
281 Description string `json:"description"`
282 Parameters struct {
283 RetryAfter int `json:"retry_after"`
284 } `json:"parameters"`
285 }
286
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"`
293 }
294
295 // TelegramChat is the chat of a message. Type is private for a chat with one
296 // user.
297 type TelegramChat struct {
298 ID int64 `json:"id"`
299 Type string `json:"type"`
300 }
301
302 // TelegramUser is the sender of a message.
303 type TelegramUser struct {
304 ID int64 `json:"id"`
305 }