-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
96 lines (79 loc) · 2.28 KB
/
handlers.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
package tgBotVkPostSendler
import (
"fmt"
"log"
tgbotapi "gopkg.in/telegram-bot-api.v4"
)
func (h *Handler) handlePosts(msg Message, channelName string) {
if msg.Error != nil {
h.errorLogging(msg.Error.Error())
return
}
if err := h.sendMsgToChannel(channelName, msg); err != nil {
h.errorLogging(fmt.Sprintf("[ERR] Channel Name: %v, Error: %v", channelName, err))
}
}
func (h *Handler) handleFailedPosts(channelName string) {
messages, err := h.DbWriter.SelectFailedRows()
if err != nil {
h.errorLogging(fmt.Sprintf("[ERR] Trying to select old rows. Error: %v", err))
return
}
for _, message := range messages {
if err := h.sendMsgToChannel(channelName, message); err != nil {
h.errorLogging(fmt.Sprintf("[ERR] Channel Name: %v, Error: %v", channelName, err))
}
}
}
func (h *Handler) handleMessages(message *tgbotapi.Message, channelName string) {
username := message.Chat.UserName
chatId := message.Chat.ID
if _, ok := h.recipients[username]; ok {
text := h.manageCommands(username, message.Text, chatId)
h.Telegram.bot.Send(tgbotapi.NewMessage(chatId, text))
return
}
if _, err := h.Telegram.bot.Send(
tgbotapi.NewMessage(chatId, fmt.Sprintf("Bot is handler for %v channel", channelName)),
); err != nil {
h.errorLogging(fmt.Sprintf("[ERR] Channel Name: %v, Error: %v", channelName, err))
}
}
const (
unsetlogs = "/unsetlogs"
setlogs = "/setlogs"
)
func (h *Handler) manageCommands(username, text string, chatId int64) string {
switch text {
case unsetlogs:
h.recipients[username] = 0
return fmt.Sprintf("%s for user %s", unsetlogs, username)
case setlogs:
h.recipients[username] = chatId
return fmt.Sprintf("%s for user %s", setlogs, username)
default:
return "unknown command"
}
}
func (h *Handler) errorLogging(text string) {
log.Println(text)
if len(h.recipients) == 0 {
return
}
// sending msgs only for users with chatId
for _, chatId := range h.recipients {
if chatId == 0 {
continue
}
h.Telegram.bot.Send(tgbotapi.NewMessage(chatId, text))
}
}
func (h *Handler) sendMsgToChannel(channelName string, msg Message) error {
if _, err := h.Telegram.bot.Send(tgbotapi.NewMessageToChannel(channelName, msg.Text)); err != nil {
return err
}
if err := h.DbWriter.UpdateStatus(msg.ID); err != nil {
return err
}
return nil
}