all repos — telegram-bot-api @ 53dec076c194332f6f38a84064ea6a43b9e53b69

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