forked from mail-ru-im/bot-golang
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
692 lines (562 loc) · 17.1 KB
/
client.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
package botgolang
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strconv"
"github.com/sirupsen/logrus"
)
type Client struct {
client *http.Client
token string
baseURL string
logger *logrus.Logger
}
func (c *Client) Do(path string, params url.Values, file *MessageFile) ([]byte, error) {
return c.DoWithContext(context.Background(), path, params, file)
}
func (c *Client) DoWithContext(ctx context.Context, path string, params url.Values, file *MessageFile) ([]byte, error) {
apiURL, err := url.Parse(c.baseURL + path)
params.Set("token", c.token)
if err != nil {
return nil, fmt.Errorf("cannot parse url: %s", err)
}
apiURL.RawQuery = params.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL.String(), nil)
if err != nil || req == nil {
return nil, fmt.Errorf("cannot init http request: %s", err)
}
if file != nil {
buffer := &bytes.Buffer{}
multipartWriter := multipart.NewWriter(buffer)
fileWriter, err := multipartWriter.CreateFormFile("file", file.Name())
if err != nil {
return nil, fmt.Errorf("cannot create multipart writer: %s", err)
}
_, err = io.Copy(fileWriter, file)
if err != nil {
return nil, fmt.Errorf("cannot copy file into buffer: %s", err)
}
if err := multipartWriter.Close(); err != nil {
return nil, fmt.Errorf("cannot close multipartWriter: %s", err)
}
req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
req.Body = io.NopCloser(buffer)
req.Method = http.MethodPost
}
c.logger.WithFields(logrus.Fields{
"api_url": apiURL,
}).Debug("requesting api")
resp, err := c.client.Do(req)
if err != nil {
c.logger.WithFields(logrus.Fields{
"err": err,
}).Error("request error")
return []byte{}, fmt.Errorf("cannot make request to bot api: %s", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
c.logger.WithFields(logrus.Fields{
"err": err,
}).Error("cannot close body")
}
}()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
c.logger.WithFields(logrus.Fields{
"err": err,
}).Error("cannot read body")
return []byte{}, fmt.Errorf("cannot read body: %s", err)
}
if c.logger.IsLevelEnabled(logrus.DebugLevel) {
c.logger.WithFields(logrus.Fields{
"response": responseBody,
}).Debug("got response from API")
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error status from API: %s", resp.Status)
}
response := &Response{}
if err := json.Unmarshal(responseBody, response); err != nil {
return nil, fmt.Errorf("cannot unmarshal json: %s", err)
}
if !response.OK {
return responseBody, fmt.Errorf("error status from API: %s", response.Description)
}
return responseBody, nil
}
func (c *Client) GetInfo() (*BotInfo, error) {
response, err := c.Do("/self/get", url.Values{}, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving information: %s", err)
}
info := &BotInfo{}
if err := json.Unmarshal(response, info); err != nil {
return nil, fmt.Errorf("error while unmarshalling information: %s", err)
}
return info, nil
}
func (c *Client) GetChatInfo(chatID string) (*Chat, error) {
params := url.Values{
"chatId": {chatID},
}
response, err := c.Do("/chats/getInfo", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving information: %s", err)
}
chat := &Chat{
client: c,
ID: chatID,
}
if err := json.Unmarshal(response, chat); err != nil {
return nil, fmt.Errorf("error while unmarshalling information: %s", err)
}
if chat.Type == Private {
return chat, nil
}
return chat, nil
}
func (c *Client) SendChatActions(chatID string, actions ...ChatAction) error {
actionsMap := make(map[ChatAction]bool)
filteredActions := make([]ChatAction, 0)
for _, action := range actions {
if _, has := actionsMap[action]; !has {
filteredActions = append(filteredActions, action)
actionsMap[action] = true
}
}
params := url.Values{
"chatId": {chatID},
"actions": filteredActions,
}
_, err := c.Do("/chats/sendActions", params, nil)
if err != nil {
return fmt.Errorf("error while receiving information: %s", err)
}
return nil
}
func (c *Client) GetChatAdmins(chatID string) ([]ChatMember, error) {
params := url.Values{
"chatId": {chatID},
}
response, err := c.Do("/chats/getAdmins", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving admins: %s", err)
}
admins := new(AdminsListResponse)
if err := json.Unmarshal(response, admins); err != nil {
return nil, fmt.Errorf("error while unmarshalling admins: %s", err)
}
return admins.List, nil
}
func (c *Client) GetChatMembers(chatID string) ([]ChatMember, error) {
params := url.Values{
"chatId": {chatID},
}
response, err := c.Do("/chats/getMembers", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving members: %s", err)
}
members := new(MembersListResponse)
if err := json.Unmarshal(response, members); err != nil {
return nil, fmt.Errorf("error while unmarshalling members: %s", err)
}
return members.List, nil
}
func (c *Client) GetChatBlockedUsers(chatID string) ([]User, error) {
params := url.Values{
"chatId": {chatID},
}
response, err := c.Do("/chats/getBlockedUsers", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving blocked users: %s", err)
}
users := new(UsersListResponse)
if err := json.Unmarshal(response, users); err != nil {
return nil, fmt.Errorf("error while unmarshalling blocked users: %s", err)
}
return users.List, nil
}
func (c *Client) GetChatPendingUsers(chatID string) ([]User, error) {
params := url.Values{
"chatId": {chatID},
}
response, err := c.Do("/chats/getPendingUsers", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving pending users: %s", err)
}
users := new(UsersListResponse)
if err := json.Unmarshal(response, users); err != nil {
return nil, fmt.Errorf("error while unmarshalling pending users: %s", err)
}
return users.List, nil
}
func (c *Client) BlockChatUser(chatID, userID string, deleteLastMessages bool) error {
params := url.Values{
"chatId": {chatID},
"userId": {userID},
"delLastMessages": {strconv.FormatBool(deleteLastMessages)},
}
response, err := c.Do("/chats/blockUser", params, nil)
if err != nil {
return fmt.Errorf("error while blocking user: %s", err)
}
users := new(UsersListResponse)
if err := json.Unmarshal(response, users); err != nil {
return fmt.Errorf("error while blocking user: %s", err)
}
return nil
}
func (c *Client) UnblockChatUser(chatID, userID string) error {
params := url.Values{
"chatId": {chatID},
"userId": {userID},
}
response, err := c.Do("/chats/unblockUser", params, nil)
if err != nil {
return fmt.Errorf("error while unblocking user: %s", err)
}
users := new(UsersListResponse)
if err := json.Unmarshal(response, users); err != nil {
return fmt.Errorf("error while unblocking user: %s", err)
}
return nil
}
func (c *Client) ResolveChatPending(chatID, userID string, approve, everyone bool) error {
params := url.Values{
"chatId": {chatID},
"approve": {strconv.FormatBool(approve)},
}
if everyone {
params.Set("everyone", "true")
} else {
params.Set("userId", userID)
}
if _, err := c.Do("/chats/resolvePending", params, nil); err != nil {
return fmt.Errorf("error while resolving chat pendings: %s", err)
}
return nil
}
func (c *Client) SetChatTitle(chatID, title string) error {
params := url.Values{
"chatId": {chatID},
"title": {title},
}
if _, err := c.Do("/chats/setTitle", params, nil); err != nil {
return fmt.Errorf("error while setting chat title: %s", err)
}
return nil
}
func (c *Client) SetChatAbout(chatID, about string) error {
params := url.Values{
"chatId": {chatID},
"about": {about},
}
if _, err := c.Do("/chats/setAbout", params, nil); err != nil {
return fmt.Errorf("error while setting chat about: %s", err)
}
return nil
}
func (c *Client) SetChatRules(chatID, rules string) error {
params := url.Values{
"chatId": {chatID},
"rules": {rules},
}
if _, err := c.Do("/chats/setRules", params, nil); err != nil {
return fmt.Errorf("error while setting chat rules: %s", err)
}
return nil
}
func (c *Client) GetFileInfo(fileID string) (*File, error) {
params := url.Values{
"fileId": {fileID},
}
response, err := c.Do("/files/getInfo", params, nil)
if err != nil {
return nil, fmt.Errorf("error while receiving information: %s", err)
}
file := &File{}
if err := json.Unmarshal(response, file); err != nil {
return nil, fmt.Errorf("error while unmarshalling information: %s", err)
}
return file, nil
}
func (c *Client) GetVoiceInfo(fileID string) (*File, error) {
return c.GetFileInfo(fileID)
}
func (c *Client) SendTextMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"text": {message.Text},
"request-id": {message.RequestID},
}
if message.ReplyMsgID != "" {
params.Set("replyMsgId", message.ReplyMsgID)
}
if message.ForwardMsgID != "" {
params.Set("forwardMsgId", message.ForwardMsgID)
params.Set("forwardChatId", message.ForwardChatID)
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
if message.ParseMode != "" {
params.Set("parseMode", string(message.ParseMode))
}
response, err := c.Do("/messages/sendText", params, nil)
if err != nil {
return fmt.Errorf("error while sending text: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response from API: %s", err)
}
return nil
}
func (c *Client) SendTextWithDeeplinkMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"text": {message.Text},
"request-id": {message.RequestID},
}
if message.ReplyMsgID != "" {
params.Set("replyMsgId", message.ReplyMsgID)
}
if message.ForwardMsgID != "" {
params.Set("forwardMsgId", message.ForwardMsgID)
params.Set("forwardChatId", message.ForwardChatID)
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
if len(message.Deeplink) == 0 {
return fmt.Errorf("deeplink can't be empty for SendTextWithDeeplink")
}
params.Set("deeplink", message.Deeplink)
if message.ParseMode != "" {
params.Set("parseMode", string(message.ParseMode))
}
response, err := c.Do("/messages/sendTextWithDeeplink", params, nil)
if err != nil {
return fmt.Errorf("error while sending text: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response from API: %s", err)
}
return nil
}
func (c *Client) EditMessage(message *Message) error {
params := url.Values{
"msgId": {message.ID},
"chatId": {message.Chat.ID},
"text": {message.Text},
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
if message.ParseMode != "" {
params.Set("parseMode", string(message.ParseMode))
}
response, err := c.Do("/messages/editText", params, nil)
if err != nil {
return fmt.Errorf("error while editing text: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response from API: %s", err)
}
return nil
}
func (c *Client) DeleteMessage(message *Message) error {
params := url.Values{
"msgId": {message.ID},
"chatId": {message.Chat.ID},
}
_, err := c.Do("/messages/deleteMessages", params, nil)
if err != nil {
return fmt.Errorf("error while deleting message: %s", err)
}
return nil
}
func (c *Client) SendFileMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"caption": {message.Text},
"fileId": {message.FileID},
}
if message.ReplyMsgID != "" {
params.Set("replyMsgId", message.ReplyMsgID)
}
if message.ForwardMsgID != "" {
params.Set("forwardMsgId", message.ForwardMsgID)
params.Set("forwardChatId", message.ForwardChatID)
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
if message.ParseMode != "" {
params.Set("parseMode", string(message.ParseMode))
}
response, err := c.Do("/messages/sendFile", params, nil)
if err != nil {
return fmt.Errorf("error while making request: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response: %s", err)
}
return nil
}
func (c *Client) SendVoiceMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"caption": {message.Text},
"fileId": {message.FileID},
}
if message.ReplyMsgID != "" {
params.Set("replyMsgId", message.ReplyMsgID)
}
if message.ForwardMsgID != "" {
params.Set("forwardMsgId", message.ForwardMsgID)
params.Set("forwardChatId", message.ForwardChatID)
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
response, err := c.Do("/messages/sendVoice", params, nil)
if err != nil {
return fmt.Errorf("error while making request: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response: %s", err)
}
return nil
}
func (c *Client) UploadFile(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"caption": {message.Text},
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
response, err := c.Do("/messages/sendFile", params, message.File)
if err != nil {
return fmt.Errorf("error while making request: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response: %s", err)
}
return nil
}
func (c *Client) UploadVoice(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"caption": {message.Text},
}
if message.InlineKeyboard != nil {
data, err := json.Marshal(message.InlineKeyboard.GetKeyboard())
if err != nil {
return fmt.Errorf("cannot marshal inline keyboard markup: %s", err)
}
params.Set("inlineKeyboardMarkup", string(data))
}
response, err := c.Do("/messages/sendVoice", params, message.File)
if err != nil {
return fmt.Errorf("error while making request: %s", err)
}
if err := json.Unmarshal(response, message); err != nil {
return fmt.Errorf("cannot unmarshal response: %s", err)
}
return nil
}
func (c *Client) GetEvents(lastEventID int, pollTime int) ([]*Event, error) {
return c.GetEventsWithContext(context.Background(), lastEventID, pollTime)
}
func (c *Client) GetEventsWithContext(ctx context.Context, lastEventID int, pollTime int) ([]*Event, error) {
params := url.Values{
"lastEventId": {strconv.Itoa(lastEventID)},
"pollTime": {strconv.Itoa(pollTime)},
}
events := &eventsResponse{}
response, err := c.DoWithContext(ctx, "/events/get", params, nil)
if err != nil {
return events.Events, fmt.Errorf("error while making request: %s", err)
}
if err := json.Unmarshal(response, events); err != nil {
return events.Events, fmt.Errorf("cannot parse events: %s", err)
}
return events.Events, nil
}
func (c *Client) PinMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"msgId": {message.ID},
}
_, err := c.Do("/chats/pinMessage", params, nil)
if err != nil {
return fmt.Errorf("error while pinning message: %s", err)
}
return nil
}
func (c *Client) UnpinMessage(message *Message) error {
params := url.Values{
"chatId": {message.Chat.ID},
"msgId": {message.ID},
}
_, err := c.Do("/chats/unpinMessage", params, nil)
if err != nil {
return fmt.Errorf("error while unpinning message: %s", err)
}
return nil
}
func (c *Client) SendAnswerCallbackQuery(answer *ButtonResponse) error {
params := url.Values{
"queryId": {answer.QueryID},
"text": {answer.Text},
"url": {answer.URL},
"showAlert": {strconv.FormatBool(answer.ShowAlert)},
}
_, err := c.Do("/messages/answerCallbackQuery", params, nil)
if err != nil {
return fmt.Errorf("error while making request: %s", err)
}
return nil
}
func NewClient(baseURL string, token string, logger *logrus.Logger) *Client {
return NewCustomClient(http.DefaultClient, baseURL, token, logger)
}
func NewCustomClient(client *http.Client, baseURL string, token string, logger *logrus.Logger) *Client {
return &Client{
token: token,
baseURL: baseURL,
client: client,
logger: logger,
}
}