-
Notifications
You must be signed in to change notification settings - Fork 9
/
bot.go
1354 lines (1047 loc) · 57.6 KB
/
bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package telego
import (
"encoding/json"
"errors"
"os"
cfg "github.com/SakoDroid/telego/v2/configs"
errs "github.com/SakoDroid/telego/v2/errors"
logger "github.com/SakoDroid/telego/v2/logger"
objs "github.com/SakoDroid/telego/v2/objects"
tba "github.com/SakoDroid/telego/v2/tba"
)
type Bot struct {
botCfg *cfg.BotConfigs
apiInterface *tba.BotAPIInterface
channelsMap map[string]map[string]*chan *objs.Update
interfaceUpdateChannel *chan *objs.Update
chatUpdateChannel *chan *objs.ChatUpdate
prcRoutineChannel *chan bool
ab *AdvancedBot
logger *logger.BotLogger
}
/*Run starts the bot. If the bot has already been started it returns an error.*/
func (bot *Bot) Run(autoPause bool) error {
logger.InitTheLogger(bot.botCfg)
if !bot.checkWebHook() {
bot.logger.GetRaw().Fatalln("Webhook check failed. See the logs for more info.")
}
go bot.startChatUpdateRoutine()
go bot.startUpdateProcessing()
cfg.Dump(bot.botCfg)
go bot.botCfg.StartCfgUpdateRoutine()
var err error
if bot.botCfg.Webhook {
wh := tba.Webhook{
Logger: bot.logger,
}
err = wh.StartWebHook(bot.botCfg, bot.apiInterface.GetUpdateParser())
} else {
err = bot.apiInterface.StartUpdateRoutine()
}
if err != nil {
return err
}
if autoPause {
ch := make(chan bool)
<-ch
}
return nil
}
func (bot *Bot) checkWebHook() bool {
wi, err := bot.apiInterface.GetWebhookInfo()
if err != nil {
bot.logger.GetRaw().Println(err)
return false
}
if wi.Result.URL == "" {
if bot.botCfg.Webhook {
err2 := bot.setWebhook()
if err2 != nil {
bot.logger.GetRaw().Println("Unable to set a new webhook.", err2)
return false
}
}
} else {
if bot.botCfg.Webhook {
if wi.Result.URL != bot.botCfg.WebHookConfigs.URL {
bot.logger.GetRaw().Println("A webhook is already set in the API server to this url :", wi.Result.URL, ". Deleting the webhook ...")
err2 := bot.deleteWebhook()
if err2 != nil {
bot.logger.GetRaw().Println("Unable to delete webhook.", err2)
return false
}
err3 := bot.setWebhook()
if err3 != nil {
bot.logger.GetRaw().Println("Unable to set webhook.", err3)
return false
}
}
} else {
bot.logger.GetRaw().Println("A webhook has been set.")
err2 := bot.deleteWebhook()
if err2 != nil {
bot.logger.GetRaw().Println("Unable to delete webhook.", err2)
return false
}
}
}
return true
}
/*Sets a new webhook*/
func (bot *Bot) setWebhook() error {
bot.logger.GetRaw().Println("Setting webhook ...")
whcfg := bot.botCfg.WebHookConfigs
var fl *os.File
if whcfg.SelfSigned {
var err2 error
fl, err2 = os.Open(whcfg.CertFile)
if err2 != nil {
return err2
}
}
res, err3 := bot.apiInterface.SetWebhook(whcfg.URL, whcfg.IP, whcfg.MaxConnections, whcfg.AllowedUpdates, whcfg.DropPendingUpdates, fl)
if err3 != nil {
return err3
}
if !res.Result {
return errors.New("unable to set webhook. API server returned false")
}
return nil
}
/*Deletes a webhook*/
func (bot *Bot) deleteWebhook() error {
bot.logger.GetRaw().Println("Deleting the webhook ...")
res, err2 := bot.apiInterface.DeleteWebhook(false)
if err2 != nil {
return err2
}
if !res.Result {
return errors.New("failed to delete the webhook. API server returned false")
}
return nil
}
// BlockUser blocks a user based on their ID and username.
func (bot *Bot) BlockUser(user *objs.User) {
for _, us := range bot.botCfg.BlockedUsers {
if us.UserID == user.Id {
return
}
}
us := cfg.BlockedUser{UserID: user.Id, UserName: user.Username}
bot.botCfg.BlockedUsers = append(bot.botCfg.BlockedUsers, us)
}
/*GetUpdateChannel returns the channel which new updates received from api server are pushed into.*/
func (bot *Bot) GetUpdateChannel() *chan *objs.Update {
return bot.channelsMap["global"]["all"]
}
/*
AddHandler adds a handler for a text message that matches the given regex pattern and chatType.
"pattern" is a regex pattern.
"chatType" must be "private","group","supergroup","channel" or "all". Any other value will cause the function to return an error.
*/
func (bot *Bot) AddHandler(pattern string, handler func(*objs.Update), chatTypes ...string) error {
if len(chatTypes) == 0 {
return errors.New("please specify a chat type")
}
for _, val := range chatTypes {
if val != "private" && val != "group" && val != "supergroup" && val != "channel" && val != "all" {
return errors.New("unknown chat type : " + val)
}
}
return bot.apiInterface.GetUpdateParser().AddHandler(pattern, handler, chatTypes...)
}
/*
GetMe returns the received informations about the bot from api server.
---------------------
Official telegarm doc :
A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.
*/
func (bot *Bot) GetMe() (*objs.Result[*objs.User], error) {
return bot.apiInterface.GetMe()
}
// GetBotManager returns a bot manager, a tool for manging personal information of the bot such as name and description.
func (bot *Bot) GetBotManager() *BotManager {
return &BotManager{bot: bot}
}
/*
SendMessage sens a text message to a chat (not channel, use SendMessageUN method for sending messages to channles) and returns the sent message on success
If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendMessage(chatId int, text, parseMode string, replyTo int, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendMessage(chatId, "", text, parseMode, nil, false, silent, false, protectContent, replyTo, 0, nil)
}
/*
SendMesssageUN sens a text message to a channel and returns the sent message on success
If you want to ignore "parseMode" pass empty string. To ignore replyTo pass 0.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendMessageUN(chatId, text, parseMode string, replyTo int, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendMessage(0, chatId, text, parseMode, nil, false, silent, false, protectContent, replyTo, 0, nil)
}
func (bot *Bot) PinChatMessage(chatIdInt int, chatIdString string, messageId int, disableNotification bool) (*objs.Result[bool], error) {
return bot.apiInterface.PinChatMessage(chatIdInt, chatIdString, messageId, disableNotification)
}
func (bot *Bot) UnpinChatMessage(chatIdInt int, chatIdString string, messageId int) (*objs.Result[bool], error) {
return bot.apiInterface.UnpinChatMessage(chatIdInt, chatIdString, messageId)
}
func (bot *Bot) UnpinAllChatMessages(chatIdInt int, chatIdString string) (*objs.Result[bool], error) {
return bot.apiInterface.UnpinAllChatMessages(chatIdInt, chatIdString)
}
func (bot *Bot) CreateChatInviteLink(chatIdInt int, chatIdString, name string, expireDate, memberLimit int, createsJoinRequest bool) (*objs.Result[*objs.ChatInviteLink], error) {
return bot.apiInterface.CreateChatInviteLink(chatIdInt, chatIdString, name, expireDate, memberLimit, createsJoinRequest)
}
func (bot *Bot) GetChatMember(chatIdInt int, chatIdString string, userId int) (*objs.Result[json.RawMessage], error) {
return bot.apiInterface.GetChatMember(chatIdInt, chatIdString, userId)
}
func (bot *Bot) BanChatMember(chatIdInt int, chatIdString string, userId, untilDate int, revokeMessages bool) (*objs.Result[bool], error) {
return bot.apiInterface.BanChatMember(chatIdInt, chatIdString, userId, untilDate, revokeMessages)
}
func (bot *Bot) UnbanChatMember(chatIdInt int, chatIdString string, userId int, onlyIfBanned bool) (*objs.Result[bool], error) {
return bot.apiInterface.UnbanChatMember(chatIdInt, chatIdString, userId, onlyIfBanned)
}
func (bot *Bot) SetMyCommands(commands []objs.BotCommand, scope objs.BotCommandScope, languageCode string) (*objs.Result[bool], error) {
return bot.apiInterface.SetMyCommands(commands, scope, languageCode)
}
/*
ForwardMessage returns a MessageForwarder which has several methods for forwarding a message
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) ForwardMessage(messageId int, disableNotif, protectContent bool) *MessageForwarder {
return &MessageForwarder{bot: bot, messageId: messageId, disableNotif: disableNotif, protectContent: protectContent}
}
/*
CopyMessage returns a MessageCopier which has several methods for copying a message
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) CopyMessage(messageId int, disableNotif, protectContent bool) *MessageCopier {
return &MessageCopier{bot: bot, messageId: messageId, disableNotif: disableNotif, protectContent: protectContent}
}
/*
SendPhoto returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to all types of chat except channels. To send a photo to a channel use "SendPhotoUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
*/
func (bot *Bot) SendPhoto(chatId, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: PHOTO, bot: bot, chatIdInt: chatId, replyTo: replyTo, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendPhotoUN returns a MediaSender which has several methods for sending a photo. This method is only used for sending a photo to a channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
*/
func (bot *Bot) SendPhotoUN(chatId string, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: PHOTO, bot: bot, chatIdInt: 0, username: chatId, replyTo: replyTo, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendVideo returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to all types of chat except channels. To send a video to a channel use "SendVideoUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendVideo(chatId int, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: VIDEO, bot: bot, chatIdInt: chatId, username: "", replyTo: replyTo, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendVideoUN returns a MediaSender which has several methods for sending a video. This method is only used for sending a video to a channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendVideoUN(chatId string, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: VIDEO, bot: bot, chatIdInt: 0, username: chatId, replyTo: replyTo, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendAudio returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to all types of chat except channels. To send a audio to a channel use "SendAudioUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
For sending voice messages, use the sendVoice method instead.
*/
func (bot *Bot) SendAudio(chatId, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: AUDIO, bot: bot, chatIdInt: chatId, username: "", replyTo: replyTo, caption: caption, parseMode: parseMode}
}
/*
SendAudioUN returns a MediaSender which has several methods for sending a audio. This method is only used for sending a audio to a channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
For sending voice messages, use the sendVoice method instead.
*/
func (bot *Bot) SendAudioUN(chatId string, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: AUDIO, bot: bot, chatIdInt: 0, username: chatId, replyTo: replyTo, caption: caption, parseMode: parseMode}
}
/*
SendDocument returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to all types of chat except channels. To send a audio to a channel use "SendDocumentUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendDocument(chatId, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: DOCUMENT, bot: bot, chatIdInt: chatId, username: "", replyTo: replyTo, caption: caption, parseMode: parseMode}
}
/*
SendDocumentUN returns a MediaSender which has several methods for sending a document. This method is only used for sending a document to a channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendDocumentUN(chatId string, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: DOCUMENT, bot: bot, chatIdInt: 0, username: chatId, replyTo: replyTo, caption: caption, parseMode: parseMode}
}
/*
SendAnimation returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to all types of chat except channels. To send a audio to a channel use "SendAnimationUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendAnimation(chatId int, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: ANIMATION, chatIdInt: chatId, username: "", replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendAnimationUN returns a MediaSender which has several methods for sending an animation. This method is only used for sending an animation to channels
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendAnimationUN(chatId string, replyTo int, caption, parseMode string, hasSpoiler bool) *MediaSender {
return &MediaSender{mediaType: ANIMATION, chatIdInt: 0, username: chatId, replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode, hasSpoiler: hasSpoiler}
}
/*
SendVoice returns a MediaSender which has several methods for sending a voice. This method is only used for sending a voice to all types of chat except channels. To send a voice to a channel use "SendVoiceUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendVoice(chatId int, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: VOICE, chatIdInt: chatId, username: "", replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode}
}
/*
SendVoiceUN returns an MediaSender which has several methods for sending a voice. This method is only used for sending a voice to channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
*/
func (bot *Bot) SendVoiceUN(chatId string, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: VOICE, chatIdInt: 0, username: chatId, replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode}
}
/*
SendVideoNote returns a MediaSender which has several methods for sending a video note. This method is only used for sending a video note to all types of chat except channels. To send a video note to a channel use "SendVideoNoteUN" method.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
*/
func (bot *Bot) SendVideoNote(chatId int, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: VIDEONOTE, chatIdInt: chatId, username: "", replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode}
}
/*
SendVideoNoteUN returns an MediaSender which has several methods for sending a video note. This method is only used for sending a video note to channels.
To ignore int arguments pass 0 and to ignore string arguments pass empty string ("")
---------------------------------
Official telegram doc :
As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
*/
func (bot *Bot) SendVideoNoteUN(chatId string, replyTo int, caption, parseMode string) *MediaSender {
return &MediaSender{mediaType: VIDEONOTE, chatIdInt: 0, username: chatId, replyTo: replyTo, bot: bot, caption: caption, parseMode: parseMode}
}
/*
CreateAlbum returns a MediaGroup for grouping media messages.
To ignore replyTo argument, pass 0.
*/
func (bot *Bot) CreateAlbum(replyTo int) *MediaGroup {
return &MediaGroup{replyTo: replyTo, bot: bot, media: make([]objs.InputMedia, 0), files: make([]*os.File, 0)}
}
/*
SendVenue sends a venue to all types of chat but channels. To send it to channels use "SendVenueUN" method.
---------------------------------
Official telegram doc :
Use this method to send information about a venue. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendVenue(chatId, replyTo int, latitude, longitude float32, title, address string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendVenue(
chatId, "", latitude, longitude, title, address, "", "", "", "", replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendVenueUN sends a venue to a channel.
---------------------------------
Official telegram doc :
Use this method to send information about a venue. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendVenueUN(chatId string, replyTo int, latitude, longitude float32, title, address string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendVenue(
0, chatId, latitude, longitude, title, address, "", "", "", "", replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendContact sends a contact to all types of chat but channels. To send it to channels use "SendContactUN" method.
---------------------------------
Official telegram doc :
Use this method to send phone contacts. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendContact(chatId, replyTo int, phoneNumber, firstName, lastName string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendContact(
chatId, "", phoneNumber, firstName, lastName, "", replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendContactUN sends a contact to a channel.
---------------------------------
Official telegram doc :
Use this method to send phone contacts. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendContactUN(chatId string, replyTo int, phoneNumber, firstName, lastName string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendContact(
0, chatId, phoneNumber, firstName, lastName, "", replyTo, 0, silent, false, protectContent, nil,
)
}
/*
CreatePoll creates a poll for all types of chat but channels. To create a poll for channels use "CreatePollForChannel" method.
The poll type can be "regular" or "quiz"
*/
func (bot *Bot) CreatePoll(chatId int, question, pollType string) (*Poll, error) {
if pollType != "quiz" && pollType != "regular" {
return nil, errors.New("poll type invalid : " + pollType)
}
return &Poll{bot: bot, pollType: pollType, chatIdInt: chatId, question: question, options: make([]string, 0)}, nil
}
/*
CreatePollForChannel creates a poll for a channel.
The poll type can be "regular" or "quiz"
*/
func (bot *Bot) CreatePollForChannel(chatId, question, pollType string) (*Poll, error) {
if pollType != "quiz" && pollType != "regular" {
return nil, errors.New("poll type invalid : " + pollType)
}
return &Poll{bot: bot, pollType: pollType, chatIdString: chatId, question: question, options: make([]string, 0)}, nil
}
/*
SendDice sends a dice message to all types of chat but channels. To send it to channels use "SendDiceUN" method.
Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.
---------------------------------
Official telegram doc :
Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendDice(chatId, replyTo int, emoji string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendDice(
chatId, "", emoji, replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendDiceUN sends a dice message to a channel.
Available emojies : “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”.
---------------------------------
Official telegram doc :
Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendDiceUN(chatId string, replyTo int, emoji string, silent, protectContent bool) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendDice(
0, chatId, emoji, replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendChatAction sends a chat action message to all types of chat but channels. To send it to channels use "SendChatActionUN" method.
Note : messageThreadId is unique identifier for the target message thread (supergroups only) which can be used for sending chat actions to a specific message thread or a forum topic.
---------------------------------
Official telegram doc :
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
action is the type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
*/
func (bot *Bot) SendChatAction(chatId, messageThreadId int, action string) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendChatAction(chatId, messageThreadId, "", action)
}
/*
SendChatActionUN sends a chat action message to a channel.
Note : messageThreadId is unique identifier for the target message thread (supergroups only) which can be used for sending chat actions to a specific message thread or a forum topic.
---------------------------------
Official telegram doc :
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
action is the type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
*/
func (bot *Bot) SendChatActionUN(chatId, action string, messageThreadId int) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendChatAction(0, messageThreadId, chatId, action)
}
/*
SendLocation sends a location (not live) to all types of chats but channels. To send it to channel use "SendLocationUN" method.
You can not use this methods to send a live location. To send a live location use AdvancedBot.
---------------------------------
Official telegram doc :
Use this method to send point on the map. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendLocation(chatId int, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendLocation(
chatId, "", latitude, longitude, accuracy, 0, 0, 0, replyTo, 0, silent, false, protectContent, nil,
)
}
/*
SendLocationUN sends a location (not live) to a channel.
You can not use this methods to send a live location. To send a live location use AdvancedBot.
---------------------------------
Official telegram doc :
Use this method to send point on the map. On success, the sent Message is returned.
If "silent" argument is true, the message will be sent without notification.
If "protectContent" argument is true, the message can't be forwarded or saved.
*/
func (bot *Bot) SendLocationUN(chatId string, silent, protectContent bool, latitude, longitude, accuracy float32, replyTo int) (*objs.Result[*objs.Message], error) {
return bot.apiInterface.SendLocation(
0, chatId, latitude, longitude, accuracy, 0, 0, 0, replyTo, 0, silent, false, protectContent, nil,
)
}
/*
GetUserProfilePhotos gets the given user profile photos.
"userId" argument is required. Other arguments are optinoal and to ignore them pass 0.
---------------------------------
Official telegram doc :
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
*/
func (bot *Bot) GetUserProfilePhotos(userId, offset, limit int) (*objs.Result[*objs.UserProfilePhotos], error) {
return bot.apiInterface.GetUserProfilePhotos(userId, offset, limit)
}
/*
GetFile gets a file from telegram server. If it is successful the File object is returned.
If "download option is true, the file will be saved into the given file and if the given file is nil file will be saved in the same name as it has been saved in telegram servers.
*/
func (bot *Bot) GetFile(fileId string, download bool, file *os.File) (*objs.File, error) {
res, err := bot.apiInterface.GetFile(fileId)
if err != nil {
return nil, err
}
if download {
err2 := bot.apiInterface.DownloadFile(res.Result, file)
if err2 != nil {
return res.Result, err2
}
}
return res.Result, nil
}
/*
GetChatManagerById creates and returns a ChatManager for groups and other chats witch an integer id.
To manage supergroups and channels which have usernames use "GetChatManagerByUsername".
*/
func (bot *Bot) GetChatManagerById(chatId int) *ChatManager {
return &ChatManager{bot: bot, chatIdInt: chatId, chatIdString: ""}
}
/*
GetChatManagerByUsrename creates and returns a ChatManager for supergroups and channels which have usernames
To manage groups and other chats witch an integer id use "GetChatManagerById".
*/
func (bot *Bot) GetChatManagerByUsrename(userName string) *ChatManager {
return &ChatManager{bot: bot, chatIdInt: 0, chatIdString: userName}
}
/*
AnswerCallbackQuery can be used to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
*/
func (bot *Bot) AnswerCallbackQuery(callbackQueryId, text string, showAlert bool) (*objs.Result[bool], error) {
return bot.apiInterface.AnswerCallbackQuery(callbackQueryId, text, "", showAlert, 0)
}
/*GetCommandManager returns a command manager which has several method for manaing bot commands.*/
func (bot *Bot) GetCommandManager() *CommandsManager {
return &CommandsManager{bot: bot}
}
/*
GetMsgEditor returns a MessageEditor for a chat with id which has several methods for editing messages.
To edit messages in a channel or a chat with username, use "GetMsgEditorWithUN"
*/
func (bot *Bot) GetMsgEditor(chatId int) *MessageEditor {
return &MessageEditor{bot: bot, chatIdInt: chatId}
}
/*GetMsgEditorWithUN returns a MessageEditor for a chat with username which has several methods for editing messages.*/
func (bot *Bot) GetMsgEditorWithUN(chatId string) *MessageEditor {
return &MessageEditor{bot: bot, chatIdInt: 0, chatIdString: chatId}
}
/*
SendSticker returns a MediaSender which has several methods for sending an sticker to all types of chats but channels.
To send it to a channel use "SendStickerWithUN".
--------------------
Official telegram doc :
Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned
*/
func (bot *Bot) SendSticker(chatId, replyTo int, eomji string) *MediaSender {
return &MediaSender{mediaType: STICKER, bot: bot, chatIdInt: chatId, username: "", replyTo: replyTo, stickerEmoji: eomji}
}
/*
SendStickerWithUn returns a MediaSender which has several methods for sending an sticker to channels.
--------------------
Official telegram doc :
Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned
*/
func (bot *Bot) SendStickerWithUn(chatId string, replyTo int, eomji string) *MediaSender {
return &MediaSender{mediaType: STICKER, bot: bot, chatIdInt: 0, username: chatId, replyTo: replyTo, stickerEmoji: eomji}
}
/*GetStickerSet returns an sticker set with the given name*/
func (bot *Bot) GetStickerSet(name string) (*StickerSet, error) {
res, err := bot.apiInterface.GetStickerSet(name)
if err != nil {
return nil, err
}
return &StickerSet{bot: bot, stickerSet: res.Result, name: name, created: true}, nil
}
/*UploadStickerFile can be used to upload a .PNG file with a sticker for later use in CreateNewStickerSet and AddStickerToSet methods (can be used multiple times). Returns the uploaded File on success.*/
func (bot *Bot) UploadStickerFile(userId int, stickerFormat string, eomjis, keywords []string, stickerFile *os.File) (*objs.Result[*objs.File], error) {
stat, err := stickerFile.Stat()
if err != nil {
return nil, err
}
return bot.apiInterface.UploadStickerFile(userId, stickerFormat, &objs.InputSticker{
Sticker: "attach://" + stat.Name(),
EmojiList: eomjis,
KeyWords: keywords,
}, stickerFile)
}
/*
GetStickerEditor returns a special object for editing stickers. Setting emoji list, keywords,mask postion and deleting the sticker.
stickerFileId : File identifier of the sticker
*/
func (bot *Bot) GetStickerEditor(stickerFileId string) *StickerEditor {
return &StickerEditor{bot: bot, stickerId: stickerFileId}
}
/*
Deprecated : This method has been completely deprecated. Use CreateStickerSet instead.
*/
func (bot *Bot) CreateNewStickerSet(userId int, name, title, pngStickerFileIdOrUrl string, pngStickerFile *os.File, tgsSticker *os.File, webmSticker *os.File, emojies string, containsMask bool, maskPosition *objs.MaskPosition) (*StickerSet, error) {
// var res *objs.Result[bool]
// var err error
// if tgsSticker == nil {
// if pngStickerFile == nil {
// if pngStickerFileIdOrUrl == "" {
// if webmSticker == nil {
// return nil, errors.New("wrong file id or url")
// } else {
// stat, er := webmSticker.Stat()
// if er != nil {
// return nil, er
// }
// res, err = bot.apiInterface.CreateNewStickerSet(
// userId, name, title, "", "", "attach://"+stat.Name(), emojies, containsMask, maskPosition, pngStickerFile,
// )
// }
// }
// res, err = bot.apiInterface.CreateNewStickerSet(
// userId, name, title, pngStickerFileIdOrUrl, "", "", emojies, containsMask, maskPosition, nil,
// )
// } else {
// stat, er := pngStickerFile.Stat()
// if er != nil {
// return nil, er
// }
// res, err = bot.apiInterface.CreateNewStickerSet(
// userId, name, title, "attach://"+stat.Name(), "", "", emojies, containsMask, maskPosition, pngStickerFile,
// )
// }
// } else {
// stat, er := tgsSticker.Stat()
// if er != nil {
// return nil, er
// }
// res, err = bot.apiInterface.CreateNewStickerSet(
// userId, name, title, "", "attach://"+stat.Name(), "", emojies, containsMask, maskPosition, tgsSticker,
// )
// }
// if err != nil {
// return nil, err
// }
// if !res.Result {
// return nil, errors.New("false returned from server")
// }
// out := &StickerSet{bot: bot, userId: userId, stickerSet: &objs.StickerSet{
// Name: name, Title: title, ContainsMask: containsMask, Stickers: make([]objs.Sticker, 0),
// }}
// out.update()
// return out, nil
return nil, &errs.MethodDeprecated{MethodName: "CreateNewStickerSet", Replacement: "CreateStickerSet"}
}
/*
CreateStickerSet returns an sticker set which can be used for creation and managing sticker sets. In this case, sticker set is locked and can be only used for creating the sticker set.
Arguments :
1. userId : User identifier of created sticker set owner
2. name : Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_<bot_username>". <bot_username> is case insensitive. 1-64 characters.
3. title : Sticker set title, 1-64 characters.
4. stickerFormat : Format of stickers in the set, must be one of “static”, “animated”, “video”
5. stickerType : Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created.
6. needsRepainting : Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only
*/
func (bot *Bot) CreateStickerSet(userId int, name, title, stickerFormat, stickerType string, needsRepainting bool) *StickerSet {
return &StickerSet{
bot: bot,
initStickers: make([]*objs.InputSticker, 0),
initFiles: make([]*os.File, 0),
userId: userId,
name: name,
title: title,
stickerFormat: stickerFormat,
stickerType: stickerType,
needsRepainting: needsRepainting,
created: false,
}
}
/*
AnswerInlineQuery returns an InlineQueryResponder which has several methods for answering an inline query or web app query.
To access more options use "AAsnwerInlineQuery" method in advanced bot.
--------------------------
Official telegram doc :
Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results per query are allowed.
*/
func (bot *Bot) AnswerInlineQuery(id string, cacheTime int) *InlineQueryResponder {
return &InlineQueryResponder{bot: bot, id: id, cacheTime: cacheTime, results: make([]objs.InlineQueryResult, 0)}
}
/*
AnswerWebAppQuery returns an InlineQueryResponder which has several methods for answering an inline query or web app query.
--------------------------
Official telegram doc :
Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
*/
func (bot *Bot) AnswerWebAppQuery(webAppQueryId string) *InlineQueryResponder {
return &InlineQueryResponder{id: webAppQueryId, isWebApp: true, results: make([]objs.InlineQueryResult, 0)}
}
/*
CreateInvoice returns an InvoiceSender which has several methods for creating and sending an invoice.
This method is suitable for sending this invoice to a chat that has an id, to send the invoice to channels use "CreateInvoiceUN" method.
To access more options, use "ACreateInvoice" method in advanced mode.
*/
func (bot *Bot) CreateInvoice(chatId int, title, description, payload, providerToken, currency string) *Invoice {
return &Invoice{
bot: bot, chatIdInt: chatId, chatIdString: "", title: title, description: description, providerToken: providerToken, payload: payload, currency: currency, prices: make([]objs.LabeledPrice, 0),
}
}
/*
CreateInvoiceUN returns an InvoiceSender which has several methods for creating and sending an invoice.
To access more options, use "ACreateInvoiceUN" method in advanced mode.
*/
func (bot *Bot) CreateInvoiceUN(chatId, title, description, payload, providerToken, currency string) *Invoice {
return &Invoice{
chatIdInt: 0, chatIdString: chatId, title: title, description: description, providerToken: providerToken, currency: currency, payload: payload, prices: make([]objs.LabeledPrice, 0),
}
}
/*
AnswerShippingQuery answers an incoming shipping query.
-----------------------
Official telegram doc :
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
"ok" : Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible).
"shippingOptions" : Required if ok is True. A JSON-serialized array of available shipping options.
"errorMessage" : Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
*/
func (bot *Bot) AnswerShippingQuery(shippingQueryId string, ok bool, shippingOptions []objs.ShippingOption, errorMessage string) (*objs.Result[bool], error) {
return bot.apiInterface.AnswerShippingQuery(shippingQueryId, ok, shippingOptions, errorMessage)
}
/*
AnswerPreCheckoutQuery answers a pre checkout query.
-----------------------
Official telegram doc :
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
"ok" : Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
"errorMessage" : Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
*/
func (bot *Bot) AnswerPreCheckoutQuery(shippingQueryId string, ok bool, errorMessage string) (*objs.Result[bool], error) {
return bot.apiInterface.AnswerPreCheckoutQuery(shippingQueryId, ok, errorMessage)
}
/*
SendGame sends a game to the chat.
**To access more options use "ASendGame" method in advanced mode.
-----------------------
Official telegram doc :