/
events.go
266 lines (231 loc) · 7.23 KB
/
events.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
package events
import (
"fmt"
"log"
"strings"
"time"
tbapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/umputun/tg-spam/app/bot"
"github.com/umputun/tg-spam/app/storage"
"github.com/umputun/tg-spam/lib/spamcheck"
)
//go:generate moq --out mocks/tb_api.go --pkg mocks --with-resets --skip-ensure . TbAPI
//go:generate moq --out mocks/spam_logger.go --pkg mocks --with-resets --skip-ensure . SpamLogger
//go:generate moq --out mocks/bot.go --pkg mocks --with-resets --skip-ensure . Bot
// TbAPI is an interface for telegram bot API, only subset of methods used
type TbAPI interface {
GetUpdatesChan(config tbapi.UpdateConfig) tbapi.UpdatesChannel
Send(c tbapi.Chattable) (tbapi.Message, error)
Request(c tbapi.Chattable) (*tbapi.APIResponse, error)
GetChat(config tbapi.ChatInfoConfig) (tbapi.Chat, error)
GetChatAdministrators(config tbapi.ChatAdministratorsConfig) ([]tbapi.ChatMember, error)
}
// SpamLogger is an interface for spam logger
type SpamLogger interface {
Save(msg *bot.Message, response *bot.Response)
}
// SpamLoggerFunc is a function that implements SpamLogger interface
type SpamLoggerFunc func(msg *bot.Message, response *bot.Response)
// Save is a function that implements SpamLogger interface
func (f SpamLoggerFunc) Save(msg *bot.Message, response *bot.Response) {
f(msg, response)
}
// Locator is an interface for message locator
type Locator interface {
AddMessage(msg string, chatID, userID int64, userName string, msgID int) error
AddSpam(userID int64, checks []spamcheck.Response) error
Message(msg string) (storage.MsgMeta, bool)
Spam(userID int64) (storage.SpamData, bool)
MsgHash(msg string) string
UserNameByID(userID int64) string
}
// Bot is an interface for bot events.
type Bot interface {
OnMessage(msg bot.Message) (response bot.Response)
UpdateSpam(msg string) error
UpdateHam(msg string) error
AddApprovedUser(id int64, name string) error
RemoveApprovedUser(id int64) error
IsApprovedUser(userID int64) bool
}
func escapeMarkDownV1Text(text string) string {
escSymbols := []string{"_", "*", "`", "["}
for _, esc := range escSymbols {
text = strings.Replace(text, esc, "\\"+esc, -1)
}
return text
}
// send a message to the telegram as markdown first and if failed - as plain text
func send(tbMsg tbapi.Chattable, tbAPI TbAPI) error {
withParseMode := func(tbMsg tbapi.Chattable, parseMode string) tbapi.Chattable {
switch msg := tbMsg.(type) {
case tbapi.MessageConfig:
msg.ParseMode = parseMode
msg.DisableWebPagePreview = true
return msg
case tbapi.EditMessageTextConfig:
msg.ParseMode = parseMode
msg.DisableWebPagePreview = true
return msg
case tbapi.EditMessageReplyMarkupConfig:
return msg
}
return tbMsg // don't touch other types
}
msg := withParseMode(tbMsg, tbapi.ModeMarkdown) // try markdown first
if _, err := tbAPI.Send(msg); err != nil {
log.Printf("[WARN] failed to send message as markdown, %v", err)
msg = withParseMode(tbMsg, "") // try plain text
if _, err := tbAPI.Send(msg); err != nil {
return fmt.Errorf("can't send message to telegram: %w", err)
}
}
return nil
}
type banRequest struct {
tbAPI TbAPI
userID int64
channelID int64
chatID int64
duration time.Duration
dry bool
training bool
}
// The bot must be an administrator in the supergroup for this to work
// and must have the appropriate admin rights.
// If channel is provided, it is banned instead of provided user, permanently.
func banUserOrChannel(r banRequest) error {
// From Telegram Bot API documentation:
// > If user is restricted for more than 366 days or less than 30 seconds from the current time,
// > they are considered to be restricted forever
// Because the API query uses unix timestamp rather than "ban duration",
// you do not want to accidentally get into this 30-second window of a lifetime ban.
// In practice BanDuration is equal to ten minutes,
// so this `if` statement is unlikely to be evaluated to true.
if r.dry {
log.Printf("[INFO] dry run: ban %d for %v", r.userID, r.duration)
return nil
}
if r.training {
log.Printf("[INFO] training mode: ban %d for %v", r.userID, r.duration)
return nil
}
if r.duration < 30*time.Second {
r.duration = 1 * time.Minute
}
if r.channelID != 0 {
resp, err := r.tbAPI.Request(tbapi.BanChatSenderChatConfig{
ChatID: r.chatID,
SenderChatID: r.channelID,
UntilDate: int(time.Now().Add(r.duration).Unix()),
})
if err != nil {
return err
}
if !resp.Ok {
return fmt.Errorf("response is not Ok: %v", string(resp.Result))
}
return nil
}
resp, err := r.tbAPI.Request(tbapi.BanChatMemberConfig{
ChatMemberConfig: tbapi.ChatMemberConfig{
ChatID: r.chatID,
UserID: r.userID,
},
UntilDate: time.Now().Add(r.duration).Unix(),
})
if err != nil {
return err
}
if !resp.Ok {
return fmt.Errorf("response is not Ok: %v", string(resp.Result))
}
return nil
}
func transform(msg *tbapi.Message) *bot.Message {
transformEntities := func(entities []tbapi.MessageEntity) *[]bot.Entity {
if len(entities) == 0 {
return nil
}
result := make([]bot.Entity, 0, len(entities))
for _, entity := range entities {
e := bot.Entity{
Type: entity.Type,
Offset: entity.Offset,
Length: entity.Length,
URL: entity.URL,
}
if entity.User != nil {
e.User = &bot.User{
ID: entity.User.ID,
Username: entity.User.UserName,
DisplayName: entity.User.FirstName + " " + entity.User.LastName,
}
}
result = append(result, e)
}
return &result
}
message := bot.Message{
ID: msg.MessageID,
Sent: msg.Time(),
Text: msg.Text,
}
if msg.Chat != nil {
message.ChatID = msg.Chat.ID
}
if msg.From != nil {
message.From = bot.User{
ID: msg.From.ID,
Username: msg.From.UserName,
}
}
if msg.From != nil && strings.TrimSpace(msg.From.FirstName) != "" {
message.From.DisplayName = msg.From.FirstName
}
if msg.From != nil && strings.TrimSpace(msg.From.LastName) != "" {
message.From.DisplayName += " " + msg.From.LastName
}
if msg.SenderChat != nil {
message.SenderChat = bot.SenderChat{
ID: msg.SenderChat.ID,
UserName: msg.SenderChat.UserName,
}
}
switch {
case msg.Entities != nil && len(msg.Entities) > 0:
message.Entities = transformEntities(msg.Entities)
case msg.Photo != nil && len(msg.Photo) > 0:
sizes := msg.Photo
lastSize := sizes[len(sizes)-1]
message.Image = &bot.Image{
FileID: lastSize.FileID,
Width: lastSize.Width,
Height: lastSize.Height,
Caption: msg.Caption,
Entities: transformEntities(msg.CaptionEntities),
}
if msg.Text == "" {
message.Text = msg.Caption
}
}
// fill in the message's reply-to message
if msg.ReplyToMessage != nil {
message.ReplyTo.Text = msg.ReplyToMessage.Text
message.ReplyTo.Sent = msg.ReplyToMessage.Time()
if msg.ReplyToMessage.From != nil {
message.ReplyTo.From = bot.User{
ID: msg.ReplyToMessage.From.ID,
Username: msg.ReplyToMessage.From.UserName,
DisplayName: msg.ReplyToMessage.From.FirstName + " " + msg.ReplyToMessage.From.LastName,
}
}
if msg.ReplyToMessage.SenderChat != nil {
message.ReplyTo.SenderChat = bot.SenderChat{
ID: msg.ReplyToMessage.SenderChat.ID,
UserName: msg.ReplyToMessage.SenderChat.UserName,
}
}
}
return &message
}