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 := NewPhotoUpload(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 := NewPhotoUpload(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 := NewPhotoUpload(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 := NewPhotoUpload(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 := NewPhotoUploadToChannel(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 := NewPhotoUploadToChannel(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 := NewPhotoUploadToChannel(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 := NewPhotoShare(ChatID, 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 := NewDocumentUpload(ChatID, "tests/image.jpg")
208 _, err := bot.Send(msg)
209
210 if err != nil {
211 t.Error(err)
212 }
213}
214
215func TestSendWithExistingDocument(t *testing.T) {
216 bot, _ := getBot(t)
217
218 msg := NewDocumentShare(ChatID, ExistingDocumentFileID)
219 _, err := bot.Send(msg)
220
221 if err != nil {
222 t.Error(err)
223 }
224}
225
226func TestSendWithNewAudio(t *testing.T) {
227 bot, _ := getBot(t)
228
229 msg := NewAudioUpload(ChatID, "tests/audio.mp3")
230 msg.Title = "TEST"
231 msg.Duration = 10
232 msg.Performer = "TEST"
233 msg.MimeType = "audio/mpeg"
234 msg.FileSize = 688
235 _, err := bot.Send(msg)
236
237 if err != nil {
238 t.Error(err)
239 }
240}
241
242func TestSendWithExistingAudio(t *testing.T) {
243 bot, _ := getBot(t)
244
245 msg := NewAudioShare(ChatID, ExistingAudioFileID)
246 msg.Title = "TEST"
247 msg.Duration = 10
248 msg.Performer = "TEST"
249
250 _, err := bot.Send(msg)
251
252 if err != nil {
253 t.Error(err)
254 }
255}
256
257func TestSendWithNewVoice(t *testing.T) {
258 bot, _ := getBot(t)
259
260 msg := NewVoiceUpload(ChatID, "tests/voice.ogg")
261 msg.Duration = 10
262 _, err := bot.Send(msg)
263
264 if err != nil {
265 t.Error(err)
266 }
267}
268
269func TestSendWithExistingVoice(t *testing.T) {
270 bot, _ := getBot(t)
271
272 msg := NewVoiceShare(ChatID, ExistingVoiceFileID)
273 msg.Duration = 10
274 _, err := bot.Send(msg)
275
276 if err != nil {
277 t.Error(err)
278 }
279}
280
281func TestSendWithContact(t *testing.T) {
282 bot, _ := getBot(t)
283
284 contact := NewContact(ChatID, "5551234567", "Test")
285
286 if _, err := bot.Send(contact); err != nil {
287 t.Error(err)
288 }
289}
290
291func TestSendWithLocation(t *testing.T) {
292 bot, _ := getBot(t)
293
294 _, err := bot.Send(NewLocation(ChatID, 40, 40))
295
296 if err != nil {
297 t.Error(err)
298 }
299}
300
301func TestSendWithVenue(t *testing.T) {
302 bot, _ := getBot(t)
303
304 venue := NewVenue(ChatID, "A Test Location", "123 Test Street", 40, 40)
305
306 if _, err := bot.Send(venue); err != nil {
307 t.Error(err)
308 }
309}
310
311func TestSendWithNewVideo(t *testing.T) {
312 bot, _ := getBot(t)
313
314 msg := NewVideoUpload(ChatID, "tests/video.mp4")
315 msg.Duration = 10
316 msg.Caption = "TEST"
317
318 _, err := bot.Send(msg)
319
320 if err != nil {
321 t.Error(err)
322 }
323}
324
325func TestSendWithExistingVideo(t *testing.T) {
326 bot, _ := getBot(t)
327
328 msg := NewVideoShare(ChatID, ExistingVideoFileID)
329 msg.Duration = 10
330 msg.Caption = "TEST"
331
332 _, err := bot.Send(msg)
333
334 if err != nil {
335 t.Error(err)
336 }
337}
338
339func TestSendWithNewVideoNote(t *testing.T) {
340 bot, _ := getBot(t)
341
342 msg := NewVideoNoteUpload(ChatID, 240, "tests/videonote.mp4")
343 msg.Duration = 10
344
345 _, err := bot.Send(msg)
346
347 if err != nil {
348 t.Error(err)
349 }
350}
351
352func TestSendWithExistingVideoNote(t *testing.T) {
353 bot, _ := getBot(t)
354
355 msg := NewVideoNoteShare(ChatID, 240, ExistingVideoNoteFileID)
356 msg.Duration = 10
357
358 _, err := bot.Send(msg)
359
360 if err != nil {
361 t.Error(err)
362 }
363}
364
365func TestSendWithNewSticker(t *testing.T) {
366 bot, _ := getBot(t)
367
368 msg := NewStickerUpload(ChatID, "tests/image.jpg")
369
370 _, err := bot.Send(msg)
371
372 if err != nil {
373 t.Error(err)
374 }
375}
376
377func TestSendWithExistingSticker(t *testing.T) {
378 bot, _ := getBot(t)
379
380 msg := NewStickerShare(ChatID, ExistingStickerFileID)
381
382 _, err := bot.Send(msg)
383
384 if err != nil {
385 t.Error(err)
386 }
387}
388
389func TestSendWithNewStickerAndKeyboardHide(t *testing.T) {
390 bot, _ := getBot(t)
391
392 msg := NewStickerUpload(ChatID, "tests/image.jpg")
393 msg.ReplyMarkup = ReplyKeyboardRemove{
394 RemoveKeyboard: true,
395 Selective: false,
396 }
397 _, err := bot.Send(msg)
398
399 if err != nil {
400 t.Error(err)
401 }
402}
403
404func TestSendWithExistingStickerAndKeyboardHide(t *testing.T) {
405 bot, _ := getBot(t)
406
407 msg := NewStickerShare(ChatID, ExistingStickerFileID)
408 msg.ReplyMarkup = ReplyKeyboardRemove{
409 RemoveKeyboard: true,
410 Selective: false,
411 }
412
413 _, err := bot.Send(msg)
414
415 if err != nil {
416 t.Error(err)
417 }
418}
419
420func TestGetFile(t *testing.T) {
421 bot, _ := getBot(t)
422
423 file := FileConfig{
424 FileID: ExistingPhotoFileID,
425 }
426
427 _, err := bot.GetFile(file)
428
429 if err != nil {
430 t.Error(err)
431 }
432}
433
434func TestSendChatConfig(t *testing.T) {
435 bot, _ := getBot(t)
436
437 _, err := bot.Request(NewChatAction(ChatID, ChatTyping))
438
439 if err != nil {
440 t.Error(err)
441 }
442}
443
444func TestSendEditMessage(t *testing.T) {
445 bot, _ := getBot(t)
446
447 msg, err := bot.Send(NewMessage(ChatID, "Testing editing."))
448 if err != nil {
449 t.Error(err)
450 }
451
452 edit := EditMessageTextConfig{
453 BaseEdit: BaseEdit{
454 ChatID: ChatID,
455 MessageID: msg.MessageID,
456 },
457 Text: "Updated text.",
458 }
459
460 _, err = bot.Send(edit)
461 if err != nil {
462 t.Error(err)
463 }
464}
465
466func TestGetUserProfilePhotos(t *testing.T) {
467 bot, _ := getBot(t)
468
469 _, err := bot.GetUserProfilePhotos(NewUserProfilePhotos(ChatID))
470 if err != nil {
471 t.Error(err)
472 }
473}
474
475func TestSetWebhookWithCert(t *testing.T) {
476 bot, _ := getBot(t)
477
478 time.Sleep(time.Second * 2)
479
480 bot.Request(RemoveWebhookConfig{})
481
482 wh, err := NewWebhookWithCert("https://example.com/tgbotapi-test/"+bot.Token, "tests/cert.pem")
483
484 if err != nil {
485 t.Error(err)
486 }
487 _, err = bot.Request(wh)
488
489 if err != nil {
490 t.Error(err)
491 }
492
493 _, err = bot.GetWebhookInfo()
494
495 if err != nil {
496 t.Error(err)
497 }
498
499 bot.Request(RemoveWebhookConfig{})
500}
501
502func TestSetWebhookWithoutCert(t *testing.T) {
503 bot, _ := getBot(t)
504
505 time.Sleep(time.Second * 2)
506
507 bot.Request(RemoveWebhookConfig{})
508
509 wh, err := NewWebhook("https://example.com/tgbotapi-test/" + bot.Token)
510
511 if err != nil {
512 t.Error(err)
513 }
514
515 _, err = bot.Request(wh)
516
517 if err != nil {
518 t.Error(err)
519 }
520
521 info, err := bot.GetWebhookInfo()
522
523 if err != nil {
524 t.Error(err)
525 }
526 if info.MaxConnections == 0 {
527 t.Errorf("Expected maximum connections to be greater than 0")
528 }
529 if info.LastErrorDate != 0 {
530 t.Errorf("failed to set webhook: %s", info.LastErrorMessage)
531 }
532
533 bot.Request(RemoveWebhookConfig{})
534}
535
536func TestSendWithMediaGroup(t *testing.T) {
537 bot, _ := getBot(t)
538
539 cfg := NewMediaGroup(ChatID, []interface{}{
540 NewInputMediaPhoto("https://i.imgur.com/unQLJIb.jpg"),
541 NewInputMediaPhoto("https://i.imgur.com/J5qweNZ.jpg"),
542 NewInputMediaVideo("https://i.imgur.com/F6RmI24.mp4"),
543 })
544
545 messages, err := bot.SendMediaGroup(cfg)
546 if err != nil {
547 t.Error(err)
548 }
549
550 if messages == nil {
551 t.Error()
552 }
553
554 if len(messages) != 3 {
555 t.Error()
556 }
557}
558
559func ExampleNewBotAPI() {
560 bot, err := NewBotAPI("MyAwesomeBotToken")
561 if err != nil {
562 panic(err)
563 }
564
565 bot.Debug = true
566
567 log.Printf("Authorized on account %s", bot.Self.UserName)
568
569 u := NewUpdate(0)
570 u.Timeout = 60
571
572 updates := bot.GetUpdatesChan(u)
573
574 // Optional: wait for updates and clear them if you don't want to handle
575 // a large backlog of old messages
576 time.Sleep(time.Millisecond * 500)
577 updates.Clear()
578
579 for update := range updates {
580 if update.Message == nil {
581 continue
582 }
583
584 log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
585
586 msg := NewMessage(update.Message.Chat.ID, update.Message.Text)
587 msg.ReplyToMessageID = update.Message.MessageID
588
589 bot.Send(msg)
590 }
591}
592
593func ExampleNewWebhook() {
594 bot, err := NewBotAPI("MyAwesomeBotToken")
595 if err != nil {
596 panic(err)
597 }
598
599 bot.Debug = true
600
601 log.Printf("Authorized on account %s", bot.Self.UserName)
602
603 wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")
604
605 if err != nil {
606 panic(err)
607 }
608
609 _, err = bot.Request(wh)
610
611 if err != nil {
612 panic(err)
613 }
614
615 info, err := bot.GetWebhookInfo()
616
617 if err != nil {
618 panic(err)
619 }
620
621 if info.LastErrorDate != 0 {
622 log.Printf("failed to set webhook: %s", info.LastErrorMessage)
623 }
624
625 updates := bot.ListenForWebhook("/" + bot.Token)
626 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
627
628 for update := range updates {
629 log.Printf("%+v\n", update)
630 }
631}
632
633func ExampleWebhookHandler() {
634 bot, err := NewBotAPI("MyAwesomeBotToken")
635 if err != nil {
636 panic(err)
637 }
638
639 bot.Debug = true
640
641 log.Printf("Authorized on account %s", bot.Self.UserName)
642
643 wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")
644
645 if err != nil {
646 panic(err)
647 }
648
649 _, err = bot.Request(wh)
650 if err != nil {
651 panic(err)
652 }
653 info, err := bot.GetWebhookInfo()
654 if err != nil {
655 panic(err)
656 }
657 if info.LastErrorDate != 0 {
658 log.Printf("[Telegram callback failed]%s", info.LastErrorMessage)
659 }
660
661 http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) {
662 log.Printf("%+v\n", bot.HandleUpdate(w, r))
663 })
664
665 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
666}
667
668func ExampleInlineConfig() {
669 bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot
670 if err != nil {
671 panic(err)
672 }
673
674 log.Printf("Authorized on account %s", bot.Self.UserName)
675
676 u := NewUpdate(0)
677 u.Timeout = 60
678
679 updates := bot.GetUpdatesChan(u)
680
681 for update := range updates {
682 if update.InlineQuery == nil { // if no inline query, ignore it
683 continue
684 }
685
686 article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query)
687 article.Description = update.InlineQuery.Query
688
689 inlineConf := InlineConfig{
690 InlineQueryID: update.InlineQuery.ID,
691 IsPersonal: true,
692 CacheTime: 0,
693 Results: []interface{}{article},
694 }
695
696 if _, err := bot.Request(inlineConf); err != nil {
697 log.Println(err)
698 }
699 }
700}
701
702func TestDeleteMessage(t *testing.T) {
703 bot, _ := getBot(t)
704
705 msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api")
706 msg.ParseMode = "markdown"
707 message, _ := bot.Send(msg)
708
709 deleteMessageConfig := DeleteMessageConfig{
710 ChatID: message.Chat.ID,
711 MessageID: message.MessageID,
712 }
713 _, err := bot.Request(deleteMessageConfig)
714
715 if err != nil {
716 t.Error(err)
717 }
718}
719
720func TestPinChatMessage(t *testing.T) {
721 bot, _ := getBot(t)
722
723 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
724 msg.ParseMode = "markdown"
725 message, _ := bot.Send(msg)
726
727 pinChatMessageConfig := PinChatMessageConfig{
728 ChatID: message.Chat.ID,
729 MessageID: message.MessageID,
730 DisableNotification: false,
731 }
732 _, err := bot.Request(pinChatMessageConfig)
733
734 if err != nil {
735 t.Error(err)
736 }
737}
738
739func TestUnpinChatMessage(t *testing.T) {
740 bot, _ := getBot(t)
741
742 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
743 msg.ParseMode = "markdown"
744 message, _ := bot.Send(msg)
745
746 // We need pin message to unpin something
747 pinChatMessageConfig := PinChatMessageConfig{
748 ChatID: message.Chat.ID,
749 MessageID: message.MessageID,
750 DisableNotification: false,
751 }
752
753 if _, err := bot.Request(pinChatMessageConfig); err != nil {
754 t.Error(err)
755 }
756
757 unpinChatMessageConfig := UnpinChatMessageConfig{
758 ChatID: message.Chat.ID,
759 }
760
761 if _, err := bot.Request(unpinChatMessageConfig); err != nil {
762 t.Error(err)
763 }
764}
765
766func TestPolls(t *testing.T) {
767 bot, _ := getBot(t)
768
769 poll := NewPoll(SupergroupChatID, "Are polls working?", "Yes", "No")
770
771 msg, err := bot.Send(poll)
772 if err != nil {
773 t.Error(err)
774 }
775
776 result, err := bot.StopPoll(NewStopPoll(SupergroupChatID, msg.MessageID))
777 if err != nil {
778 t.Error(err)
779 }
780
781 if result.Question != "Are polls working?" {
782 t.Error("Poll question did not match")
783 }
784
785 if !result.IsClosed {
786 t.Error("Poll did not end")
787 }
788
789 if result.Options[0].Text != "Yes" || result.Options[0].VoterCount != 0 || result.Options[1].Text != "No" || result.Options[1].VoterCount != 0 {
790 t.Error("Poll options were incorrect")
791 }
792}
793
794func TestSendDice(t *testing.T) {
795 bot, _ := getBot(t)
796
797 dice := NewSendDice(ChatID)
798
799 msg, err := bot.Send(dice)
800 if err != nil {
801 t.Error("Unable to send dice roll")
802 }
803
804 if msg.Dice == nil {
805 t.Error("Dice roll was not received")
806 }
807}
808
809func TestSetCommands(t *testing.T) {
810 bot, _ := getBot(t)
811
812 setCommands := NewSetMyCommands(BotCommand{
813 Command: "test",
814 Description: "a test command",
815 })
816
817 if _, err := bot.Request(setCommands); err != nil {
818 t.Error("Unable to set commands")
819 }
820
821 commands, err := bot.GetMyCommands()
822 if err != nil {
823 t.Error("Unable to get commands")
824 }
825
826 if len(commands) != 1 {
827 t.Error("Incorrect number of commands returned")
828 }
829
830 if commands[0].Command != "test" || commands[0].Description != "a test command" {
831 t.Error("Commands were incorrectly set")
832 }
833}