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