-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
466 lines (407 loc) · 10.9 KB
/
bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package telegram
//go:generate python methods_bool.py
//go:generate python methods_message.py
//go:generate python types_keyboards.py
//go:generate gofmt -w .
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"time"
"golang.org/x/net/proxy"
)
const jsonContentType = "application/json;chartset=utf-8"
const (
defaultURL = "https://api.telegram.org/bot"
defaultErrTimeout = 5 * time.Second
defaultPollTimeout = time.Minute
)
var ErrEmptyToken = errors.New("telegram: empty token")
type Bot interface {
Username() string
Updates() <-chan *Update
Errors() <-chan error
GetMe(context.Context) (*User, error)
GetUpdates(context.Context, ...UpdatesOption) ([]*Update, error)
SendMessage(context.Context, *TextMessage) (*Message, error)
ForwardMessage(context.Context, *ForwardedMessage) (*Message, error)
// SendPhoto(context.Context, *PhotoMessage) (*Message, error)
// SendAudio(context.Context, *AudioMessage) (*Message, error)
// SendDocument(context.Context, *DocumentMessage) (*Message, error)
// SendSticker(context.Context, *StickerMessage) (*Message, error)
// SendVideo(context.Context, *VideoMessage) (*Message, error)
// SendVoice(context.Context, *VoiceMessage) (*Message, error)
// SendVoiceNote(context.Context, *VoiceNoteMessage) (*Message, error)
// SendLocation(context.Context, *LocationMessage) (*Message, error)
// SendVenue(context.Context, *VenueMessage) (*Message, error)
// SendContact(context.Context, *ContactMessage) (*Message, error)
EditMessageText(context.Context, *MessageText) (*Message, error)
EditMessageCaption(context.Context, *MessageCaption) (*Message, error)
EditMessageReplyMarkup(context.Context, *MessageReplyMarkup) (*Message, error)
DeleteMessage(context.Context, *DeletedMessage) error
}
func NewBot(ctx context.Context, token string, opts ...BotOption) (Bot, error) {
if token == "" {
return nil, ErrEmptyToken
}
b := newBot(ctx, token, opts...)
if err := b.getUsername(); err != nil {
return nil, err
}
if !b.noUpdates {
go b.listenToUpdates()
}
return b, nil
}
type SOCKS5 struct {
Address string // host:port
User string
Password string
}
func (s *SOCKS5) Auth() *proxy.Auth {
if s.User != "" {
return &proxy.Auth{
User: s.User,
Password: s.Password,
}
}
return nil
}
type botOptions struct {
Username string
URL string
ErrTimeout time.Duration
PollTimeout time.Duration
NoUpdates bool
// TODO: Support several proxies.
SOCKS5 *SOCKS5
}
type BotOption func(*botOptions)
func WithUsername(s string) BotOption {
return func(o *botOptions) {
o.Username = s
}
}
func WithSOCKS5(v SOCKS5) BotOption {
return func(o *botOptions) {
o.SOCKS5 = &v
}
}
func withURL(url string) BotOption {
return func(o *botOptions) {
o.URL = url
}
}
func WithErrTimeout(t time.Duration) BotOption {
return func(o *botOptions) {
o.ErrTimeout = t
}
}
func WithPollTimeout(t time.Duration) BotOption {
return func(o *botOptions) {
o.PollTimeout = t
}
}
func WithoutUpdates() BotOption {
return func(o *botOptions) {
o.NoUpdates = true
}
}
type bot struct {
username string
url string
ctx context.Context
client *http.Client
errTimeout time.Duration
pollTimeout time.Duration
noUpdates bool
updatec chan *Update
errorc chan error
}
func newBot(ctx context.Context, token string, opts ...BotOption) *bot {
o := &botOptions{URL: defaultURL, ErrTimeout: defaultErrTimeout, PollTimeout: defaultPollTimeout}
for _, opt := range opts {
opt(o)
}
var client *http.Client
if v := o.SOCKS5; v != nil {
p, err := proxy.SOCKS5("tcp", v.Address, v.Auth(), proxy.Direct)
if err != nil {
fmt.Println("Error connecting to proxy:", err)
}
client = &http.Client{
Transport: &http.Transport{
Dial: p.Dial,
},
}
}
b := &bot{
username: o.Username,
url: o.URL + token,
ctx: ctx,
client: client,
errTimeout: o.ErrTimeout,
pollTimeout: o.PollTimeout,
noUpdates: o.NoUpdates,
updatec: make(chan *Update),
errorc: make(chan error),
}
if b.noUpdates {
close(b.updatec)
close(b.errorc)
}
return b
}
func (b *bot) getUsername() error {
if b.username != "" {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), b.errTimeout)
defer cancel()
me, err := b.GetMe(ctx)
if err != nil {
return fmt.Errorf("telegram: could not get name: %s", err)
}
b.username = *me.Username
return nil
}
func (b *bot) listenToUpdates() {
var offset int
donec := b.ctx.Done()
loop:
for {
u, err := b.GetUpdates(b.ctx, WithOffset(offset), WithTimeout(b.pollTimeout))
// Handle context errors differently - shutdown gracefully.
switch err {
case context.Canceled, context.DeadlineExceeded:
break loop
}
if err != nil {
select {
case b.errorc <- err:
sleepctx(b.ctx, b.errTimeout)
continue
case <-donec:
break
}
}
// No updates this time - repeat the loop and wait for another pack.
if len(u) == 0 {
continue
}
// Increment offset according to the last update id. Next time updates
// pack will not contain updates up to this last one.
offset = u[len(u)-1].UpdateID + 1
for _, up := range u {
select {
case b.updatec <- up:
continue
case <-donec:
break loop
}
}
}
// TODO: How to ensure updatesc and errorc to be drained?
// Don't forget to close channels.
close(b.updatec)
close(b.errorc)
}
// sleepctx pauses for at lease t duration. It returns early if ctx is cancelled or
// its deadline is exceeded.
func sleepctx(ctx context.Context, t time.Duration) {
select {
case <-ctx.Done():
case <-time.After(t):
}
}
func (b *bot) Username() string { return b.username }
func (b *bot) Updates() <-chan *Update { return b.updatec }
func (b *bot) Errors() <-chan error { return b.errorc }
// call issues HTTP request to API for the method with form values and decodes
// received data in v. It returns error otherwise.
func (b *bot) do(ctx context.Context, method string, data interface{}, v interface{}) error {
url := b.url + "/" + method
body, contentType, err := b.encode(data)
if err != nil {
return err
}
resp, err := post(ctx, b.client, url, contentType, body)
if err != nil {
return err
}
defer resp.Body.Close()
bdata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
r := new(apiResponse)
if err := json.Unmarshal(bdata, r); err != nil {
return err
}
if !r.OK {
return &Error{
ErrorCode: r.ErrorCode,
Description: r.Description,
Parameters: r.Parameters,
}
}
return json.Unmarshal([]byte(r.Result), v)
}
// post issues a POST request via the do function.
//
// Copied from golang.org/x/net/context/ctxhttp
func post(ctx context.Context, client *http.Client, url, bodyType string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", bodyType)
return do(ctx, client, req)
}
// do sends an HTTP request with the provided http.Client and returns
// an HTTP response.
//
// If the client is nil, http.DefaultClient is used.
//
// The provided ctx must be non-nil. If it is canceled or times out,
// ctx.Err() will be returned.
//
// Copied from golang.org/x/net/context/ctxhttp
func do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req.WithContext(ctx))
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
if err != nil {
select {
case <-ctx.Done():
err = ctx.Err()
default:
}
}
return resp, err
}
func (b *bot) encode(data interface{}) (io.Reader, string, error) {
if m, ok := data.(Multiparter); ok {
if v := m.Multipart(); v != nil {
return v.Encode()
}
}
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(data); err != nil {
return nil, "", err
}
return buf, jsonContentType, nil
}
// Multiparter is an interface for messages that may be converted to a multipart
// form (e.g. photo, document, video). *Multipart may be nil meaning unavailable
// conversion.
type Multiparter interface {
Multipart() *Multipart
}
type Multipart struct {
Form url.Values
Files map[string]InputFile
}
// Encode encodes Multipart to multipart/form-data. It returns io.Reader for
// content, content type with boundary and error. In case of failed encoding
// io.Reader is nil, content type is an empty string.
func (m *Multipart) Encode() (io.Reader, string, error) {
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)
for key := range m.Form {
if err := w.WriteField(key, m.Form.Get(key)); err != nil {
return nil, "", err
}
}
for key := range m.Files {
file := m.Files[key]
if dest, err := w.CreateFormFile(key, file.Name()); err != nil {
return nil, "", err
} else {
if _, err := io.Copy(dest, file); err != nil {
return nil, "", err
}
}
}
if err := w.Close(); err != nil {
return nil, "", err
}
return buf, w.FormDataContentType(), nil
}
type updatesOptions struct {
Offset int
Limit int
Timeout time.Duration
// AllowedUpdates []string
}
// MarshalJSON implements json.Marshaler interface.
func (o *updatesOptions) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{}
if o.Offset > 0 {
m["offset"] = o.Offset
}
if o.Limit > 0 {
m["limit"] = o.Limit
}
if o.Timeout > 0 {
m["timeout"] = int(o.Timeout.Seconds())
}
return json.Marshal(m)
}
type UpdatesOption func(*updatesOptions)
// WithOffset sets id of the first expected update in response. Usually offset
// should equal last update's id + 1.
func WithOffset(offset int) UpdatesOption {
return func(o *updatesOptions) {
o.Offset = offset
}
}
// WithLimit modifies updates request to limit the number of updates in response.
func WithLimit(limit int) UpdatesOption {
return func(o *updatesOptions) {
if limit < 1 {
limit = 1
}
if limit > 100 {
limit = 100
}
o.Limit = limit
}
}
// WithTimeout modifies timeout of updates request. 0 duration means short
// polling (for testing only).
func WithTimeout(t time.Duration) UpdatesOption {
return func(o *updatesOptions) {
o.Timeout = t
}
}
// Error represents an error returned by API. It satisfies error interface.
type Error struct {
ErrorCode int
Description string
Parameters *ResponseParameters
}
// Error returns an error string.
func (e *Error) Error() string {
return fmt.Sprintf("telegram: %d %s", e.ErrorCode, e.Description)
}
// apiResponse represents API response. When OK is false then ErrorCode and
// Description defines the error situation.
type apiResponse struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result,omitempty"`
// error part
ErrorCode int `json:"error_code,omitempty"`
Description string `json:"description,omitempty"`
Parameters *ResponseParameters `json:"parameters,omitempty"`
}