all repos — telegram-bot-api @ 67c5217394180c54527b5fc2a756dac724f9ed04

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