all repos — telegram-bot-api @ 1059fc759ddd50b5380daa671bd34544302fd62d

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