-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
414 lines (368 loc) · 10.6 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"strconv"
"strings"
"time"
tgbotapi "github.com/OvyFlash/telegram-bot-api"
"gopkg.in/yaml.v3"
)
type Config struct {
Token string `yaml:"bot_token"`
Connection string `yaml:"connection"`
HostPort string `yaml:"hostport"`
ForbiddenText []string `yaml:"forbiddenText"`
Ranks map[string]string `yaml:"ranks"`
WelcomeMessage string `yaml:"welcome_message"`
WelcomeButtonMessage string `yaml:"welcome_button_message"`
DenyBots []string `yaml:"denybots"`
Admins []int `yaml:"admins"`
PinnedMessage string `yaml:"pinnedMessage"`
PinnedMessageId int `yaml:"pinnedMessageId"`
}
var emulate = false
var forceProtection = true
var MainConfig Config
var startTime time.Time
var bot *tgbotapi.BotAPI
var err error
func init() {
readConfig() //Fill config with values
readTriggers()
importCache()
startTime = time.Now()
go syncData()
}
func main() {
var updates tgbotapi.UpdatesChannel
botInit()
afterBotInit()
// initMetrics()
updates = startBot()
processUpdates(updates)
} //End main()
func processUpdates(updates tgbotapi.UpdatesChannel) {
for update := range updates {
// Check for callback query
if update.CallbackQuery != nil {
handleCallback(update.CallbackQuery)
continue
}
//Private chat
if update.MyChatMember != nil {
slog.Info(fmt.Sprintf("New MyChatMember %d", update.MyChatMember.NewChatMember.User.ID))
}
//If chat hides userlist
if update.ChatMember != nil {
if update.ChatMember.NewChatMember.Status == "kicked" {
continue
}
if isNewMember(update.ChatMember) {
setInitialRights(update, *update.ChatMember.NewChatMember.User)
if forceProtection {
if isUserApiBanned(int(update.ChatMember.NewChatMember.User.ID)) {
BanChatMember(update.ChatMember.Chat.ID, update.ChatMember.NewChatMember.User.ID, 0)
} else {
welcomeNewUser(update, *update.ChatMember.NewChatMember.User)
}
} else {
welcomeNewUser(update, *update.ChatMember.NewChatMember.User)
}
}
}
if update.Message == nil { // ignore any non-Message updates
if update.EditedMessage != nil {
CheckTriggerMessage(update.EditedMessage)
}
continue
}
if update.Message.IsCommand() { // ignore any non-command Messages
processCommands(update.Message.Command(), *update.Message)
continue
}
// Handle new members joining
if update.Message.NewChatMembers != nil {
for _, newMember := range update.Message.NewChatMembers {
if isCachedUser(newMember.ID) {
welcomeNewUser(update, newMember)
setInitialRights(update, newMember)
continue
}
}
}
//Handle member left
if update.Message.LeftChatMember != nil {
slog.Info("Member left: " + update.Message.LeftChatMember.UserName)
slog.Info("Update.Message" + update.Message.Text)
//log.Print(fmt.Printf("%+v\n", update.Message))
continue
}
if isDenyBot(update.Message) {
deleteMessage(update.Message.Chat.ID, update.Message.MessageID)
}
// Check for forbidden text
if !isAdmin(update.Message.From.ID) {
// Check Bad text message
if isBadMessage(update.Message.Text) {
if emulate {
log.Print(update.Message.Chat.ID, update.Message.MessageID)
continue
}
deleteMessage(update.Message.Chat.ID, update.Message.MessageID)
CleanUpWelcome()
continue
}
//Check message starting with emoji. Usually spam.
if isMessageStartsWithEmoji(update) {
slog.Info("Deleted message with emoji - " + update.Message.From.UserName)
deleteMessage(update.Message.Chat.ID, update.Message.MessageID)
}
//Check message from channel
if isChannelMessage(update) {
slog.Info("Deleted message from channel - " + update.Message.SenderChat.UserName)
deleteMessage(update.Message.Chat.ID, update.Message.MessageID)
continue
}
} else {
//AdminsZone
if update.Message.ChatShared != nil {
if update.Message.ChatShared.RequestID == 1000 { //pin message
pinMessage(update.Message.ChatShared.ChatID)
}
}
}
CheckTriggerMessage(update.Message)
//Fix rights for the newcomers
fixRights(update)
}
}
func pinMessage(id int64) {
msg := tgbotapi.NewMessage(id, getPinnedMessage())
msg.ParseMode = "HTML"
mId, _ := bot.Send(msg)
slog.Info(fmt.Sprintf("Pinned message ID: %d", mId.MessageID))
}
func handleCallback(query *tgbotapi.CallbackQuery) {
type Command struct {
Command string `json:"command"`
Data string `json:"data"`
}
var callback Command
var user int64
err := json.Unmarshal([]byte(query.Data), &callback)
if err != nil {
slog.Warn("Callback error:", "error", err)
}
switch callback.Command {
case "upgrade_rights":
user, err = strconv.ParseInt(callback.Data, 10, 64)
if !isAdmin(query.From.ID) {
if user != query.From.ID {
slog.Info(fmt.Sprintf("User %s(%d) clicked wrong button", query.From.UserName, query.From.ID))
break
}
}
slog.Info(fmt.Sprintf("User %s(%d) clicked his button", query.From.UserName, query.From.ID))
if isUserApiBanned(int(user)) {
answerCallbackQuery(query.ID, "Sorry, Api Ban")
BanChatMember(query.Message.Chat.ID, user, 0)
} else {
upgradeUserRights(query.Message.Chat.ID, user)
answerCallbackQuery(query.ID, "Rights upgraded!")
}
deleteMessage(query.Message.Chat.ID, query.Message.MessageID)
// handle other callbacks here
case "show_menu":
deleteMessage(query.Message.Chat.ID, query.Message.MessageID)
msg := tgbotapi.NewMessage(query.Message.Chat.ID, "ᓚᘏᗢ"+strings.Repeat(" ", 80)+"\\^o^/")
msg.ParseMode = "HTML"
msg.ReplyMarkup = replyWithMenu(callback.Data)
bot.Send(msg)
case "show_root_menu":
deleteMessage(query.Message.Chat.ID, query.Message.MessageID)
msg := tgbotapi.NewMessage(query.Message.Chat.ID, "Дополнительные команды в кнопке меню.\r\n Посмотрите готовые статьи")
msg.ParseMode = "HTML"
msg.ReplyMarkup = rootMenu()
bot.Send(msg)
}
}
func fixRights(update tgbotapi.Update) {
config := tgbotapi.GetChatMemberConfig{
ChatConfigWithUser: tgbotapi.ChatConfigWithUser{
ChatConfig: tgbotapi.ChatConfig{
ChatID: update.Message.Chat.ID,
},
UserID: update.Message.From.ID,
},
}
member, err := bot.GetChatMember(config)
if err != nil {
log.Print(err)
}
if member.CanSendMessages && !member.CanSendPhotos {
log.Print("Fix rights for user " + update.Message.From.UserName)
upgradeUserRights(update.Message.Chat.ID, update.Message.From.ID)
}
}
func processCommands(command string, message tgbotapi.Message) {
//Only Private messages
if message.From.ID != message.Chat.ID {
deleteMessage(message.Chat.ID, message.MessageID)
return
}
msg := tgbotapi.NewMessage(message.Chat.ID, "")
switch command {
case "help":
msg.Text = "I understand /uptime and /start."
msg.ReplyParameters.MessageID = message.MessageID
case "uptime":
msg.Text = "Uptime: " + uptime()
msg.ReplyParameters.MessageID = message.MessageID
case "start":
msg.Text = "Дополнительные команды в кнопке меню.\r\nПосмотрите готовые статьи"
msg.ReplyMarkup = rootMenu()
deleteMessage(message.Chat.ID, message.MessageID)
case "reload":
reload()
msg.Text = "Reloaded"
case "triggers":
msg.ParseMode = "HTML"
msg.Text = getTriggersList()
case "say":
msg.Text = "Select chat to send"
msg.ReplyMarkup = say()
case "deletequeue":
msg.Text = ToDeleteQueue()
case "checkqueue":
counter := checkBanQueue()
msg.Text = "Cleaned " + strconv.Itoa(counter) + " messages"
case "welcomequeue":
CleanWelcomeQueue()
msg.Text = "Welcome queue cleaned"
case "cleanup":
counter := CleanUpWelcome()
msg.Text = "Cleaned " + strconv.Itoa(counter) + " messages"
case "debug_mode":
msg.Text = toggle_debugMode()
case "force_mode":
msg.Text = toggle_forceMode()
default:
msg.Text = ""
}
if msg.Text != "" {
_, err = bot.Send(msg)
if err != nil {
log.Println(err)
}
}
}
func say() tgbotapi.ReplyKeyboardMarkup {
var buttonRow []tgbotapi.KeyboardButton
buttonRow = append(buttonRow,
tgbotapi.KeyboardButton{
RequestChat: &tgbotapi.KeyboardButtonRequestChat{RequestID: 1000, BotIsMember: true},
Text: "Select chat",
})
return tgbotapi.NewOneTimeReplyKeyboard(buttonRow)
}
func ToDeleteQueue() string {
return fmt.Sprintln(cache.DeleteList)
}
func CleanWelcomeQueue() {
cache.Member = nil
}
func checkBanQueue() int {
counter := 0
if len(cache.DeleteList) > 0 {
for id := 0; id < len(cache.DeleteList); id++ {
if isUserApiBanned(int(cache.DeleteList[id].UserID)) {
cache.DeleteList[id].Timestamp = time.Now().UTC()
counter++
}
}
}
CleanUpWelcome()
return counter
}
func uptime() string {
return fmt.Sprintln(time.Since(startTime).Round(time.Second))
}
func reload() {
readTriggers()
readMenu()
}
func readConfig() {
// Read and parse the config file
configFile, err := os.ReadFile("config.yaml")
if err != nil {
log.Panic(err)
}
err = yaml.Unmarshal(configFile, &MainConfig)
if err != nil {
log.Panic(err)
}
//Override with ENV
token := os.Getenv("BOT_TOKEN")
if token != "" {
MainConfig.Token = token
}
hostport := os.Getenv("WEBHOOK_HOSTPORT")
if token != "" {
MainConfig.HostPort = hostport
}
}
func botInit() {
//Common part
bot, err = tgbotapi.NewBotAPI(MainConfig.Token) // Set up the Telegram bot
if err != nil {
log.Panic(err)
}
if isDebugMode() {
bot.Debug = true
}
slog.Info(fmt.Sprintf("Authorized on account %s", bot.Self.UserName))
}
func afterBotInit() {
startMenu()
}
func startBot() tgbotapi.UpdatesChannel {
var updates tgbotapi.UpdatesChannel
if !isWebhook() {
deleteWh := tgbotapi.DeleteWebhookConfig{}
bot.Request(deleteWh)
//GetUpdatesWay
// Create a new Update config with a timeout
u := tgbotapi.NewUpdate(0)
u.Timeout = 10
updates = bot.GetUpdatesChan(u)
// TODO Ranking
// Initialize a map to track user message counts
//userMessageCounts := make(map[int]int)
//End GetUpdates
//Webhook way
} else {
wh, err := tgbotapi.NewWebhookWithCert("https://"+MainConfig.HostPort+"/"+bot.Token, tgbotapi.FilePath("jpbot.pem"))
if err != nil {
panic(err)
}
_, err = bot.Request(wh)
if err != nil {
panic(err)
}
info, err := bot.GetWebhookInfo()
if err != nil {
panic(err)
}
if info.LastErrorDate != 0 {
log.Printf("failed to set webhook: %s", info.LastErrorMessage)
}
updates = bot.ListenForWebhook("/" + bot.Token)
go http.ListenAndServeTLS(MainConfig.HostPort, "jpbot.pem", "jpbot.key", nil)
}
return updates
}