-
Notifications
You must be signed in to change notification settings - Fork 469
/
bot.go
1354 lines (1138 loc) · 32.8 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"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// 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.Client{Timeout: time.Minute}
}
if pref.URL == "" {
pref.URL = DefaultApiURL
}
if pref.Poller == nil {
pref.Poller = &LongPoller{}
}
if pref.OnError == nil {
pref.OnError = defaultOnError
}
bot := &Bot{
Token: pref.Token,
URL: pref.URL,
Poller: pref.Poller,
onError: pref.OnError,
Updates: make(chan Update, pref.Updates),
handlers: make(map[string]HandlerFunc),
stop: make(chan chan struct{}),
synchronous: pref.Synchronous,
verbose: pref.Verbose,
parseMode: pref.ParseMode,
client: client,
}
if pref.Offline {
bot.Me = &User{}
} else {
user, err := bot.getMe()
if err != nil {
return nil, err
}
bot.Me = user
}
bot.group = bot.Group()
return bot, nil
}
// Bot represents a separate Telegram bot instance.
type Bot struct {
Me *User
Token string
URL string
Updates chan Update
Poller Poller
onError func(error, Context)
group *Group
handlers map[string]HandlerFunc
synchronous bool
verbose bool
parseMode ParseMode
stop chan chan struct{}
client *http.Client
stopMu sync.RWMutex
stopClient chan struct{}
}
// Settings represents a utility struct for passing certain
// properties of a bot around and is required to make bots.
type Settings struct {
URL string
Token string
// Updates channel capacity, defaulted to 100.
Updates int
// Poller is the provider of Updates.
Poller Poller
// Synchronous prevents handlers from running in parallel.
// It makes ProcessUpdate return after the handler is finished.
Synchronous bool
// Verbose forces bot to log all upcoming requests.
// Use for debugging purposes only.
Verbose bool
// ParseMode used to set default parse mode of all sent messages.
// It attaches to every send, edit or whatever method. You also
// will be able to override the default mode by passing a new one.
ParseMode ParseMode
// OnError is a callback function that will get called on errors
// resulted from the handler. It is used as post-middleware function.
// Notice that context can be nil.
OnError func(error, Context)
// HTTP Client used to make requests to telegram api
Client *http.Client
// Offline allows to create a bot without network for testing purposes.
Offline bool
}
var defaultOnError = func(err error, c Context) {
if c != nil {
log.Println(c.Update().ID, err)
} else {
log.Println(err)
}
}
func (b *Bot) OnError(err error, c Context) {
b.onError(err, c)
}
func (b *Bot) debug(err error) {
if b.verbose {
b.OnError(err, nil)
}
}
// Group returns a new group.
func (b *Bot) Group() *Group {
return &Group{b: b}
}
// Use adds middleware to the global bot chain.
func (b *Bot) Use(middleware ...MiddlewareFunc) {
b.group.Use(middleware...)
}
var (
cmdRx = regexp.MustCompile(`^(/\w+)(@(\w+))?(\s|$)(.+)?`)
cbackRx = regexp.MustCompile(`^\f([-\w]+)(\|(.+))?$`)
)
// Handle lets you set the handler for some command name or
// one of the supported endpoints. It also applies middleware
// if such passed to the function.
//
// Example:
//
// b.Handle("/start", func (c tele.Context) error {
// return c.Reply("Hello!")
// })
//
// b.Handle(&inlineButton, func (c tele.Context) error {
// return c.Respond(&tele.CallbackResponse{Text: "Hello!"})
// })
//
// Middleware usage:
//
// b.Handle("/ban", onBan, middleware.Whitelist(ids...))
func (b *Bot) Handle(endpoint interface{}, h HandlerFunc, m ...MiddlewareFunc) {
end := extractEndpoint(endpoint)
if end == "" {
panic("telebot: unsupported endpoint")
}
if len(b.group.middleware) > 0 {
m = appendMiddleware(b.group.middleware, m)
}
b.handlers[end] = func(c Context) error {
return applyMiddleware(h, m...)(c)
}
}
// Trigger executes the registered handler by the endpoint.
func (b *Bot) Trigger(endpoint interface{}, c Context) error {
end := extractEndpoint(endpoint)
if end == "" {
return fmt.Errorf("telebot: unsupported endpoint")
}
handler, ok := b.handlers[end]
if !ok {
return fmt.Errorf("telebot: no handler found for given endpoint")
}
return handler(c)
}
// 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")
}
// do nothing if called twice
b.stopMu.Lock()
if b.stopClient != nil {
b.stopMu.Unlock()
return
}
b.stopClient = make(chan struct{})
b.stopMu.Unlock()
stop := make(chan struct{})
stopConfirm := make(chan struct{})
go func() {
b.Poller.Poll(b, b.Updates, stop)
close(stopConfirm)
}()
for {
select {
// handle incoming updates
case upd := <-b.Updates:
b.ProcessUpdate(upd)
// call to stop polling
case confirm := <-b.stop:
close(stop)
<-stopConfirm
close(confirm)
return
}
}
}
// Stop gracefully shuts the poller down.
func (b *Bot) Stop() {
b.stopMu.Lock()
if b.stopClient != nil {
close(b.stopClient)
b.stopClient = nil
}
b.stopMu.Unlock()
confirm := make(chan struct{})
b.stop <- confirm
<-confirm
}
// NewMarkup simply returns newly created markup instance.
func (b *Bot) NewMarkup() *ReplyMarkup {
return &ReplyMarkup{}
}
// NewContext returns a new native context object,
// field by the passed update.
func (b *Bot) NewContext(u Update) Context {
return NewContext(b, u)
}
// 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 receivers, 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 shortcut flag for popular options)
// - ParseMode (HTML, Markdown, etc)
func (b *Bot) Send(to Recipient, what interface{}, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
sendOpts := b.extractOptions(opts)
switch object := what.(type) {
case string:
return b.sendText(to, object, sendOpts)
case Sendable:
return object.Send(b, to, sendOpts)
default:
return nil, ErrUnsupportedWhat
}
}
// SendPaid sends multiple instances of paid media as a single message.
// To include the caption, make sure the first PaidInputtable of an album has it.
func (b *Bot) SendPaid(to Recipient, stars int, a PaidAlbum, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
params := map[string]string{
"chat_id": to.Recipient(),
"star_count": strconv.Itoa(stars),
}
sendOpts := b.extractOptions(opts)
media := make([]string, len(a))
files := make(map[string]File)
for i, x := range a {
repr := x.MediaFile().process(strconv.Itoa(i), files)
if repr == "" {
return nil, fmt.Errorf("telebot: paid media entry #%d does not exist", i)
}
im := x.InputMedia()
im.Media = repr
if i == 0 {
params["caption"] = im.Caption
if im.CaptionAbove {
params["show_caption_above_media"] = "true"
}
}
data, _ := json.Marshal(im)
media[i] = string(data)
}
params["media"] = "[" + strings.Join(media, ",") + "]"
b.embedSendOptions(params, sendOpts)
data, err := b.sendFiles("sendPaidMedia", files, params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// SendAlbum sends multiple instances of media as a single message.
// To include the caption, make sure the first Inputtable of an album has it.
// From all existing options, it only supports tele.Silent.
func (b *Bot) SendAlbum(to Recipient, a Album, opts ...interface{}) ([]Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
sendOpts := b.extractOptions(opts)
media := make([]string, len(a))
files := make(map[string]File)
for i, x := range a {
repr := x.MediaFile().process(strconv.Itoa(i), files)
if repr == "" {
return nil, fmt.Errorf("telebot: album entry #%d does not exist", i)
}
im := x.InputMedia()
im.Media = repr
if len(sendOpts.Entities) > 0 {
im.Entities = sendOpts.Entities
} else {
im.ParseMode = sendOpts.ParseMode
}
data, _ := json.Marshal(im)
media[i] = string(data)
}
params := map[string]string{
"chat_id": to.Recipient(),
"media": "[" + strings.Join(media, ",") + "]",
}
b.embedSendOptions(params, sendOpts)
data, err := b.sendFiles("sendMediaGroup", files, params)
if err != nil {
return nil, err
}
var resp struct {
Result []Message
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, wrapError(err)
}
for attachName := range files {
i, _ := strconv.Atoi(attachName)
r := resp.Result[i]
var newID string
switch {
case r.Photo != nil:
newID = r.Photo.FileID
case r.Video != nil:
newID = r.Video.FileID
case r.Audio != nil:
newID = r.Audio.FileID
case r.Document != nil:
newID = r.Document.FileID
}
a[i].MediaFile().FileID = newID
}
return resp.Result, nil
}
// Reply behaves just like Send() with an exception of "reply-to" indicator.
// This function will panic upon nil Message.
func (b *Bot) Reply(to *Message, what interface{}, opts ...interface{}) (*Message, error) {
sendOpts := b.extractOptions(opts)
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 nil Editable.
func (b *Bot) Forward(to Recipient, msg Editable, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
msgID, chatID := msg.MessageSig()
params := map[string]string{
"chat_id": to.Recipient(),
"from_chat_id": strconv.FormatInt(chatID, 10),
"message_id": msgID,
}
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("forwardMessage", params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// ForwardMany method forwards multiple messages of any kind.
// If some of the specified messages can't be found or forwarded, they are skipped.
// Service messages and messages with protected content can't be forwarded.
// Album grouping is kept for forwarded messages.
func (b *Bot) ForwardMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
return b.forwardCopyMany(to, msgs, "forwardMessages", opts...)
}
// Copy behaves just like Forward() but the copied message doesn't have a link to the original message (see Bots API).
//
// This function will panic upon nil Editable.
func (b *Bot) Copy(to Recipient, msg Editable, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
msgID, chatID := msg.MessageSig()
params := map[string]string{
"chat_id": to.Recipient(),
"from_chat_id": strconv.FormatInt(chatID, 10),
"message_id": msgID,
}
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("copyMessage", params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// CopyMany this method makes a copy of messages of any kind.
// If some of the specified messages can't be found or copied, they are skipped.
// Service messages, giveaway messages, giveaway winners messages, and
// invoice messages can't be copied. A quiz poll can be copied only if the value of the field
// correct_option_id is known to the bot. The method is analogous
// to the method forwardMessages, but the copied messages don't have a link to the original message.
// Album grouping is kept for copied messages.
func (b *Bot) CopyMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
return b.forwardCopyMany(to, msgs, "copyMessages", opts...)
}
// Edit is magic, it lets you change already sent message.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
//
// Use cases:
//
// b.Edit(m, m.Text, newMarkup)
// b.Edit(m, "new <b>text</b>", tele.ModeHTML)
// b.Edit(m, &tele.ReplyMarkup{...})
// b.Edit(m, &tele.Photo{File: ...})
// b.Edit(m, tele.Location{42.1337, 69.4242})
// b.Edit(c, "edit inline message from the callback")
// b.Edit(r, "edit message from chosen inline result")
func (b *Bot) Edit(msg Editable, what interface{}, opts ...interface{}) (*Message, error) {
var (
method string
params = make(map[string]string)
)
switch v := what.(type) {
case *ReplyMarkup:
return b.EditReplyMarkup(msg, v)
case Inputtable:
return b.EditMedia(msg, v, opts...)
case string:
method = "editMessageText"
params["text"] = v
case Location:
method = "editMessageLiveLocation"
params["latitude"] = fmt.Sprintf("%f", v.Lat)
params["longitude"] = fmt.Sprintf("%f", v.Lng)
if v.HorizontalAccuracy != nil {
params["horizontal_accuracy"] = fmt.Sprintf("%f", *v.HorizontalAccuracy)
}
if v.Heading != 0 {
params["heading"] = strconv.Itoa(v.Heading)
}
if v.AlertRadius != 0 {
params["proximity_alert_radius"] = strconv.Itoa(v.AlertRadius)
}
if v.LivePeriod != 0 {
params["live_period"] = strconv.Itoa(v.LivePeriod)
}
default:
return nil, ErrUnsupportedWhat
}
msgID, chatID := msg.MessageSig()
if chatID == 0 { // if inline message
params["inline_message_id"] = msgID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = msgID
}
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw(method, params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// EditReplyMarkup edits reply markup of already sent message.
// This function will panic upon nil Editable.
// Pass nil or empty ReplyMarkup to delete it from the message.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
func (b *Bot) EditReplyMarkup(msg Editable, markup *ReplyMarkup) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := make(map[string]string)
if chatID == 0 { // if inline message
params["inline_message_id"] = msgID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = msgID
}
if markup == nil {
// will delete reply markup
markup = &ReplyMarkup{}
}
processButtons(markup.InlineKeyboard)
data, _ := json.Marshal(markup)
params["reply_markup"] = string(data)
data, err := b.Raw("editMessageReplyMarkup", params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// EditCaption edits already sent photo caption with known recipient and message id.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
func (b *Bot) EditCaption(msg Editable, caption string, opts ...interface{}) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{
"caption": caption,
}
if chatID == 0 { // if inline message
params["inline_message_id"] = msgID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = msgID
}
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("editMessageCaption", params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// EditMedia edits already sent media with known recipient and message id.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
//
// Use cases:
//
// b.EditMedia(m, &tele.Photo{File: tele.FromDisk("chicken.jpg")})
// b.EditMedia(m, &tele.Video{File: tele.FromURL("http://video.mp4")})
func (b *Bot) EditMedia(msg Editable, media Inputtable, opts ...interface{}) (*Message, error) {
var (
repr string
file = media.MediaFile()
files = make(map[string]File)
thumb *Photo
thumbName = "thumb"
)
switch {
case file.InCloud():
repr = file.FileID
case file.FileURL != "":
repr = file.FileURL
case file.OnDisk() || file.FileReader != nil:
s := file.FileLocal
if file.FileReader != nil {
s = "0"
} else if s == thumbName {
thumbName = "thumb2"
}
repr = "attach://" + s
files[s] = *file
default:
return nil, fmt.Errorf("telebot: cannot edit media, it does not exist")
}
switch m := media.(type) {
case *Video:
thumb = m.Thumbnail
case *Audio:
thumb = m.Thumbnail
case *Document:
thumb = m.Thumbnail
case *Animation:
thumb = m.Thumbnail
}
msgID, chatID := msg.MessageSig()
params := make(map[string]string)
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
im := media.InputMedia()
im.Media = repr
if len(sendOpts.Entities) > 0 {
im.Entities = sendOpts.Entities
} else {
im.ParseMode = sendOpts.ParseMode
}
if thumb != nil {
im.Thumbnail = "attach://" + thumbName
files[thumbName] = *thumb.MediaFile()
}
data, _ := json.Marshal(im)
params["media"] = string(data)
if chatID == 0 { // if inline message
params["inline_message_id"] = msgID
} else {
params["chat_id"] = strconv.FormatInt(chatID, 10)
params["message_id"] = msgID
}
data, err := b.sendFiles("editMessageMedia", files, params)
if err != nil {
return nil, err
}
return extractMessage(data)
}
// Delete removes the message, including service messages.
// This function will panic upon nil Editable.
//
// - A message can only be deleted if it was sent less than 48 hours ago.
// - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
// - Bots can delete outgoing messages in private chats, groups, and supergroups.
// - Bots can delete incoming messages in private chats.
// - 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(msg Editable) error {
msgID, chatID := msg.MessageSig()
params := map[string]string{
"chat_id": strconv.FormatInt(chatID, 10),
"message_id": msgID,
}
_, err := b.Raw("deleteMessage", params)
return err
}
// DeleteMany deletes multiple messages simultaneously.
// If some of the specified messages can't be found, they are skipped.
func (b *Bot) DeleteMany(msgs []Editable) error {
params := make(map[string]string)
embedMessages(params, msgs)
_, err := b.Raw("deleteMessages", params)
return err
}
// 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 receives 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(to Recipient, action ChatAction, threadID ...int) error {
if to == nil {
return ErrBadRecipient
}
params := map[string]string{
"chat_id": to.Recipient(),
"action": string(action),
}
if len(threadID) > 0 {
params["message_thread_id"] = strconv.Itoa(threadID[0])
}
_, err := b.Raw("sendChatAction", params)
return err
}
// Ship replies to the shipping query, if you sent an invoice
// requesting an address and the parameter is_flexible was specified.
//
// Example:
//
// b.Ship(query) // OK
// b.Ship(query, opts...) // OK with options
// b.Ship(query, "Oops!") // Error message
func (b *Bot) Ship(query *ShippingQuery, what ...interface{}) error {
params := map[string]string{
"shipping_query_id": query.ID,
}
if len(what) == 0 {
params["ok"] = "true"
} else if s, ok := what[0].(string); ok {
params["ok"] = "false"
params["error_message"] = s
} else {
var opts []ShippingOption
for _, v := range what {
opt, ok := v.(ShippingOption)
if !ok {
return ErrUnsupportedWhat
}
opts = append(opts, opt)
}
params["ok"] = "true"
data, _ := json.Marshal(opts)
params["shipping_options"] = string(data)
}
_, err := b.Raw("answerShippingQuery", params)
return err
}
// Accept finalizes the deal.
func (b *Bot) Accept(query *PreCheckoutQuery, errorMessage ...string) error {
params := map[string]string{
"pre_checkout_query_id": query.ID,
}
if len(errorMessage) == 0 {
params["ok"] = "true"
} else {
params["ok"] = "False"
params["error_message"] = errorMessage[0]
}
_, err := b.Raw("answerPreCheckoutQuery", params)
return err
}
// 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:
//
// b.Respond(c)
// b.Respond(c, response)
func (b *Bot) Respond(c *Callback, resp ...*CallbackResponse) error {
var r *CallbackResponse
if resp == nil {
r = &CallbackResponse{}
} else {
r = resp[0]
}
r.CallbackID = c.ID
_, err := b.Raw("answerCallbackQuery", r)
return err
}
// 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, resp *QueryResponse) error {
resp.QueryID = query.ID
for _, result := range resp.Results {
result.Process(b)
}
_, err := b.Raw("answerInlineQuery", resp)
return err
}
// AnswerWebApp sends a response for a query from Web App and returns
// information about an inline message sent by a Web App on behalf of a user
func (b *Bot) AnswerWebApp(query *Query, r Result) (*WebAppMessage, error) {
r.Process(b)
params := map[string]interface{}{
"web_app_query_id": query.ID,
"result": r,
}
data, err := b.Raw("answerWebAppQuery", params)
if err != nil {
return nil, err
}
var resp struct {
Result *WebAppMessage
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, wrapError(err)
}
return resp.Result, err
}
// 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,
}
data, err := b.Raw("getFile", params)
if err != nil {
return File{}, err
}
var resp struct {
Result File
}
if err := json.Unmarshal(data, &resp); err != nil {
return File{}, wrapError(err)
}
return resp.Result, nil
}
// Download saves the file from Telegram servers locally.
// Maximum file size to download is 20 MB.
func (b *Bot) Download(file *File, localFilename string) error {
reader, err := b.File(file)
if err != nil {
return err
}
defer reader.Close()
out, err := os.Create(localFilename)
if err != nil {
return wrapError(err)
}
defer out.Close()
_, err = io.Copy(out, reader)
if err != nil {
return wrapError(err)
}
file.FileLocal = localFilename
return nil
}
// File gets a file from Telegram servers.
func (b *Bot) File(file *File) (io.ReadCloser, error) {
f, err := b.FileByID(file.FileID)
if err != nil {
return nil, err
}
url := b.URL + "/file/bot" + b.Token + "/" + f.FilePath
file.FilePath = f.FilePath // saving file path
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, wrapError(err)
}
resp, err := b.client.Do(req)
if err != nil {
return nil, wrapError(err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("telebot: expected status 200 but got %s", resp.Status)
}
return resp.Body, nil
}
// StopLiveLocation stops broadcasting live message location
// before Location.LivePeriod expires.
//
// It supports ReplyMarkup.
// This function will panic upon nil Editable.
//
// If the message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
func (b *Bot) StopLiveLocation(msg Editable, opts ...interface{}) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{
"chat_id": strconv.FormatInt(chatID, 10),
"message_id": msgID,
}
sendOpts := b.extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("stopMessageLiveLocation", params)