all repos — telegram-bot-api @ ce4fc988c916518bf64e8d02be6e19d89d745928

Golang bindings for the Telegram Bot API

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