forked from tucnak/telebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
1156 lines (947 loc) · 26.1 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
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package telebot
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
// NewBot does try to build a Bot with token `token`, which
// is a secret API key assigned to particular bot.
func NewBot(pref Settings) (*Bot, error) {
if pref.Updates == 0 {
pref.Updates = 100
}
client := pref.Client
if client == nil {
client = http.DefaultClient
}
bot := &Bot{
Token: pref.Token,
Updates: make(chan Update, pref.Updates),
Poller: pref.Poller,
handlers: make(map[string]interface{}),
stop: make(chan struct{}),
reporter: pref.Reporter,
client: client,
}
user, err := bot.getMe()
if err != nil {
return nil, err
}
bot.Me = user
return bot, nil
}
// Bot represents a separate Telegram bot instance.
type Bot struct {
Me *User
Token string
Updates chan Update
Poller Poller
handlers map[string]interface{}
reporter func(error)
stop chan struct{}
client *http.Client
}
// Settings represents a utility struct for passing certain
// properties of a bot around and is required to make bots.
type Settings struct {
// Telegram token
Token string
// Updates channel capacity
Updates int // Default: 100
// Poller is the provider of Updates.
Poller Poller
// Reporter is a callback function that will get called
// on any panics recovered from endpoint handlers.
Reporter func(error)
// HTTP Client used to make requests to telegram api
Client *http.Client
}
// Update object represents an incoming update.
type Update struct {
ID int `json:"update_id"`
Message *Message `json:"message,omitempty"`
EditedMessage *Message `json:"edited_message,omitempty"`
ChannelPost *Message `json:"channel_post,omitempty"`
EditedChannelPost *Message `json:"edited_channel_post,omitempty"`
Callback *Callback `json:"callback_query,omitempty"`
Query *Query `json:"inline_query,omitempty"`
ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"`
}
// ChosenInlineResult represents a result of an inline query that was chosen
// by the user and sent to their chat partner.
type ChosenInlineResult struct {
ResultID string `json:"result_id"`
Query string `json:"query"`
// Inline messages only!
MessageID string `json:"inline_message_id"`
From User `json:"from"`
Location *Location `json:"location,omitempty"`
}
// Handle lets you set the handler for some command name or
// one of the supported endpoints.
//
// Example:
//
// b.handle("/help", func (m *tb.Message) {})
// b.handle(tb.OnEdited, func (m *tb.Message) {})
// b.handle(tb.OnQuery, func (q *tb.Query) {})
//
// // make a hook for one of your preserved (by-pointer)
// // inline buttons.
// b.handle(&inlineButton, func (c *tb.Callback) {})
//
func (b *Bot) Handle(endpoint interface{}, handler interface{}) {
switch end := endpoint.(type) {
case string:
b.handlers[end] = handler
case CallbackEndpoint:
b.handlers[end.CallbackUnique()] = handler
default:
panic("telebot: unsupported endpoint")
}
}
var (
cmdRx = regexp.MustCompile(`^(\/\w+)(@(\w+))?(\s|$)(.+)?`)
cbackRx = regexp.MustCompile(`^\f(\w+)(\|(.+))?$`)
)
func (b *Bot) handleCommand(m *Message, cmdName, cmdBot string) bool {
return false
}
// Start brings bot into motion by consuming incoming
// updates (see Bot.Updates channel).
func (b *Bot) Start() {
if b.Poller == nil {
panic("telebot: can't start without a poller")
}
stopPoller := make(chan struct{})
go b.Poller.Poll(b, b.Updates, stopPoller)
for {
select {
// handle incoming updates
case upd := <-b.Updates:
b.incomingUpdate(&upd)
// call to stop polling
case <-b.stop:
stopPoller <- struct{}{}
// polling has stopped
case <-stopPoller:
return
}
}
}
func (b *Bot) incomingUpdate(upd *Update) {
if upd.Message != nil {
m := upd.Message
if m.PinnedMessage != nil {
b.handle(OnPinned, m)
return
}
// Commands
if m.Text != "" {
// Filtering malicious messsages
if m.Text[0] == '\a' {
return
}
match := cmdRx.FindAllStringSubmatch(m.Text, -1)
// Command found - handle and return
if match != nil {
// Syntax: "</command>@<bot> <payload>"
command, botName := match[0][1], match[0][3]
m.Payload = match[0][5]
if botName != "" && !strings.EqualFold(b.Me.Username, botName) {
return
}
if b.handle(command, m) {
return
}
}
// 1:1 satisfaction
if b.handle(m.Text, m) {
return
}
// OnText
b.handle(OnText, m)
return
}
// on media
if b.handleMedia(m) {
return
}
// OnAddedToGroup
wasAdded := (m.UserJoined != nil && m.UserJoined.ID == b.Me.ID) ||
(m.UsersJoined != nil && isUserInList(b.Me, m.UsersJoined))
if m.GroupCreated || m.SuperGroupCreated || wasAdded {
b.handle(OnAddedToGroup, m)
return
}
if m.UserJoined != nil {
b.handle(OnUserJoined, m)
return
}
if m.UsersJoined != nil {
for _, user := range m.UsersJoined {
m.UserJoined = &user
b.handle(OnUserJoined, m)
}
return
}
if m.UserLeft != nil {
b.handle(OnUserLeft, m)
return
}
if m.NewGroupTitle != "" {
b.handle(OnNewGroupTitle, m)
return
}
if m.NewGroupPhoto != nil {
b.handle(OnNewGroupPhoto, m)
return
}
if m.GroupPhotoDeleted {
b.handle(OnGroupPhotoDeleted, m)
return
}
if m.MigrateTo != 0 {
if handler, ok := b.handlers[OnMigration]; ok {
if handler, ok := handler.(func(int64, int64)); ok {
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(int64, int64), from, to int64) {
defer b.deferDebug()
handler(from, to)
}(b, handler, m.MigrateFrom, m.MigrateTo)
} else {
panic("telebot: migration handler is bad")
}
}
return
}
return
}
if upd.EditedMessage != nil {
b.handle(OnEdited, upd.EditedMessage)
return
}
if upd.ChannelPost != nil {
b.handle(OnChannelPost, upd.ChannelPost)
return
}
if upd.EditedChannelPost != nil {
b.handle(OnEditedChannelPost, upd.EditedChannelPost)
return
}
if upd.Callback != nil {
if upd.Callback.Data != "" {
data := upd.Callback.Data
if data[0] == '\f' {
match := cbackRx.FindAllStringSubmatch(data, -1)
if match != nil {
unique, payload := match[0][1], match[0][3]
if handler, ok := b.handlers["\f"+unique]; ok {
if handler, ok := handler.(func(*Callback)); ok {
upd.Callback.Data = payload
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(*Callback), c *Callback) {
defer b.deferDebug()
handler(c)
}(b, handler, upd.Callback)
return
}
}
}
}
}
if handler, ok := b.handlers[OnCallback]; ok {
if handler, ok := handler.(func(*Callback)); ok {
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(*Callback), c *Callback) {
defer b.deferDebug()
handler(c)
}(b, handler, upd.Callback)
} else {
panic("telebot: callback handler is bad")
}
}
return
}
if upd.Query != nil {
if handler, ok := b.handlers[OnQuery]; ok {
if handler, ok := handler.(func(*Query)); ok {
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(*Query), q *Query) {
defer b.deferDebug()
handler(q)
}(b, handler, upd.Query)
} else {
panic("telebot: query handler is bad")
}
}
return
}
if upd.ChosenInlineResult != nil {
if handler, ok := b.handlers[OnChosenInlineResult]; ok {
if handler, ok := handler.(func(*ChosenInlineResult)); ok {
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(*ChosenInlineResult),
r *ChosenInlineResult) {
defer b.deferDebug()
handler(r)
}(b, handler, upd.ChosenInlineResult)
} else {
panic("telebot: chosen inline result handler is bad")
}
}
return
}
}
func (b *Bot) handle(end string, m *Message) bool {
handler, ok := b.handlers[end]
if !ok {
return false
}
if handler, ok := handler.(func(*Message)); ok {
// i'm not 100% sure that any of the values
// won't be cached, so I pass them all in:
go func(b *Bot, handler func(*Message), m *Message) {
defer b.deferDebug()
handler(m)
}(b, handler, m)
return true
}
return false
}
func (b *Bot) handleMedia(m *Message) bool {
if m.Photo != nil {
b.handle(OnPhoto, m)
return true
}
if m.Voice != nil {
b.handle(OnVoice, m)
return true
}
if m.Audio != nil {
b.handle(OnAudio, m)
return true
}
if m.Document != nil {
b.handle(OnDocument, m)
return true
}
if m.Sticker != nil {
b.handle(OnSticker, m)
return true
}
if m.Video != nil {
b.handle(OnVideo, m)
return true
}
if m.VideoNote != nil {
b.handle(OnVideoNote, m)
return true
}
if m.Contact != nil {
b.handle(OnContact, m)
return true
}
if m.Location != nil {
b.handle(OnLocation, m)
return true
}
if m.Venue != nil {
b.handle(OnVenue, m)
return true
}
return false
}
// Stop gracefully shuts the poller down.
func (b *Bot) Stop() {
b.stop <- struct{}{}
}
// Send accepts 2+ arguments, starting with destination chat, followed by
// some Sendable (or string!) and optional send options.
//
// Note: since most arguments are of type interface{}, but have pointer
// method recievers, make sure to pass them by-pointer, NOT by-value.
//
// What is a send option exactly? It can be one of the following types:
//
// - *SendOptions (the actual object accepted by Telegram API)
// - *ReplyMarkup (a component of SendOptions)
// - Option (a shorcut flag for popular options)
// - ParseMode (HTML, Markdown, etc)
//
// This function will panic upon unsupported payloads and options!
func (b *Bot) Send(to Recipient, what interface{}, options ...interface{}) (*Message, error) {
sendOpts := extractOptions(options)
switch object := what.(type) {
case string:
return b.sendText(to, object, sendOpts)
case Sendable:
return object.Send(b, to, sendOpts)
default:
return nil, errors.New("telebot: unsupported sendable")
}
}
// SendAlbum is used when sending multiple instances of media as a single
// message (so-called album).
//
// From all existing options, it only supports telebot.Silent.
func (b *Bot) SendAlbum(to Recipient, a Album, options ...interface{}) ([]Message, error) {
media := make([]string, len(a))
files := make(map[string]File)
for i, x := range a {
var mediaRepr string
var jsonRepr []byte
f := x.MediaFile()
if f.InCloud() {
mediaRepr = f.FileID
} else if f.FileURL != "" {
mediaRepr = f.FileURL
} else if f.OnDisk() || f.FileReader != nil {
mediaRepr = fmt.Sprintf("attach://%d", i)
files[strconv.Itoa(i)] = *f
} else {
return nil, errors.Errorf(
"telebot: album entry #%d doesn't exist anywhere", i)
}
switch y := x.(type) {
case *Photo:
jsonRepr, _ = json.Marshal(struct {
Type string `json:"type"`
Caption string `json:"caption"`
Media string `json:"media"`
}{
"photo",
y.Caption,
mediaRepr,
})
case *Video:
jsonRepr, _ = json.Marshal(struct {
Type string `json:"type"`
Caption string `json:"caption"`
Media string `json:"media"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Duration int `json:"duration,omitempty"`
SupportsStreaming bool `json:"supports_streaming,omitempty"`
}{
"video",
y.Caption,
mediaRepr,
y.Width,
y.Height,
y.Duration,
y.SupportsStreaming,
})
default:
return nil, errors.Errorf("telebot: album entry #%d is not valid", i)
}
media[i] = string(jsonRepr)
}
params := map[string]string{
"chat_id": to.Recipient(),
"media": "[" + strings.Join(media, ",") + "]",
}
sendOpts := extractOptions(options)
embedSendOptions(params, sendOpts)
respJSON, err := b.sendFiles("sendMediaGroup", files, params)
if err != nil {
return nil, err
}
var resp struct {
Ok bool
Result []Message
Description string
}
err = json.Unmarshal(respJSON, &resp)
if err != nil {
return nil, errors.Wrap(err, "bad response json")
}
if !resp.Ok {
return nil, errors.Errorf("api error: %s", resp.Description)
}
for attachName, _ := range files {
i, _ := strconv.Atoi(attachName)
var newID string
if resp.Result[i].Photo != nil {
newID = resp.Result[i].Photo.FileID
} else {
newID = resp.Result[i].Video.FileID
}
a[i].MediaFile().FileID = newID
}
return resp.Result, nil
}
// Reply behaves just like Send() with an exception of "reply-to" indicator.
func (b *Bot) Reply(to *Message, what interface{}, options ...interface{}) (*Message, error) {
// This function will panic upon unsupported payloads and options!
sendOpts := extractOptions(options)
if sendOpts == nil {
sendOpts = &SendOptions{}
}
sendOpts.ReplyTo = to
return b.Send(to.Chat, what, sendOpts)
}
// Forward behaves just like Send() but of all options it
// only supports Silent (see Bots API).
//
// This function will panic upon unsupported payloads and options!
func (b *Bot) Forward(to Recipient, what *Message, options ...interface{}) (*Message, error) {
params := map[string]string{
"chat_id": to.Recipient(),
"from_chat_id": what.Chat.Recipient(),
"message_id": strconv.Itoa(what.ID),
}
sendOpts := extractOptions(options)
embedSendOptions(params, sendOpts)
respJSON, err := b.Raw("forwardMessage", params)
if err != nil {
return nil, err
}
return extractMsgResponse(respJSON)
}
// Edit is magic, it lets you change already sent message.
//
// Use cases:
//
// b.Edit(msg, msg.Text, newMarkup)
// b.Edit(msg, "new <b>text</b>", tb.ModeHTML)
//
// // Edit live location:
// b.Edit(liveMsg, tb.Location{42.1337, 69.4242})
//
func (b *Bot) Edit(message Editable, what interface{}, options ...interface{}) (*Message, error) {
messageID, chatID := message.MessageSig()
// TODO: add support for inline messages (chatID = 0)
params := map[string]string{}
switch v := what.(type) {
case string:
params["text"] = v
case Location:
params["latitude"] = fmt.Sprintf("%f", v.Lat)
params["longitude"] = fmt.Sprintf("%f", v.Lng)
default:
panic("telebot: unsupported what argument")
}
// if inline message
if chatID == 0 {
params["inline_message_id"] = messageID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = messageID
}
sendOpts := extractOptions(options)
embedSendOptions(params, sendOpts)
respJSON, err := b.Raw("editMessageText", params)
if err != nil {
return nil, err
}
return extractMsgResponse(respJSON)
}
// EditCaption used to edit already sent photo caption with known recepient and message id.
//
// On success, returns edited message object
func (b *Bot) EditCaption(originalMsg Editable, caption string) (*Message, error) {
messageID, chatID := originalMsg.MessageSig()
params := map[string]string{"caption": caption}
// if inline message
if chatID == 0 {
params["inline_message_id"] = messageID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = messageID
}
respJSON, err := b.Raw("editMessageCaption", params)
if err != nil {
return nil, err
}
return extractMsgResponse(respJSON)
}
// Delete removes the message, including service messages,
// with the following limitations:
//
// * A message can only be deleted if it was sent less than 48 hours ago.
// * Bots can delete outgoing messages in groups and supergroups.
// * Bots granted can_post_messages permissions can delete outgoing
// messages in channels.
// * If the bot is an administrator of a group, it can delete any message there.
// * If the bot has can_delete_messages permission in a supergroup or a
// channel, it can delete any message there.
//
func (b *Bot) Delete(message Editable) error {
messageID, chatID := message.MessageSig()
params := map[string]string{
"chat_id": strconv.FormatInt(chatID, 10),
"message_id": messageID,
}
respJSON, err := b.Raw("deleteMessage", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// Notify updates the chat action for recipient.
//
// Chat action is a status message that recipient would see where
// you typically see "Harry is typing" status message. The only
// difference is that bots' chat actions live only for 5 seconds
// and die just once the client recieves a message from the bot.
//
// Currently, Telegram supports only a narrow range of possible
// actions, these are aligned as constants of this package.
func (b *Bot) Notify(recipient Recipient, action ChatAction) error {
params := map[string]string{
"chat_id": recipient.Recipient(),
"action": string(action),
}
respJSON, err := b.Raw("sendChatAction", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// Answer sends a response for a given inline query. A query can only
// be responded to once, subsequent attempts to respond to the same query
// will result in an error.
func (b *Bot) Answer(query *Query, response *QueryResponse) error {
response.QueryID = query.ID
for _, result := range response.Results {
result.Process()
}
respJSON, err := b.Raw("answerInlineQuery", response)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// Respond sends a response for a given callback query. A callback can
// only be responded to once, subsequent attempts to respond to the same callback
// will result in an error.
//
// Example:
//
// bot.Respond(c)
// bot.Respond(c, response)
//
func (b *Bot) Respond(callback *Callback, responseOptional ...*CallbackResponse) error {
var response *CallbackResponse
if responseOptional == nil {
response = &CallbackResponse{}
} else {
response = responseOptional[0]
}
response.CallbackID = callback.ID
respJSON, err := b.Raw("answerCallbackQuery", response)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// FileByID returns full file object including File.FilePath, allowing you to
// download the file from the server.
//
// Usually, Telegram-provided File objects miss FilePath so you might need to
// perform an additional request to fetch them.
func (b *Bot) FileByID(fileID string) (File, error) {
params := map[string]string{
"file_id": fileID,
}
respJSON, err := b.Raw("getFile", params)
if err != nil {
return File{}, err
}
var resp struct {
Ok bool
Description string
Result File
}
err = json.Unmarshal(respJSON, &resp)
if err != nil {
return File{}, errors.Wrap(err, "bad response json")
}
if !resp.Ok {
return File{}, errors.Errorf("api error: %s", resp.Description)
}
return resp.Result, nil
}
// Download saves the file from Telegram servers locally.
//
// Maximum file size to download is 20 MB.
func (b *Bot) Download(f *File, localFilename string) error {
g, err := b.FileByID(f.FileID)
if err != nil {
return err
}
url := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s",
b.Token, g.FilePath)
out, err := os.Create(localFilename)
if err != nil {
return wrapSystem(err)
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return wrapSystem(err)
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return wrapSystem(err)
}
g.FileLocal = localFilename
*f = g
return nil
}
// StopLiveLocation should be called to stop broadcasting live message location
// before Location.LivePeriod expires.
//
// It supports telebot.ReplyMarkup.
func (b *Bot) StopLiveLocation(message Editable, options ...interface{}) (*Message, error) {
messageID, chatID := message.MessageSig()
params := map[string]string{
"chat_id": fmt.Sprintf("%d", chatID),
"message_id": messageID,
}
sendOpts := extractOptions(options)
embedSendOptions(params, sendOpts)
respJSON, err := b.Raw("stopMessageLiveLocation", params)
if err != nil {
return nil, err
}
return extractMsgResponse(respJSON)
}
// GetInviteLink should be used to export chat's invite link.
func (b *Bot) GetInviteLink(chat *Chat) (string, error) {
params := map[string]string{
"chat_id": chat.Recipient(),
}
respJSON, err := b.Raw("exportChatInviteLink", params)
if err != nil {
return "", err
}
var resp struct {
Ok bool
Description string
Result string
}
err = json.Unmarshal(respJSON, &resp)
if err != nil {
return "", errors.Wrap(err, "bad response json")
}
if !resp.Ok {
return "", errors.Errorf("api error: %s", resp.Description)
}
return resp.Result, nil
}
// SetChatTitle should be used to update group title.
func (b *Bot) SetGroupTitle(chat *Chat, newTitle string) error {
params := map[string]string{
"chat_id": chat.Recipient(),
"title": newTitle,
}
respJSON, err := b.Raw("setChatTitle", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// SetGroupDescription should be used to update group title.
func (b *Bot) SetGroupDescription(chat *Chat, description string) error {
params := map[string]string{
"chat_id": chat.Recipient(),
"description": description,
}
respJSON, err := b.Raw("setChatDescription", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// SetGroupPhoto should be used to update group photo.
func (b *Bot) SetGroupPhoto(chat *Chat, p *Photo) error {
params := map[string]string{
"chat_id": chat.Recipient(),
}
respJSON, err := b.sendFiles("setChatPhoto", map[string]File{"photo": p.File}, params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// SetGroupStickerSet should be used to update group's group sticker set.
func (b *Bot) SetGroupStickerSet(chat *Chat, setName string) error {
params := map[string]string{
"chat_id": chat.Recipient(),
"sticker_set_name": setName,
}
respJSON, err := b.Raw("setChatStickerSet", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// DeleteGroupPhoto should be used to just remove group photo.
func (b *Bot) DeleteGroupPhoto(chat *Chat) error {
params := map[string]string{
"chat_id": chat.Recipient(),
}
respJSON, err := b.Raw("deleteGroupPhoto", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// DeleteGroupStickerSet should be used to just remove group sticker set.
func (b *Bot) DeleteGroupStickerSet(chat *Chat) error {
params := map[string]string{
"chat_id": chat.Recipient(),
}
respJSON, err := b.Raw("deleteChatStickerSet", params)
if err != nil {
return err
}
return extractOkResponse(respJSON)
}
// Leave makes bot leave a group, supergroup or channel.
func (b *Bot) Leave(chat *Chat) error {
params := map[string]string{
"chat_id": chat.Recipient(),
}
respJSON, err := b.Raw("leaveChat", params)
if err != nil {