forked from requilence/integram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bots.go
1740 lines (1434 loc) · 53.5 KB
/
bots.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 integram
import (
"encoding/gob"
"errors"
"fmt"
"math/rand"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"crypto/md5"
"github.com/kennygrant/sanitize"
"github.com/requilence/jobs"
tg "github.com/requilence/telegram-bot-api"
log "github.com/sirupsen/logrus"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const inlineButtonStateKeyword = '`'
const antiFloodSameMessageTimeout = 60
var botPerID = make(map[int64]*Bot)
var botPerService = make(map[string]*Bot)
var botTokenRE = regexp.MustCompile("([0-9]*):([0-9a-zA-Z_-]*)")
// Bot represents parsed auth data & API reference
type Bot struct {
// Bot Telegram user id
ID int64
// Bot Telegram username
Username string
// Bot Telegram token
token string
// Slice of services that using this bot (len=1 means that bot is dedicated for service – recommended case)
services []*Service
// Used to store long-pulling updates channel and survive panics
updatesChan <-chan tg.Update
API *tg.BotAPI
}
type Location struct {
Latitude float64
Longitude float64
}
// Message represent both outgoing and incoming message data
type Message struct {
ID bson.ObjectId `bson:"_id,omitempty"` // Internal unique BSON ID
EventID []string `bson:",omitempty"`
MsgID int `bson:",omitempty"` // Telegram Message ID. BotID+MsgID is unique
InlineMsgID string `bson:",omitempty"` // Telegram InlineMessage ID. ChatID+InlineMsgID is unique
BotID int64 `bson:",minsize"` // TG bot's ID on which behalf message is sending or receiving
FromID int64 `bson:",minsize"` // TG User's ID of sender. Equal to BotID in case of outgoinf message from bot
ChatID int64 `bson:",omitempty,minsize"` // Telegram chat's ID, equal to FromID in case of private message
BackupChatID int64 `bson:",omitempty,minsize"` // This chat will be used if chatid failed (bot not started or stopped or group deactivated)
ReplyToMsgID int `bson:",omitempty"` // If this message is reply, contains Telegram's Message ID of original message
Date time.Time
Text string `bson:"-"` // Exclude text field
TextHash string `bson:",omitempty"`
Location *Location `bson:",omitempty"`
AntiFlood bool `bson:",omitempty"`
Deleted bool `bson:",omitempty"` // f.e. admin can delete the message in supergroup and we can't longer edit or reply on it
OnCallbackAction string `bson:",omitempty"` // Func to call on inline button press
OnCallbackData []byte `bson:",omitempty"` // Args to send to this func
OnReplyAction string `bson:",omitempty"` // Func to call on message reply
OnReplyData []byte `bson:",omitempty"` // Args to send to this func
OnEditAction string `bson:",omitempty"` // Func to call on message edit
OnEditData []byte `bson:",omitempty"` // Args to send to this func
om *OutgoingMessage // Cache when retreiving original replied message
}
// IncomingMessage specifies data that available for incoming message
type IncomingMessage struct {
Message `bson:",inline"`
From User
Chat Chat
ForwardFrom *User
ForwardDate time.Time
ForwardFromMessageID int64
ReplyToMessage *Message `bson:"-"`
ForwardFromChat *Chat `json:"forward_from_chat"` // optional
EditDate int `json:"edit_date"` // optional
Entities *[]tg.MessageEntity `json:"entities"` // optional
Audio *tg.Audio `json:"audio"` // optional
Document *tg.Document `json:"document"` // optional
Photo *[]tg.PhotoSize `json:"photo"` // optional
Sticker *tg.Sticker `json:"sticker"` // optional
Video *tg.Video `json:"video"` // optional
Voice *tg.Voice `json:"voice"` // optional
Caption string `json:"caption"` // optional
Contact *tg.Contact `json:"contact"` // optional
Location *tg.Location `json:"location"` // optional
Venue *tg.Venue `json:"venue"` // optional
NewChatMembers []*User `json:"new_chat_members"` // optional
LeftChatMember *User `json:"left_chat_member"` // optional
NewChatTitle string `json:"new_chat_title"` // optional
NewChatPhoto *[]tg.PhotoSize `json:"new_chat_photo"` // optional
DeleteChatPhoto bool `json:"delete_chat_photo"` // optional
GroupChatCreated bool `json:"group_chat_created"` // optional
SuperGroupChatCreated bool `json:"supergroup_chat_created"` // optional
ChannelChatCreated bool `json:"channel_chat_created"` // optional
MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional
MigrateFromChatID int64 `json:"migrate_from_chat_id"` // optional
PinnedMessage *Message `json:"pinned_message"` // optional
// Need to update message in DB. Used f.e. when you set the eventID for outgoing message
needToUpdateDB bool
}
// OutgoingMessage specispecifiesfy data of performing or performed outgoing message
type OutgoingMessage struct {
Message `bson:",inline"`
KeyboardHide bool `bson:",omitempty"`
ResizeKeyboard bool `bson:",omitempty"`
KeyboardMarkup Keyboard `bson:"-"`
InlineKeyboardMarkup InlineKeyboard `bson:",omitempty"`
Keyboard bool `bson:",omitempty"`
ParseMode string `bson:",omitempty"`
OneTimeKeyboard bool `bson:",omitempty"`
Selective bool `bson:",omitempty"`
ForceReply bool `bson:",omitempty"` // in the private dialog assume user's message as the reply for the last message sent by the bot if bot's message has Reply handler and ForceReply set
WebPreview bool `bson:",omitempty"`
Silent bool `bson:",omitempty"`
FilePath string `bson:",omitempty"`
FileName string `bson:",omitempty"`
FileType string `bson:",omitempty"`
FileRemoveAfter bool `bson:",omitempty"`
SendAfter *time.Time `bson:",omitempty"`
processed bool
ctx *Context
}
// Keyboard is a Shorthand for [][]Button
type Keyboard []Buttons
// Buttons is a Shorthand for []Button
type Buttons []Button
// InlineKeyboard contains the data to create the Inline keyboard for Telegram and store it in DB
type InlineKeyboard struct {
Buttons []InlineButtons // You must specify at least 1 InlineButton in slice
FixedWidth bool `bson:",omitempty"` // will add right padding to match all buttons text width
State string // determine the current keyboard's state. Useful to change the behavior for branch cases and make it little thread safe while it is using by several users
MaxRows int `bson:",omitempty"` // Will automatically add next/prev buttons. Zero means no limit
RowOffset int `bson:",omitempty"` // Current offset when using MaxRows
}
// InlineButtons is a Shorthand for []InlineButton
type InlineButtons []InlineButton
// Button contains the data to create Keyboard
type Button struct {
Data string // data is stored in the DB. May be collisions if button text is not unique per keyboard
Text string // should be unique per keyboard
}
// InlineButton contains the data to create InlineKeyboard
// One of URL, Data, SwitchInlineQuery must be specified
// If more than one specified the first in order of (URL, Data, SwitchInlineQuery) will be used
type InlineButton struct {
Text string
State int
URL string `bson:",omitempty"`
Data string `bson:",omitempty"` // maximum 64 bytes
SwitchInlineQuery string `bson:",omitempty"` //
SwitchInlineQueryCurrentChat string `bson:",omitempty"`
OutOfPagination bool `bson:",omitempty" json:"-"` // Only for the single button in first or last row. Use together with InlineKeyboard.MaxRows – for buttons outside of pagination list
}
type ChatConfig struct {
tg.ChatConfig
}
type ChatConfigWithUser struct {
tg.ChatConfigWithUser
}
// InlineKeyboardMarkup allow to generate TG and DB data from different states - (InlineButtons, []InlineButtons and InlineKeyboard)
type InlineKeyboardMarkup interface {
tg() [][]tg.InlineKeyboardButton
Keyboard() InlineKeyboard
}
// KeyboardMarkup allow to generate TG and DB data from different states - (Buttons and Keyboard)
type KeyboardMarkup interface {
tg() [][]tg.KeyboardButton
Keyboard() Keyboard
db() map[string]string
}
func (c *Bot) tgToken() string {
return fmt.Sprintf("%d:%s", c.ID, c.token)
}
// PMURL return URL to private messaging with the bot like https://telegram.me/trello_bot?start=param
func (c *Bot) PMURL(param string) string {
if param == "" {
return fmt.Sprintf("https://telegram.me/%v", c.Username)
}
return fmt.Sprintf("https://telegram.me/%v?start=%v", c.Username, param)
}
func (c *Bot) webhookURL() *url.URL {
url, _ := url.Parse(fmt.Sprintf("%s/tg/%d/%s", Config.BaseURL, c.ID, compactHash(c.token)))
return url
}
func (service *Service) registerBot(fullTokenWithID string) error {
s := botTokenRE.FindStringSubmatch(fullTokenWithID)
if len(s) < 3 {
return errors.New("can't parse token")
}
id, err := strconv.ParseInt(s[1], 10, 64)
if err != nil {
return err
}
if b, exists := botPerID[id]; !exists || b.token != s[2] {
// bot with this ID not exists or the bot's token changed
bot := Bot{ID: id, token: s[2], services: []*Service{service}}
botPerID[id] = &bot
token := bot.tgToken()
bot.API, err = tg.NewBotAPI(token)
if err != nil {
log.WithError(err).WithField("token", token).Error("NewBotAPI returned error")
return err
}
bot.Username = bot.API.Self.UserName
} else {
b := botPerID[id]
serviceAlreadyExists := false
for _, s := range b.services {
if s.Name == service.Name {
serviceAlreadyExists = true
break
}
}
if !serviceAlreadyExists {
b.services = append(b.services, service)
}
botPerID[id] = b
}
botPerService[service.Name] = botPerID[id]
return nil
}
// Compare if InlineKeyboard.tg() of 2 keyboards are equal
func whetherTGInlineKeyboardsAreEqual(tg1, tg2 [][]tg.InlineKeyboardButton) bool {
if len(tg1) != len(tg2) {
return false
}
for i := 0; i < len(tg1); i++ {
if len(tg1[i]) != len(tg2[i]) {
return false
}
for j := 0; j < len(tg1[i]); j++ {
b1 := tg1[i][j]
b2 := tg2[i][j]
if b1.Text != b2.Text ||
b1.CallbackData == nil && b2.CallbackData != nil ||
b1.CallbackData != nil && b2.CallbackData == nil ||
b1.CallbackData != nil && b2.CallbackData != nil && *b1.CallbackData != *b2.CallbackData ||
b1.URL == nil && b2.URL != nil ||
b1.URL != nil && b2.URL == nil ||
b1.URL != nil && b2.URL != nil && *b1.URL != *b2.URL ||
b1.SwitchInlineQuery == nil && b2.SwitchInlineQuery != nil ||
b1.SwitchInlineQuery != nil && b2.SwitchInlineQuery == nil ||
b1.SwitchInlineQuery != nil && b2.SwitchInlineQuery != nil && *b1.SwitchInlineQuery != *b2.SwitchInlineQuery ||
b1.SwitchInlineQueryCurrentChat == nil && b2.SwitchInlineQueryCurrentChat != nil ||
b1.SwitchInlineQueryCurrentChat != nil && b2.SwitchInlineQueryCurrentChat == nil ||
b1.SwitchInlineQueryCurrentChat != nil && b2.SwitchInlineQueryCurrentChat != nil && *b1.SwitchInlineQueryCurrentChat != *b2.SwitchInlineQueryCurrentChat {
return false
}
}
}
return true
}
// Find the InlineButton in Keyboard by the Data
func (keyboard *InlineKeyboard) Find(buttonData string) (i, j int, but *InlineButton) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
return i, j, &button
}
}
}
return -1, -1, nil
}
// EditText find the InlineButton in Keyboard by the Data and change the text of that button
func (keyboard *InlineKeyboard) EditText(buttonData string, newText string) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
keyboard.Buttons[i][j].Text = newText
return
}
}
}
}
// AddPMSwitchButton add the button to switch to PM as a first row in the InlineKeyboard
func (keyboard *InlineKeyboard) AddPMSwitchButton(b *Bot, text string, param string) {
if len(keyboard.Buttons) > 0 && len(keyboard.Buttons[0]) > 0 && keyboard.Buttons[0][0].Text == text {
return
}
keyboard.PrependRows(InlineButtons{InlineButton{Text: text, URL: b.PMURL(param)}})
}
// AppendRows adds 1 or more InlineButtons (rows) to the end of InlineKeyboard
func (keyboard *InlineKeyboard) AppendRows(buttons ...InlineButtons) {
keyboard.Buttons = append(keyboard.Buttons, buttons...)
}
// PrependRows adds 1 or more InlineButtons (rows) to the begin of InlineKeyboard
func (keyboard *InlineKeyboard) PrependRows(buttons ...InlineButtons) {
keyboard.Buttons = append(buttons, keyboard.Buttons...)
}
// Append adds 1 or more InlineButton (column) to the end of InlineButtons(row)
func (buttons *InlineButtons) Append(data string, text string) {
if len(data) > 64 {
log.WithField("text", text).Errorf("InlineButton data '%s' extends 64 bytes limit", data)
}
*buttons = append(*buttons, InlineButton{Data: data, Text: text})
}
// Prepend adds 1 or more InlineButton (column) to the begin of InlineButtons(row)
func (buttons *InlineButtons) Prepend(data string, text string) {
if len(data) > 64 {
log.WithField("text", text).Errorf("InlineButton data '%s' extends 64 bytes limit", data)
}
*buttons = append([]InlineButton{{Data: data, Text: text}}, *buttons...)
}
// AppendWithState add the InlineButton with state to the end of InlineButtons(row)
// Useful for checkbox or to revert the action
func (buttons *InlineButtons) AppendWithState(state int, data string, text string) {
if len(data) > 64 {
log.WithField("text", text).Errorf("InlineButton data '%s' extends 64 bytes limit", data)
}
if state > 9 || state < 0 {
log.WithField("data", data).WithField("text", text).Errorf("AppendWithState – state must be [0-9], %d received", state)
}
*buttons = append(*buttons, InlineButton{Data: data, Text: text, State: state})
}
// PrependWithState add the InlineButton with state to the begin of InlineButtons(row)
// Useful for checkbox or to revert the action
func (buttons *InlineButtons) PrependWithState(state int, data string, text string) {
if len(data) > 64 {
log.WithField("text", text).Errorf("InlineButton data '%s' extends 64 bytes limit", data)
}
if state > 9 || state < 0 {
log.WithField("data", data).WithField("text", text).Errorf("PrependWithState – state must be [0-9], %d received", state)
}
*buttons = append([]InlineButton{{Data: data, Text: text, State: state}}, *buttons...)
}
// AddURL adds InlineButton with URL to the end of InlineButtons(row)
func (buttons *InlineButtons) AddURL(url string, text string) {
*buttons = append(*buttons, InlineButton{URL: url, Text: text})
}
// Markup generate InlineKeyboard from InlineButtons ([]Button), chunking buttons by columns number, and specifying current keyboard state
// Keyboard state useful for nested levels to determine current position
func (buttons *InlineButtons) Markup(columns int, state string) InlineKeyboard {
keyboard := InlineKeyboard{}
col := 0
row := InlineButtons{}
len := len(*buttons)
for i, button := range *buttons {
row = append(row, button)
col++
if col == columns || i == (len-1) {
col = 0
keyboard.AppendRows(row)
row = InlineButtons{}
}
}
keyboard.State = state
return keyboard
}
// Keyboard generates inline keyboard from inline keyboard :-D
func (keyboard InlineKeyboard) Keyboard() InlineKeyboard {
return keyboard
}
// Keyboard generates inline keyboard with 1 button
func (button InlineButton) Keyboard() InlineKeyboard {
return InlineKeyboard{Buttons: []InlineButtons{{button}}}
}
// Keyboard generates inline keyboard with 1 column
func (buttons InlineButtons) Keyboard() InlineKeyboard {
return buttons.Markup(1, "")
}
func (button InlineButton) tg() [][]tg.InlineKeyboardButton {
return button.Keyboard().tg()
}
func (buttons InlineButtons) tg() [][]tg.InlineKeyboardButton {
return buttons.Keyboard().tg()
}
func stringPointer(s string) *string {
return &s
}
func (keyboard InlineKeyboard) tg() [][]tg.InlineKeyboardButton {
res := make([][]tg.InlineKeyboardButton, len(keyboard.Buttons))
maxWidth := 0
if keyboard.FixedWidth {
for _, columns := range keyboard.Buttons {
for _, button := range columns {
if len(button.Text) > maxWidth {
maxWidth = len(button.Text)
}
}
}
}
for r, columns := range keyboard.Buttons {
res[r] = make([]tg.InlineKeyboardButton, len(keyboard.Buttons[r]))
c := 0
for _, button := range columns {
if keyboard.FixedWidth {
button.Text = button.Text + strings.Repeat(" ", maxWidth-len(button.Text))
}
if button.State != 0 {
button.Data = fmt.Sprintf("%c%d%s", inlineButtonStateKeyword, button.State, button.Data)
}
if button.URL != "" {
res[r][c] = tg.InlineKeyboardButton{Text: button.Text, URL: stringPointer(button.URL)}
} else if button.Data != "" {
res[r][c] = tg.InlineKeyboardButton{Text: button.Text, CallbackData: stringPointer(button.Data)}
} else if button.SwitchInlineQueryCurrentChat != "" {
res[r][c] = tg.InlineKeyboardButton{Text: button.Text, SwitchInlineQueryCurrentChat: stringPointer(button.SwitchInlineQueryCurrentChat)}
} else {
res[r][c] = tg.InlineKeyboardButton{Text: button.Text, SwitchInlineQuery: stringPointer(button.SwitchInlineQuery)}
}
c++
}
}
return res
}
// AddRows adds 1 or more Buttons (rows) to the end of InlineKeyboard
func (keyboard *Keyboard) AddRows(buttons ...Buttons) {
*keyboard = append(*keyboard, buttons...)
}
// Prepend adds InlineButton with URL to the begin of InlineButtons(row)
func (buttons *Buttons) Prepend(data string, text string) {
*buttons = append([]Button{{Data: data, Text: text}}, *buttons...)
}
// Append adds Button with URL to the end of Buttons(row)
func (buttons *Buttons) Append(data string, text string) {
*buttons = append(*buttons, Button{Data: data, Text: text})
}
// InlineButtons converts Buttons to InlineButtons
// useful with universal methods that create keyboard (f.e. settigns) for both usual and inline keyboard
func (buttons *Buttons) InlineButtons() InlineButtons {
row := InlineButtons{}
for _, button := range *buttons {
row.Append(button.Data, button.Text)
}
return row
}
// Markup generate Keyboard from Buttons ([]Button), chunking buttons by columns number
func (buttons *Buttons) Markup(columns int) Keyboard {
keyboard := Keyboard{}
col := 0
row := Buttons{}
len := len(*buttons)
for i, button := range *buttons {
row.Append(button.Data, button.Text)
col++
if col == columns || i == (len-1) {
col = 0
keyboard.AddRows(row)
row = Buttons{}
}
}
return keyboard
}
// Keyboard is generating Keyboard with 1 column
func (buttons Buttons) Keyboard() Keyboard {
return buttons.Markup(1)
}
func (buttons Buttons) tg() [][]tg.KeyboardButton {
return buttons.Keyboard().tg()
}
func (buttons Buttons) db() map[string]string {
res := make(map[string]string)
for _, button := range buttons {
res[checksumString(button.Text)] = button.Data
}
return res
}
// Keyboard generates keyboard from 1 button
func (button Button) Keyboard() Keyboard {
btns := Buttons{button}
return btns.Keyboard()
}
func (button Button) tg() [][]tg.KeyboardButton {
btns := Buttons{button}
return btns.Keyboard().tg()
}
func (button Button) db() map[string]string {
res := make(map[string]string)
res[checksumString(button.Text)] = button.Data
return res
}
func (keyboard Keyboard) db() map[string]string {
res := make(map[string]string)
for _, columns := range keyboard {
for _, button := range columns {
res[checksumString(button.Text)] = button.Data
}
}
return res
}
// Keyboard generate keyboard for keyboard – just to match the KeyboardMarkup interface
func (keyboard Keyboard) Keyboard() Keyboard {
return keyboard
}
func (keyboard Keyboard) tg() [][]tg.KeyboardButton {
res := make([][]tg.KeyboardButton, len(keyboard))
for r, columns := range keyboard {
res[r] = make([]tg.KeyboardButton, len(keyboard[r]))
c := 0
for _, button := range columns {
res[r][c] = tg.KeyboardButton{Text: button.Text}
c++
}
}
return res
}
// FindMessageByEventID find message by event id
func (c *Context) FindMessageByEventID(id string) (*Message, error) {
if c.Bot() == nil {
return nil, errors.New("Bot not set for the service")
}
return findMessageByEventID(c.db, c.Chat.ID, c.Bot().ID, id)
}
func findMessageByEventID(db *mgo.Database, chatID int64, botID int64, eventID string) (*Message, error) {
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"chatid": chatID, "botid": botID, "eventid": eventID}).Sort("-_id").One(&msg)
if err != nil || msg.BotID == 0 {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
func findMessageByBsonID(db *mgo.Database, id bson.ObjectId) (*Message, error) {
if !id.Valid() {
return nil, errors.New("BSON ObjectId is not valid")
}
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"_id": id}).One(&msg)
if err != nil {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
func findMessage(db *mgo.Database, chatID int64, botID int64, msgID int) (*Message, error) {
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"chatid": chatID, "botid": botID, "msgid": msgID}).One(&msg)
if err != nil {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
func findInlineMessage(db *mgo.Database, botID int64, inlineMsgID string) (*Message, error) {
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"botid": botID, "inlinemsgid": inlineMsgID}).One(&msg)
if err != nil {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
func findLastOutgoingMessageInChat(db *mgo.Database, botID int64, chatID int64) (*Message, error) {
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"chatid": chatID, "botid": botID, "fromid": botID}).Sort("-msgid").One(&msg)
if err != nil {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
func findLastMessageInChat(db *mgo.Database, botID int64, chatID int64) (*Message, error) {
msg := OutgoingMessage{}
err := db.C("messages").Find(bson.M{"chatid": chatID, "botid": botID}).Sort("-msgid").One(&msg)
if err != nil {
return nil, err
}
msg.Message.om = &msg
return &msg.Message, nil
}
// SetChat sets the target chat to send the message
func (m *OutgoingMessage) SetChat(id int64) *OutgoingMessage {
m.ChatID = id
return m
}
// SetBackupChat set backup chat id that will be used in case message failed to sent to private chat (f.e. bot stopped or not initialized)
func (m *OutgoingMessage) SetBackupChat(id int64) *OutgoingMessage {
m.BackupChatID = id
return m
}
// SetDocument adds the file located at localPath with name fileName to the message
func (m *OutgoingMessage) SetDocument(localPath string, fileName string) *OutgoingMessage {
m.FilePath = localPath
m.FileName = fileName
m.FileType = "document"
return m
}
// SetImage adds the image file located at localPath with name fileName to the message
func (m *OutgoingMessage) SetImage(localPath string, fileName string) *OutgoingMessage {
m.FilePath = localPath
m.FileName = fileName
m.FileType = "image"
return m
}
// EnableFileRemoveAfter adds the flag to remove the file after message will be sent
func (m *OutgoingMessage) EnableFileRemoveAfter() *OutgoingMessage {
m.FileRemoveAfter = true
return m
}
// SetKeyboard sets the keyboard markup and Selective bool. If Selective is true keyboard will sent only for target users that you must @mention people in text or specify with SetReplyToMsgID
func (m *OutgoingMessage) SetKeyboard(k KeyboardMarkup, selective bool) *OutgoingMessage {
m.Keyboard = true
m.KeyboardMarkup = k.Keyboard()
m.Selective = selective
//todo: here is workaround for QT version. Keyboard with selective is not working
return m
}
// SetInlineKeyboard sets the inline keyboard markup
func (m *OutgoingMessage) SetInlineKeyboard(k InlineKeyboardMarkup) *OutgoingMessage {
m.InlineKeyboardMarkup = k.Keyboard()
return m
}
// SetSelective sets the Selective mode for the keyboard. If Selective is true keyboard make sure to @mention people in text or specify message to reply with SetReplyToMsgID
func (m *OutgoingMessage) SetSelective(b bool) *OutgoingMessage {
m.Selective = b
return m
}
// SetSilent turns off notifications on iOS and make it silent on Android
func (m *OutgoingMessage) SetSilent(b bool) *OutgoingMessage {
m.Silent = b
return m
}
// SetOneTimeKeyboard sets the Onetime mode for keyboard. Keyboard will be hided after 1st use
func (m *OutgoingMessage) SetOneTimeKeyboard(b bool) *OutgoingMessage {
m.OneTimeKeyboard = b
return m
}
// SetResizeKeyboard sets the ResizeKeyboard to collapse keyboard wrapper to match the actual underneath keyboard
func (m *OutgoingMessage) SetResizeKeyboard(b bool) *OutgoingMessage {
m.ResizeKeyboard = b
return m
}
// SetCallbackAction sets the callback func that will be called when user press inline button with Data field
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *IncomingMessage) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage {
m.Message.SetCallbackAction(handlerFunc, args...)
//TODO: save reply action
return m
}
// SetCallbackAction sets the callback func that will be called when user press inline button with Data field
func (m *OutgoingMessage) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *OutgoingMessage {
m.Message.SetCallbackAction(handlerFunc, args...)
return m
}
// SetEditAction sets the edited func that will be called when user edit the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *IncomingMessage) SetEditAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage {
m.Message.SetEditAction(handlerFunc, args...)
return m
}
// SetReplyAction sets the reply func that will be called when user reply the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *IncomingMessage) SetReplyAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage {
m.Message.SetReplyAction(handlerFunc, args...)
//TODO: save reply action
return m
}
// SetReplyAction sets the reply func that will be called when user reply the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *OutgoingMessage) SetReplyAction(handlerFunc interface{}, args ...interface{}) *OutgoingMessage {
m.Message.SetReplyAction(handlerFunc, args...)
return m
}
// SetCallbackAction sets the reply func that will be called when user reply the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *Message) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *Message {
service, err := detectServiceByBot(m.BotID)
if err != nil {
log.WithError(err).Errorf("SetCallbackAction detectServiceByBot")
}
funcName := service.getShortFuncPath(handlerFunc)
err = verifyTypeMatching(handlerFunc, args...)
if err != nil {
log.WithError(err).Error("Can't verify onCallback args for " + funcName + ". Be sure to omit first arg of type '*integram.Context'")
return m
}
bytes, err := encode(args)
if err != nil {
log.WithError(err).Error("Can't encode onCallback args")
return m
}
m.OnCallbackData = bytes
m.OnCallbackAction = funcName
return m
}
// SetReplyAction sets the reply func that will be called when user reply the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *Message) SetReplyAction(handlerFunc interface{}, args ...interface{}) *Message {
service, err := detectServiceByBot(m.BotID)
if err != nil {
log.WithError(err).Errorf("SetReplyAction detectServiceByBot")
}
funcName := service.getShortFuncPath(handlerFunc)
if _, ok := actionFuncs[funcName]; !ok {
log.Panic(errors.New("Action for '" + funcName + "' not registred in service's configuration!"))
return m
}
err = verifyTypeMatching(handlerFunc, args...)
if err != nil {
log.WithError(err).Error("Can't verify onReply args for " + funcName + ". Be sure to omit first arg of type '*integram.Context'")
return m
}
bytes, err := encode(args)
if err != nil {
log.WithError(err).Error("Can't encode onReply args")
return m
}
m.OnReplyData = bytes
m.OnReplyAction = funcName
return m
}
// SetEditAction sets the edited func that will be called when user edit the message
// !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context
func (m *Message) SetEditAction(handlerFunc interface{}, args ...interface{}) *Message {
service, err := detectServiceByBot(m.BotID)
if err != nil {
log.WithError(err).Errorf("SetEditAction detectServiceByBot")
}
funcName := service.getShortFuncPath(handlerFunc)
if _, ok := actionFuncs[funcName]; !ok {
log.Panic(errors.New("Action for '" + funcName + "' not registred in service's configuration!"))
return m
}
err = verifyTypeMatching(handlerFunc, args...)
if err != nil {
log.WithError(err).Error("Can't verify onEdit args for " + funcName + ". Be sure to omit first arg of type '*integram.Context'")
return m
}
bytes, err := encode(args)
if err != nil {
log.WithError(err).Error("Can't encode onEdit args")
return m
}
m.OnEditData = bytes
m.OnEditAction = funcName
return m
}
// HideKeyboard will hide existing keyboard in the chat where message will be sent
func (m *OutgoingMessage) HideKeyboard() *OutgoingMessage {
m.KeyboardHide = true
return m
}
// EnableForceReply will automatically set the reply to this message and focus on the input field
func (m *OutgoingMessage) EnableForceReply() *OutgoingMessage {
m.ForceReply = true
return m
}
type messageSender interface {
Send(m *OutgoingMessage) error
}
type scheduleMessageSender struct{}
var activeMessageSender = messageSender(scheduleMessageSender{})
var ErrorFlood = fmt.Errorf("Too many messages. You could not send the same message more than once per %d sec", antiFloodSameMessageTimeout)
var ErrorBadRequstPrefix = "Can't process your request: "
func (t scheduleMessageSender) Send(m *OutgoingMessage) error {
if m.processed {
return nil
}
if m.AntiFlood {
db := mongoSession.Clone().DB(mongo.Database)
defer db.Session.Close()
msg, _ := findLastOutgoingMessageInChat(db, m.BotID, m.ChatID)
if msg != nil && msg.om.TextHash == m.GetTextHash() && time.Now().Sub(msg.Date).Seconds() < antiFloodSameMessageTimeout {
//log.Errorf("flood. mins %v", time.Now().Sub(msg.Date).Minutes())
return ErrorFlood
}
}
if m.Selective && m.ChatID > 0 {
m.Selective = false
}
m.ID = bson.NewObjectId()
if m.Selective && len(m.findUsernames()) == 0 && m.ReplyToMsgID == 0 {
err := errors.New("Inconsistence. Selective is true but there are no @mention or ReplyToMsgID specified")
log.WithField("chat", m.ChatID).Error(err)
return err
}
if m.ParseMode == "HTML" {
text := ""
var err error
if m.FilePath == "" {
text, err = sanitize.HTMLAllowing(m.Text, []string{"a", "b", "strong", "i", "em", "a", "code", "pre"}, []string{"href"})
} else {
// formatiing is not supported for file captions
text = sanitize.HTML(m.Text)
}
if err == nil && text != "" {
m.Text = text
}
} else {
text := sanitize.HTML(m.Text)
if text != "" {
m.Text = text
}
}
var sendAfter time.Time
if m.SendAfter != nil {
sendAfter = *m.SendAfter
} else {
sendAfter = time.Now()
}
_, err := sendMessageJob.Schedule(0, sendAfter, &m)
if err != nil {
log.WithField("chat", m.ChatID).WithError(err).Error("Can't schedule sendMessageJob")
} else {
m.processed = true
}
return err
}
// Send put the message to the jobs queue
func (m *OutgoingMessage) Send() error {
if m.ChatID == 0 {
return errors.New("ChatID is empty")
}
if m.BotID == 0 {
return errors.New("BotID is empty")
}
if m.Text == "" && m.FilePath == "" && m.Location == nil {
return errors.New("Text, FilePath and Location are empty")
}
if m.ctx != nil && m.ctx.messageAnsweredAt == nil {
n := time.Now()
m.ctx.messageAnsweredAt = &n
}
return activeMessageSender.Send(m)
}
// SetSendAfter set the time to send the message
func (m *OutgoingMessage) SetSendAfter(after time.Time) *OutgoingMessage {
m.SendAfter = &after
return m
}
// AddEventID attach one or more event ID. You can use eventid to edit the message in case of additional webhook received or to ignore in case of duplicate
func (m *OutgoingMessage) AddEventID(id ...string) *OutgoingMessage {
m.EventID = append(m.EventID, id...)
return m
}
// EnableAntiFlood will check if the message wasn't already sent within last antiFloodSameMessageTimeout seconds
func (m *OutgoingMessage) EnableAntiFlood() *OutgoingMessage {
m.AntiFlood = true