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 := NewWebhookWithCert("https://example.com/tgbotapi-test/"+bot.Token, "tests/cert.pem")
483 _, err := bot.Request(wh)
484 if err != nil {
485 t.Error(err)
486 }
487
488 _, err = bot.GetWebhookInfo()
489
490 if err != nil {
491 t.Error(err)
492 }
493
494 bot.Request(RemoveWebhookConfig{})
495}
496
497func TestSetWebhookWithoutCert(t *testing.T) {
498 bot, _ := getBot(t)
499
500 time.Sleep(time.Second * 2)
501
502 bot.Request(RemoveWebhookConfig{})
503
504 wh := NewWebhook("https://example.com/tgbotapi-test/" + bot.Token)
505 _, err := bot.Request(wh)
506 if err != nil {
507 t.Error(err)
508 }
509
510 info, err := bot.GetWebhookInfo()
511
512 if err != nil {
513 t.Error(err)
514 }
515 if info.MaxConnections == 0 {
516 t.Errorf("Expected maximum connections to be greater than 0")
517 }
518 if info.LastErrorDate != 0 {
519 t.Errorf("failed to set webhook: %s", info.LastErrorMessage)
520 }
521
522 bot.Request(RemoveWebhookConfig{})
523}
524
525func TestSendWithMediaGroup(t *testing.T) {
526 bot, _ := getBot(t)
527
528 cfg := NewMediaGroup(ChatID, []interface{}{
529 NewInputMediaPhoto("https://github.com/go-telegram-bot-api/telegram-bot-api/raw/0a3a1c8716c4cd8d26a262af9f12dcbab7f3f28c/tests/image.jpg"),
530 NewInputMediaVideo("https://github.com/go-telegram-bot-api/telegram-bot-api/raw/0a3a1c8716c4cd8d26a262af9f12dcbab7f3f28c/tests/video.mp4"),
531 })
532
533 messages, err := bot.SendMediaGroup(cfg)
534 if err != nil {
535 t.Error(err)
536 }
537
538 if messages == nil {
539 t.Error()
540 }
541
542 if len(messages) != 2 {
543 t.Error()
544 }
545}
546
547func ExampleNewBotAPI() {
548 bot, err := NewBotAPI("MyAwesomeBotToken")
549 if err != nil {
550 panic(err)
551 }
552
553 bot.Debug = true
554
555 log.Printf("Authorized on account %s", bot.Self.UserName)
556
557 u := NewUpdate(0)
558 u.Timeout = 60
559
560 updates := bot.GetUpdatesChan(u)
561
562 // Optional: wait for updates and clear them if you don't want to handle
563 // a large backlog of old messages
564 time.Sleep(time.Millisecond * 500)
565 updates.Clear()
566
567 for update := range updates {
568 if update.Message == nil {
569 continue
570 }
571
572 log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
573
574 msg := NewMessage(update.Message.Chat.ID, update.Message.Text)
575 msg.ReplyToMessageID = update.Message.MessageID
576
577 bot.Send(msg)
578 }
579}
580
581func ExampleNewWebhook() {
582 bot, err := NewBotAPI("MyAwesomeBotToken")
583 if err != nil {
584 panic(err)
585 }
586
587 bot.Debug = true
588
589 log.Printf("Authorized on account %s", bot.Self.UserName)
590
591 _, err = bot.Request(NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
592 if err != nil {
593 panic(err)
594 }
595
596 info, err := bot.GetWebhookInfo()
597
598 if err != nil {
599 panic(err)
600 }
601
602 if info.LastErrorDate != 0 {
603 log.Printf("failed to set webhook: %s", info.LastErrorMessage)
604 }
605
606 updates := bot.ListenForWebhook("/" + bot.Token)
607 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
608
609 for update := range updates {
610 log.Printf("%+v\n", update)
611 }
612}
613
614func ExampleWebhookHandler() {
615 bot, err := NewBotAPI("MyAwesomeBotToken")
616 if err != nil {
617 panic(err)
618 }
619
620 bot.Debug = true
621
622 log.Printf("Authorized on account %s", bot.Self.UserName)
623
624 _, err = bot.Request(NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
625 if err != nil {
626 panic(err)
627 }
628 info, err := bot.GetWebhookInfo()
629 if err != nil {
630 panic(err)
631 }
632 if info.LastErrorDate != 0 {
633 log.Printf("[Telegram callback failed]%s", info.LastErrorMessage)
634 }
635
636 http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) {
637 log.Printf("%+v\n", bot.HandleUpdate(w, r))
638 })
639
640 go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
641}
642
643func ExampleInlineConfig() {
644 bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot
645 if err != nil {
646 panic(err)
647 }
648
649 log.Printf("Authorized on account %s", bot.Self.UserName)
650
651 u := NewUpdate(0)
652 u.Timeout = 60
653
654 updates := bot.GetUpdatesChan(u)
655
656 for update := range updates {
657 if update.InlineQuery == nil { // if no inline query, ignore it
658 continue
659 }
660
661 article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query)
662 article.Description = update.InlineQuery.Query
663
664 inlineConf := InlineConfig{
665 InlineQueryID: update.InlineQuery.ID,
666 IsPersonal: true,
667 CacheTime: 0,
668 Results: []interface{}{article},
669 }
670
671 if _, err := bot.Request(inlineConf); err != nil {
672 log.Println(err)
673 }
674 }
675}
676
677func TestDeleteMessage(t *testing.T) {
678 bot, _ := getBot(t)
679
680 msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api")
681 msg.ParseMode = "markdown"
682 message, _ := bot.Send(msg)
683
684 deleteMessageConfig := DeleteMessageConfig{
685 ChatID: message.Chat.ID,
686 MessageID: message.MessageID,
687 }
688 _, err := bot.Request(deleteMessageConfig)
689
690 if err != nil {
691 t.Error(err)
692 }
693}
694
695func TestPinChatMessage(t *testing.T) {
696 bot, _ := getBot(t)
697
698 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
699 msg.ParseMode = "markdown"
700 message, _ := bot.Send(msg)
701
702 pinChatMessageConfig := PinChatMessageConfig{
703 ChatID: message.Chat.ID,
704 MessageID: message.MessageID,
705 DisableNotification: false,
706 }
707 _, err := bot.Request(pinChatMessageConfig)
708
709 if err != nil {
710 t.Error(err)
711 }
712}
713
714func TestUnpinChatMessage(t *testing.T) {
715 bot, _ := getBot(t)
716
717 msg := NewMessage(SupergroupChatID, "A test message from the test library in telegram-bot-api")
718 msg.ParseMode = "markdown"
719 message, _ := bot.Send(msg)
720
721 // We need pin message to unpin something
722 pinChatMessageConfig := PinChatMessageConfig{
723 ChatID: message.Chat.ID,
724 MessageID: message.MessageID,
725 DisableNotification: false,
726 }
727
728 if _, err := bot.Request(pinChatMessageConfig); err != nil {
729 t.Error(err)
730 }
731
732 unpinChatMessageConfig := UnpinChatMessageConfig{
733 ChatID: message.Chat.ID,
734 }
735
736 if _, err := bot.Request(unpinChatMessageConfig); err != nil {
737 t.Error(err)
738 }
739}
740
741func TestPolls(t *testing.T) {
742 bot, _ := getBot(t)
743
744 poll := NewPoll(SupergroupChatID, "Are polls working?", "Yes", "No")
745
746 msg, err := bot.Send(poll)
747 if err != nil {
748 t.Error(err)
749 }
750
751 result, err := bot.StopPoll(NewStopPoll(SupergroupChatID, msg.MessageID))
752 if err != nil {
753 t.Error(err)
754 }
755
756 if result.Question != "Are polls working?" {
757 t.Error("Poll question did not match")
758 }
759
760 if !result.IsClosed {
761 t.Error("Poll did not end")
762 }
763
764 if result.Options[0].Text != "Yes" || result.Options[0].VoterCount != 0 || result.Options[1].Text != "No" || result.Options[1].VoterCount != 0 {
765 t.Error("Poll options were incorrect")
766 }
767}
768
769func TestSendDice(t *testing.T) {
770 bot, _ := getBot(t)
771
772 dice := NewSendDice(ChatID)
773
774 msg, err := bot.Send(dice)
775 if err != nil {
776 t.Error("Unable to send dice roll")
777 }
778
779 if msg.Dice == nil {
780 t.Error("Dice roll was not received")
781 }
782}
783
784func TestSetCommands(t *testing.T) {
785 bot, _ := getBot(t)
786
787 setCommands := NewSetMyCommands(BotCommand{
788 Command: "test",
789 Description: "a test command",
790 })
791
792 if _, err := bot.Request(setCommands); err != nil {
793 t.Error("Unable to set commands")
794 }
795
796 commands, err := bot.GetMyCommands()
797 if err != nil {
798 t.Error("Unable to get commands")
799 }
800
801 if len(commands) != 1 {
802 t.Error("Incorrect number of commands returned")
803 }
804
805 if commands[0].Command != "test" || commands[0].Description != "a test command" {
806 t.Error("Commands were incorrectly set")
807 }
808}