all repos — telegram-bot-api @ 9d3974d340f237d4b935ce3e1b512ce343868959

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