bot_test.go (view raw)
1package tgbotapi
2
3import (
4 "io/ioutil"
5 "net/http"
6 "os"
7 "testing"
8 "time"
9)
10
11const (
12 TestToken = "153667468:AAHlSHlMqSt1f_uFmVRJbm5gntu2HI4WW8I"
13 ChatID = 76918703
14 Channel = "@tgbotapitest"
15 SupergroupChatID = -1001120141283
16 ReplyToMessageID = 35
17 ExistingPhotoFileID = "AgADAgADw6cxG4zHKAkr42N7RwEN3IFShCoABHQwXEtVks4EH2wBAAEC"
18 ExistingDocumentFileID = "BQADAgADOQADjMcoCcioX1GrDvp3Ag"
19 ExistingAudioFileID = "BQADAgADRgADjMcoCdXg3lSIN49lAg"
20 ExistingVoiceFileID = "AwADAgADWQADjMcoCeul6r_q52IyAg"
21 ExistingVideoFileID = "BAADAgADZgADjMcoCav432kYe0FRAg"
22 ExistingVideoNoteFileID = "DQADAgADdQAD70cQSUK41dLsRMqfAg"
23 ExistingStickerFileID = "BQADAgADcwADjMcoCbdl-6eB--YPAg"
24)
25
26func getBot(t *testing.T) (*BotAPI, error) {
27 bot, err := NewBotAPI(TestToken)
28 bot.Debug = true
29
30 if err != nil {
31 t.Error(err)
32 }
33
34 return bot, err
35}
36
37func TestNewBotAPI_notoken(t *testing.T) {
38 _, err := NewBotAPI("")
39
40 if err == nil {
41 t.Error(err)
42 }
43}
44
45func TestGetUpdates(t *testing.T) {
46 bot, _ := getBot(t)
47
48 u := NewUpdate(0)
49
50 _, err := bot.GetUpdates(u)
51
52 if err != nil {
53 t.Error(err)
54 }
55}
56
57func TestSendWithMessage(t *testing.T) {
58 bot, _ := getBot(t)
59
60 msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api")
61 msg.ParseMode = "markdown"
62 _, err := bot.Send(msg)
63
64 if err != nil {
65 t.Error(err)
66 }
67}
68
69func TestSendWithMessageReply(t *testing.T) {
70 bot, _ := getBot(t)
71
72 msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api")
73 msg.ReplyToMessageID = ReplyToMessageID
74 _, err := bot.Send(msg)
75
76 if err != nil {
77 t.Error(err)
78 }
79}
80
81func TestSendWithMessageForward(t *testing.T) {
82 bot, _ := getBot(t)
83
84 msg := NewForward(ChatID, ChatID, ReplyToMessageID)
85 _, err := bot.Send(msg)
86
87 if err != nil {
88 t.Error(err)
89 }
90}
91
92func TestSendWithNewPhoto(t *testing.T) {
93 bot, _ := getBot(t)
94
95 msg := NewPhoto(ChatID, "tests/image.jpg")
96 msg.Caption = "Test"
97 _, err := bot.Send(msg)
98
99 if err != nil {
100 t.Error(err)
101 }
102}
103
104func TestSendWithNewPhotoWithFileBytes(t *testing.T) {
105 bot, _ := getBot(t)
106
107 data, _ := ioutil.ReadFile("tests/image.jpg")
108 b := FileBytes{Name: "image.jpg", Bytes: data}
109
110 msg := NewPhoto(ChatID, b)
111 msg.Caption = "Test"
112 _, err := bot.Send(msg)
113
114 if err != nil {
115 t.Error(err)
116 }
117}
118
119func TestSendWithNewPhotoWithFileReader(t *testing.T) {
120 bot, _ := getBot(t)
121
122 f, _ := os.Open("tests/image.jpg")
123 reader := FileReader{Name: "image.jpg", Reader: f, Size: -1}
124
125 msg := NewPhoto(ChatID, reader)
126 msg.Caption = "Test"
127 _, err := bot.Send(msg)
128
129 if err != nil {
130 t.Error(err)
131 }
132}
133
134func TestSendWithNewPhotoReply(t *testing.T) {
135 bot, _ := getBot(t)
136
137 msg := NewPhoto(ChatID, "tests/image.jpg")
138 msg.ReplyToMessageID = ReplyToMessageID
139
140 _, err := bot.Send(msg)
141
142 if err != nil {
143 t.Error(err)
144 }
145}
146
147func TestSendNewPhotoToChannel(t *testing.T) {
148 bot, _ := getBot(t)
149
150 msg := NewPhotoToChannel(Channel, "tests/image.jpg")
151 msg.Caption = "Test"
152 _, err := bot.Send(msg)
153
154 if err != nil {
155 t.Error(err)
156 t.Fail()
157 }
158}
159
160func TestSendNewPhotoToChannelFileBytes(t *testing.T) {
161 bot, _ := getBot(t)
162
163 data, _ := ioutil.ReadFile("tests/image.jpg")
164 b := FileBytes{Name: "image.jpg", Bytes: data}
165
166 msg := NewPhotoToChannel(Channel, b)
167 msg.Caption = "Test"
168 _, err := bot.Send(msg)
169
170 if err != nil {
171 t.Error(err)
172 t.Fail()
173 }
174}
175
176func TestSendNewPhotoToChannelFileReader(t *testing.T) {
177 bot, _ := getBot(t)
178
179 f, _ := os.Open("tests/image.jpg")
180 reader := FileReader{Name: "image.jpg", Reader: f, Size: -1}
181
182 msg := NewPhotoToChannel(Channel, reader)
183 msg.Caption = "Test"
184 _, err := bot.Send(msg)
185
186 if err != nil {
187 t.Error(err)
188 t.Fail()
189 }
190}
191
192func TestSendWithExistingPhoto(t *testing.T) {
193 bot, _ := getBot(t)
194
195 msg := NewPhoto(ChatID, FileID(ExistingPhotoFileID))
196 msg.Caption = "Test"
197 _, err := bot.Send(msg)
198
199 if err != nil {
200 t.Error(err)
201 }
202}
203
204func TestSendWithNewDocument(t *testing.T) {
205 bot, _ := getBot(t)
206
207 msg := NewDocument(ChatID, "tests/image.jpg")
208 _, err := bot.Send(msg)
209
210 if err != nil {
211 t.Error(err)
212 }
213}
214
215func TestSendWithNewDocumentAndThumb(t *testing.T) {
216 bot, _ := getBot(t)
217
218 msg := NewDocument(ChatID, "tests/voice.ogg")
219 msg.Thumb = "tests/image.jpg"
220 _, err := bot.Send(msg)
221
222 if err != nil {
223 t.Error(err)
224 }
225}
226
227func TestSendWithExistingDocument(t *testing.T) {
228 bot, _ := getBot(t)
229
230 msg := NewDocument(ChatID, FileID(ExistingDocumentFileID))
231 _, err := bot.Send(msg)
232
233 if err != nil {
234 t.Error(err)
235 }
236}
237
238func TestSendWithNewAudio(t *testing.T) {
239 bot, _ := getBot(t)
240
241 msg := NewAudio(ChatID, "tests/audio.mp3")
242 msg.Title = "TEST"
243 msg.Duration = 10
244 msg.Performer = "TEST"
245 _, err := bot.Send(msg)
246
247 if err != nil {
248 t.Error(err)
249 }
250}
251
252func TestSendWithExistingAudio(t *testing.T) {
253 bot, _ := getBot(t)
254
255 msg := NewAudio(ChatID, FileID(ExistingAudioFileID))
256 msg.Title = "TEST"
257 msg.Duration = 10
258 msg.Performer = "TEST"
259
260 _, err := bot.Send(msg)
261
262 if err != nil {
263 t.Error(err)
264 }
265}
266
267func TestSendWithNewVoice(t *testing.T) {
268 bot, _ := getBot(t)
269
270 msg := NewVoice(ChatID, "tests/voice.ogg")
271 msg.Duration = 10
272 _, err := bot.Send(msg)
273
274 if err != nil {
275 t.Error(err)
276 }
277}
278
279func TestSendWithExistingVoice(t *testing.T) {
280 bot, _ := getBot(t)
281
282 msg := NewVoice(ChatID, FileID(ExistingVoiceFileID))
283 msg.Duration = 10
284 _, err := bot.Send(msg)
285
286 if err != nil {
287 t.Error(err)
288 }
289}
290
291func TestSendWithContact(t *testing.T) {
292 bot, _ := getBot(t)
293
294 contact := NewContact(ChatID, "5551234567", "Test")
295
296 if _, err := bot.Send(contact); err != nil {
297 t.Error(err)
298 }
299}
300
301func TestSendWithLocation(t *testing.T) {
302 bot, _ := getBot(t)
303
304 _, err := bot.Send(NewLocation(ChatID, 40, 40))
305
306 if err != nil {
307 t.Error(err)
308 }
309}
310
311func TestSendWithVenue(t *testing.T) {
312 bot, _ := getBot(t)
313
314 venue := NewVenue(ChatID, "A Test Location", "123 Test Street", 40, 40)
315
316 if _, err := bot.Send(venue); err != nil {
317 t.Error(err)
318 }
319}
320
321func TestSendWithNewVideo(t *testing.T) {
322 bot, _ := getBot(t)
323
324 msg := NewVideo(ChatID, "tests/video.mp4")
325 msg.Duration = 10
326 msg.Caption = "TEST"
327
328 _, err := bot.Send(msg)
329
330 if err != nil {
331 t.Error(err)
332 }
333}
334
335func TestSendWithExistingVideo(t *testing.T) {
336 bot, _ := getBot(t)
337
338 msg := NewVideo(ChatID, FileID(ExistingVideoFileID))
339 msg.Duration = 10
340 msg.Caption = "TEST"
341
342 _, err := bot.Send(msg)
343
344 if err != nil {
345 t.Error(err)
346 }
347}
348
349func TestSendWithNewVideoNote(t *testing.T) {
350 bot, _ := getBot(t)
351
352 msg := NewVideoNote(ChatID, 240, "tests/videonote.mp4")
353 msg.Duration = 10
354
355 _, err := bot.Send(msg)
356
357 if err != nil {
358 t.Error(err)
359 }
360}
361
362func TestSendWithExistingVideoNote(t *testing.T) {
363 bot, _ := getBot(t)
364
365 msg := NewVideoNote(ChatID, 240, FileID(ExistingVideoNoteFileID))
366 msg.Duration = 10
367
368 _, err := bot.Send(msg)
369
370 if err != nil {
371 t.Error(err)
372 }
373}
374
375func TestSendWithNewSticker(t *testing.T) {
376 bot, _ := getBot(t)
377
378 msg := NewSticker(ChatID, "tests/image.jpg")
379
380 _, err := bot.Send(msg)
381
382 if err != nil {
383 t.Error(err)
384 }
385}
386
387func TestSendWithExistingSticker(t *testing.T) {
388 bot, _ := getBot(t)
389
390 msg := NewSticker(ChatID, FileID(ExistingStickerFileID))
391
392 _, err := bot.Send(msg)
393
394 if err != nil {
395 t.Error(err)
396 }
397}
398
399func TestSendWithNewStickerAndKeyboardHide(t *testing.T) {
400 bot, _ := getBot(t)
401
402 msg := NewSticker(ChatID, "tests/image.jpg")
403 msg.ReplyMarkup = ReplyKeyboardRemove{
404 RemoveKeyboard: true,
405 Selective: false,
406 }
407 _, err := bot.Send(msg)
408
409 if err != nil {
410 t.Error(err)
411 }
412}
413
414func TestSendWithExistingStickerAndKeyboardHide(t *testing.T) {
415 bot, _ := getBot(t)
416
417 msg := NewSticker(ChatID, FileID(ExistingStickerFileID))
418 msg.ReplyMarkup = ReplyKeyboardRemove{
419 RemoveKeyboard: true,
420 Selective: false,
421 }
422
423 _, err := bot.Send(msg)
424
425 if err != nil {
426 t.Error(err)
427 }
428}
429
430func TestGetFile(t *testing.T) {
431 bot, _ := getBot(t)
432
433 file := FileConfig{
434 FileID: ExistingPhotoFileID,
435 }
436
437 _, err := bot.GetFile(file)
438
439 if err != nil {
440 t.Error(err)
441 }
442}
443
444func TestSendChatConfig(t *testing.T) {
445 bot, _ := getBot(t)
446
447 _, err := bot.Request(NewChatAction(ChatID, ChatTyping))
448
449 if err != nil {
450 t.Error(err)
451 }
452}
453
454func TestSendEditMessage(t *testing.T) {
455 bot, _ := getBot(t)
456
457 msg, err := bot.Send(NewMessage(ChatID, "Testing editing."))
458 if err != nil {
459 t.Error(err)
460 }
461
462 edit := EditMessageTextConfig{
463 BaseEdit: BaseEdit{
464 ChatID: ChatID,
465 MessageID: msg.MessageID,
466 },
467 Text: "Updated text.",
468 }
469
470 _, err = bot.Send(edit)
471 if err != nil {
472 t.Error(err)
473 }
474}
475
476func TestGetUserProfilePhotos(t *testing.T) {
477 bot, _ := getBot(t)
478
479 _, err := bot.GetUserProfilePhotos(NewUserProfilePhotos(ChatID))
480 if err != nil {
481 t.Error(err)
482 }
483}
484
485func TestSetWebhookWithCert(t *testing.T) {
486 bot, _ := getBot(t)
487
488 time.Sleep(time.Second * 2)
489
490 bot.Request(RemoveWebhookConfig{})
491
492 wh := NewWebhookWithCert("https://example.com/tgbotapi-test/"+bot.Token, "tests/cert.pem")
493 _, err := bot.Request(wh)
494 if err != nil {
495 t.Error(err)
496 }
497
498 _, err = bot.GetWebhookInfo()
499
500 if err != nil {
501 t.Error(err)
502 }
503
504 bot.Request(RemoveWebhookConfig{})
505}
506
507func TestSetWebhookWithoutCert(t *testing.T) {
508 bot, _ := getBot(t)
509
510 time.Sleep(time.Second * 2)
511
512 bot.Request(RemoveWebhookConfig{})
513
514 wh := NewWebhook("https://example.com/tgbotapi-test/" + bot.Token)
515 _, err := bot.Request(wh)
516 if err != nil {
517 t.Error(err)
518 }
519
520 info, err := bot.GetWebhookInfo()
521
522 if err != nil {
523 t.Error(err)
524 }
525 if info.MaxConnections == 0 {
526 t.Errorf("Expected maximum connections to be greater than 0")
527 }
528 if info.LastErrorDate != 0 {
529 t.Errorf("failed to set webhook: %s", info.LastErrorMessage)
530 }
531
532 bot.Request(RemoveWebhookConfig{})
533}
534
535func TestSendWithMediaGroup(t *testing.T) {
536 bot, _ := getBot(t)
537
538 cfg := NewMediaGroup(ChatID, []interface{}{
539 NewInputMediaPhoto(FileURL("https://i.imgur.com/unQLJIb.jpg")),
540 NewInputMediaPhoto("tests/image.jpg"),
541 NewInputMediaVideo("tests/video.mp4"),
542 })
543
544 messages, err := bot.SendMediaGroup(cfg)
545 if err != nil {
546 t.Error(err)
547 }
548
549 if messages == nil {
550 t.Error("No received messages")
551 }
552
553 if len(messages) != len(cfg.Media) {
554 t.Errorf("Different number of messages: %d", len(messages))
555 }
556}
557
558func ExampleNewBotAPI() {
559 bot, err := NewBotAPI("MyAwesomeBotToken")
560 if err != nil {
561 panic(err)
562 }
563
564 bot.Debug = true
565
566 log.Printf("Authorized on account %s", bot.Self.UserName)
567
568 u := NewUpdate(0)
569 u.Timeout = 60
570
571 updates := bot.GetUpdatesChan(u)
572
573 // Optional: wait for updates and clear them if you don't want to handle
574 // a large backlog of old messages
575 time.Sleep(time.Millisecond * 500)
576 updates.Clear()
577
578 for update := range updates {
579 if update.Message == nil {
580 continue
581 }
582
583 log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
584
585 msg := NewMessage(update.Message.Chat.ID, update.Message.Text)
586 msg.ReplyToMessageID = update.Message.MessageID
587
588 bot.Send(msg)
589 }
590}
591
592func ExampleNewWebhook() {
593 bot, err := NewBotAPI("MyAwesomeBotToken")
594 if err != nil {
595 panic(err)
596 }
597
598 bot.Debug = true
599
600 log.Printf("Authorized on account %s", bot.Self.UserName)
601
602 _, err = bot.Request(NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
603 if err != nil {
604 panic(err)
605 }
606
607 info, err := bot.GetWebhookInfo()
608
609 if err != nil {
610 panic(err)
611 }
612
613 if info.LastErrorDate != 0 {
614 log.Printf("failed to set webhook: %s", info.LastErrorMessage)
615 }
616
617 updates := bot.ListenForWebhook("/" + bot.Token)
618 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
619
620 for update := range updates {
621 log.Printf("%+v\n", update)
622 }
623}
624
625func ExampleWebhookHandler() {
626 bot, err := NewBotAPI("MyAwesomeBotToken")
627 if err != nil {
628 panic(err)
629 }
630
631 bot.Debug = true
632
633 log.Printf("Authorized on account %s", bot.Self.UserName)
634
635 _, err = bot.Request(NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
636 if err != nil {
637 panic(err)
638 }
639 info, err := bot.GetWebhookInfo()
640 if err != nil {
641 panic(err)
642 }
643 if info.LastErrorDate != 0 {
644 log.Printf("[Telegram callback failed]%s", info.LastErrorMessage)
645 }
646
647 http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) {
648 log.Printf("%+v\n", bot.HandleUpdate(w, r))
649 })
650
651 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
652}
653
654func ExampleInlineConfig() {
655 bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot
656 if err != nil {
657 panic(err)
658 }
659
660 log.Printf("Authorized on account %s", bot.Self.UserName)
661
662 u := NewUpdate(0)
663 u.Timeout = 60
664
665 updates := bot.GetUpdatesChan(u)
666
667 for update := range updates {
668 if update.InlineQuery == nil { // if no inline query, ignore it
669 continue
670 }
671
672 article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query)
673 article.Description = update.InlineQuery.Query
674
675 inlineConf := InlineConfig{
676 InlineQueryID: update.InlineQuery.ID,
677 IsPersonal: true,
678 CacheTime: 0,
679 Results: []interface{}{article},
680 }
681
682 if _, err := bot.Request(inlineConf); err != nil {
683 log.Println(err)
684 }
685 }
686}
687
688func TestDeleteMessage(t *testing.T) {
689 bot, _ := getBot(t)
690
691 msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api")
692 msg.ParseMode = "markdown"
693 message, _ := bot.Send(msg)
694
695 deleteMessageConfig := DeleteMessageConfig{
696 ChatID: message.Chat.ID,
697 MessageID: message.MessageID,
698 }
699 _, err := bot.Request(deleteMessageConfig)
700
701 if err != nil {
702 t.Error(err)
703 }
704}
705
706func TestPinChatMessage(t *testing.T) {
707 bot, _ := getBot(t)
708
709 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
710 msg.ParseMode = "markdown"
711 message, _ := bot.Send(msg)
712
713 pinChatMessageConfig := PinChatMessageConfig{
714 ChatID: message.Chat.ID,
715 MessageID: message.MessageID,
716 DisableNotification: false,
717 }
718 _, err := bot.Request(pinChatMessageConfig)
719
720 if err != nil {
721 t.Error(err)
722 }
723}
724
725func TestUnpinChatMessage(t *testing.T) {
726 bot, _ := getBot(t)
727
728 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
729 msg.ParseMode = "markdown"
730 message, _ := bot.Send(msg)
731
732 // We need pin message to unpin something
733 pinChatMessageConfig := PinChatMessageConfig{
734 ChatID: message.Chat.ID,
735 MessageID: message.MessageID,
736 DisableNotification: false,
737 }
738
739 if _, err := bot.Request(pinChatMessageConfig); err != nil {
740 t.Error(err)
741 }
742
743 unpinChatMessageConfig := UnpinChatMessageConfig{
744 ChatID: message.Chat.ID,
745 }
746
747 if _, err := bot.Request(unpinChatMessageConfig); err != nil {
748 t.Error(err)
749 }
750}
751
752func TestPolls(t *testing.T) {
753 bot, _ := getBot(t)
754
755 poll := NewPoll(SupergroupChatID, "Are polls working?", "Yes", "No")
756
757 msg, err := bot.Send(poll)
758 if err != nil {
759 t.Error(err)
760 }
761
762 result, err := bot.StopPoll(NewStopPoll(SupergroupChatID, msg.MessageID))
763 if err != nil {
764 t.Error(err)
765 }
766
767 if result.Question != "Are polls working?" {
768 t.Error("Poll question did not match")
769 }
770
771 if !result.IsClosed {
772 t.Error("Poll did not end")
773 }
774
775 if result.Options[0].Text != "Yes" || result.Options[0].VoterCount != 0 || result.Options[1].Text != "No" || result.Options[1].VoterCount != 0 {
776 t.Error("Poll options were incorrect")
777 }
778}
779
780func TestSendDice(t *testing.T) {
781 bot, _ := getBot(t)
782
783 dice := NewSendDice(ChatID)
784
785 msg, err := bot.Send(dice)
786 if err != nil {
787 t.Error("Unable to send dice roll")
788 }
789
790 if msg.Dice == nil {
791 t.Error("Dice roll was not received")
792 }
793}
794
795func TestSetCommands(t *testing.T) {
796 bot, _ := getBot(t)
797
798 setCommands := NewSetMyCommands(BotCommand{
799 Command: "test",
800 Description: "a test command",
801 })
802
803 if _, err := bot.Request(setCommands); err != nil {
804 t.Error("Unable to set commands")
805 }
806
807 commands, err := bot.GetMyCommands()
808 if err != nil {
809 t.Error("Unable to get commands")
810 }
811
812 if len(commands) != 1 {
813 t.Error("Incorrect number of commands returned")
814 }
815
816 if commands[0].Command != "test" || commands[0].Description != "a test command" {
817 t.Error("Commands were incorrectly set")
818 }
819}
820
821func TestEditMessageMedia(t *testing.T) {
822 bot, _ := getBot(t)
823
824 msg := NewPhoto(ChatID, "tests/image.jpg")
825 msg.Caption = "Test"
826 m, err := bot.Send(msg)
827
828 if err != nil {
829 t.Error(err)
830 }
831
832 edit := EditMessageMediaConfig{
833 BaseEdit: BaseEdit{
834 ChatID: ChatID,
835 MessageID: m.MessageID,
836 },
837 Media: NewInputMediaVideo("tests/video.mp4"),
838 }
839
840 _, err = bot.Request(edit)
841 if err != nil {
842 t.Error(err)
843 }
844}
845
846func TestPrepareInputMediaForParams(t *testing.T) {
847 media := []interface{}{
848 NewInputMediaPhoto("tests/image.jpg"),
849 NewInputMediaVideo(FileID("test")),
850 }
851
852 prepared := prepareInputMediaForParams(media)
853
854 if media[0].(InputMediaPhoto).Media != "tests/image.jpg" {
855 t.Error("Original media was changed")
856 }
857
858 if prepared[0].(InputMediaPhoto).Media != "attach://file-0" {
859 t.Error("New media was not replaced")
860 }
861
862 if prepared[1].(InputMediaVideo).Media != FileID("test") {
863 t.Error("Passthrough value was not the same")
864 }
865}