]> git.giacomolli.uk - onechat/blob - telegram_api.go
bb4ee2c07bc425eab5805176595def55c22c80c6
[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 // 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
30 // a longer limit.
31 telegramSendTimeout = 30 * time.Second
32
33 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
34 telegramAnswerBytes = 16 << 20
35 )
36
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")
40
41 // newTelegramAPI returns the client of the Bot API at base with token.
42 func newTelegramAPI(base, token string) *TelegramAPI {
43 return &TelegramAPI{
44 base: base,
45 token: token,
46 http: &http.Client{},
47 sendTimeout: telegramSendTimeout,
48 }
49 }
50
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) {
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 ctx, cancel := context.WithTimeout(ctx, telegramPollSeconds*time.Second+telegramPollSlack)
92 defer cancel()
93
94 var updates []TelegramUpdate
95 err := b.call(ctx, "getUpdates", map[string]any{
96 "offset": offset,
97 "timeout": telegramPollSeconds,
98 "allowed_updates": []string{"message"},
99 }, &updates)
100
101 return updates, err
102 }
103
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)
110 defer cancel()
111
112 params := map[string]any{
113 "chat_id": chat,
114 "text": text,
115 }
116
117 if len(entities) > 0 {
118 params["entities"] = entities
119 }
120
121 return b.call(ctx, "sendMessage", params, nil)
122 }
123
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)
129 defer cancel()
130
131 return b.call(ctx, "sendRichMessage", map[string]any{
132 "chat_id": chat,
133 "rich_message": map[string]any{
134 "markdown": markdown,
135 },
136 }, nil)
137 }
138
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)
143 defer cancel()
144
145 return b.call(ctx, "sendChatAction", map[string]any{
146 "chat_id": chat,
147 "action": "typing",
148 }, nil)
149 }
150
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)
155 if err != nil {
156 return fmt.Errorf("%s: encode request: %w", method, err)
157 }
158
159 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
160 if err != nil {
161 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
162 }
163
164 request.Header.Set("Content-Type", "application/json")
165 response, err := b.http.Do(request)
166 if err != nil {
167 return fmt.Errorf("%s: %w: %s", method, errTelegramNetwork, b.redact(err))
168 }
169
170 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
171 err = errors.Join(err, response.Body.Close())
172 if err != nil {
173 return fmt.Errorf("%s: %w: read answer: %s", method, errTelegramNetwork, b.redact(err))
174 }
175
176 var answer TelegramAnswer
177 err = json.Unmarshal(data, &answer)
178 if err != nil && response.StatusCode != http.StatusOK {
179 return &TelegramError{
180 Method: method,
181 Status: response.StatusCode,
182 Description: http.StatusText(response.StatusCode),
183 }
184 }
185
186 if err != nil {
187 return fmt.Errorf("%s: %w: decode answer: %s", method, errTelegramNetwork, b.redact(err))
188 }
189
190 if !answer.OK {
191 return &TelegramError{
192 Method: method,
193 Status: response.StatusCode,
194 Description: b.redact(errors.New(answer.Description)),
195 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
196 Refused: true,
197 }
198 }
199
200 if result == nil {
201 return nil
202 }
203
204 err = json.Unmarshal(answer.Result, result)
205 if err != nil {
206 return fmt.Errorf("%s: %w: decode result: %s", method, errTelegramNetwork, b.redact(err))
207 }
208
209 return nil
210 }
211
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
214 // cause is kept.
215 func (b *TelegramAPI) redact(err error) string {
216 var urlError *url.Error
217 if errors.As(err, &urlError) {
218 err = urlError.Err
219 }
220
221 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
222 }
223
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
227 // server error.
228 type TelegramError struct {
229 Method string
230 Status int
231 Description string
232 RetryAfter time.Duration
233 Refused bool
234 }
235
236 func (e *TelegramError) Error() string {
237 return fmt.Sprintf("%s: Bot API answered %d: %s", e.Method, e.Status, e.Description)
238 }
239
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"`
245 }
246
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"`
256 }
257
258 // TelegramAnswer is the envelope of each answer of the Bot API.
259 type TelegramAnswer struct {
260 OK bool `json:"ok"`
261 Result json.RawMessage `json:"result"`
262 ErrorCode int `json:"error_code"`
263 Description string `json:"description"`
264 Parameters struct {
265 RetryAfter int `json:"retry_after"`
266 } `json:"parameters"`
267 }
268
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"`
275 }
276
277 // TelegramChat is the chat of a message. Type is private for a chat with one
278 // user.
279 type TelegramChat struct {
280 ID int64 `json:"id"`
281 Type string `json:"type"`
282 }
283
284 // TelegramUser is the sender of a message.
285 type TelegramUser struct {
286 ID int64 `json:"id"`
287 }