all repos — telegram-bot-api @ ca09b25f8c79e3f045e121dd85bc7b79175f5f7e

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