-
Notifications
You must be signed in to change notification settings - Fork 5
/
bot.go
273 lines (251 loc) · 6.63 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
package govkbot
import (
"log"
"strconv"
"strings"
"time"
)
// VKBot - bot config
type VKBot struct {
msgRoutes map[string]msgRoute
actionRoutes map[string]func(*Message) string
cmdHandlers map[string]func(*Message) string
msgHandlers map[string]func(*Message) string
errorHandler func(*Message, error)
LastMsg int64
lastUserMessages map[int64]int64
lastChatMessages map[int64]int64
autoFriend bool
IgnoreBots bool
API *VkAPI
}
type msgRoute struct {
SimpleHandler func(*Message) string
Handler func(*Message) Reply
}
// NewBot - create new instance of bot
func (api *VkAPI) NewBot() *VKBot {
return &VKBot{
msgRoutes: make(map[string]msgRoute),
actionRoutes: make(map[string]func(*Message) string),
lastUserMessages: make(map[int64]int64),
lastChatMessages: make(map[int64]int64),
API: api,
}
}
// ListenUser - listen User VK API (deprecated)
func (bot *VKBot) ListenUser(api *VkAPI) error {
poller := NewUserLongPollServer(false, longPollVersion, API.RequestInterval)
go bot.friendReceiver()
c := time.Tick(3 * time.Second)
for range c {
bot.MainRoute(poller)
}
return nil
}
// ListenGroup - listen group VK API
func (bot *VKBot) ListenGroup(api *VkAPI) error {
poller := NewGroupLongPollServer(API.RequestInterval)
c := time.Tick(3 * time.Second)
for range c {
bot.MainRoute(poller)
}
return nil
}
// HandleMessage - add substr message handler.
// Function must return string to reply or "" (if no reply)
func (bot *VKBot) HandleMessage(command string, handler func(*Message) string) {
bot.msgRoutes[command] = msgRoute{SimpleHandler: handler}
}
// HandleAdvancedMessage - add substr message handler.
// Function must return string to reply or "" (if no reply)
func (bot *VKBot) HandleAdvancedMessage(command string, handler func(*Message) Reply) {
bot.msgRoutes[command] = msgRoute{Handler: handler}
}
// HandleAction - add action handler.
// Function must return string to reply or "" (if no reply)
func (bot *VKBot) HandleAction(command string, handler func(*Message) string) {
bot.actionRoutes[command] = handler
}
// HandleError - add error handler
func (bot *VKBot) HandleError(handler func(*Message, error)) {
bot.errorHandler = handler
}
// SetAutoFriend - auto add friends
func (bot *VKBot) SetAutoFriend(af bool) {
bot.autoFriend = af
}
// SetIgnoreBots - ignore bots messages
func (bot *VKBot) SetIgnoreBots(ignore bool) {
bot.IgnoreBots = ignore
}
// GetMessages - request unread messages from VK (more than 200)
func (bot *VKBot) GetMessages() ([]*Message, error) {
var allMessages []*Message
lastMsg := bot.LastMsg
offset := 0
var err error
var messages *Messages
for {
messages, err = API.GetMessages(API.MessagesCount, offset)
if len(messages.Items) > 0 {
if messages.Items[0].ID > lastMsg {
lastMsg = messages.Items[0].ID
}
}
allMessages = append(allMessages, messages.Items...)
if bot.LastMsg > 0 {
if len(messages.Items) > 0 {
if messages.Items[len(messages.Items)-1].ID <= bot.LastMsg {
bot.LastMsg = lastMsg
break
}
} else {
break
}
offset += API.MessagesCount
} else {
bot.LastMsg = lastMsg
break
}
}
if offset > 0 {
API.NotifyAdmin("many messages in interval. offset: " + strconv.Itoa(offset))
}
return allMessages, err
}
// RouteAction routes an action
func (bot *VKBot) RouteAction(m *Message) (replies []string, err error) {
if m.Action != "" {
debugPrint("route action: %+v\n", m.Action)
for k, v := range bot.actionRoutes {
if m.Action == k {
msg := v(m)
if msg != "" {
replies = append(replies, msg)
}
}
}
}
return replies, nil
}
// RouteMessage routes single message
func (bot *VKBot) RouteMessage(m *Message) (replies []Reply, err error) {
message := strings.TrimSpace(strings.ToLower(m.Body))
if HasPrefix(message, "/ ") {
message = "/" + TrimPrefix(message, "/ ")
}
if m.Action != "" {
actionReplies, err := bot.RouteAction(m)
for _, r := range actionReplies {
replies = append(replies, Reply{Msg: r})
}
return replies, err
}
for k, v := range bot.msgRoutes {
if HasPrefix(message, k) {
if v.Handler != nil {
reply := v.Handler(m)
if reply.Msg != "" || reply.Keyboard != nil {
replies = append(replies, reply)
}
} else {
msg := v.SimpleHandler(m)
if msg != "" {
replies = append(replies, Reply{Msg: msg})
}
}
}
}
return replies, nil
}
// RouteMessages routes inbound messages
func (bot *VKBot) RouteMessages(messages []*Message) (result map[*Message][]Reply) {
result = make(map[*Message][]Reply)
for _, m := range messages {
if m.ReadState == 0 {
if bot.IgnoreBots && m.UserID < 0 {
continue
}
replies, err := bot.RouteMessage(m)
if err != nil {
sendError(m, err)
}
if len(replies) > 0 {
result[m] = replies
}
}
}
return result
}
// MainRoute - main router func. Working cycle Listen.
func (bot *VKBot) MainRoute(poller LongPollServer) {
messages, err := poller.GetLongPollMessages()
if err != nil {
sendError(nil, err)
}
debugPrint("inbox: %+v\n", messages)
replies := bot.RouteMessages(messages)
for m, msgs := range replies {
for _, reply := range msgs {
debugPrint("outbox: ", reply.Msg)
if reply.Msg != "" || reply.Keyboard != nil {
_, err = bot.Reply(m, reply)
if err != nil {
log.Printf("Error sending message: '%+v'\n", reply)
sendError(m, err)
_, err = bot.Reply(m, Reply{Msg: "Cant send message, maybe wrong/china letters?"})
if err != nil {
sendError(m, err)
}
}
}
}
}
}
// Reply - reply message
func (bot *VKBot) Reply(m *Message, reply Reply) (id int64, err error) {
if m.PeerID != 0 {
return bot.API.SendAdvancedPeerMessage(m.PeerID, reply)
}
if m.ChatID != 0 {
return bot.API.SendChatMessage(m.ChatID, reply.Msg)
}
return bot.API.SendMessage(m.UserID, reply.Msg)
}
// CheckFriends checking friend invites and matсhes and deletes mutual
func (bot *VKBot) CheckFriends() {
uids, _ := bot.API.GetFriendRequests(false)
if len(uids) > 0 {
for _, uid := range uids {
bot.API.AddFriend(uid)
for k, v := range bot.actionRoutes {
if k == "friend_add" {
m := Message{Action: "friend_add", UserID: uid}
v(&m)
}
}
}
}
uids, _ = bot.API.GetFriendRequests(true)
if len(uids) > 0 {
for _, uid := range uids {
bot.API.DeleteFriend(uid)
for k, v := range bot.actionRoutes {
if k == "friend_delete" {
m := Message{Action: "friend_delete", UserID: uid}
v(&m)
}
}
}
}
}
func (bot *VKBot) friendReceiver() {
if bot.API.UID > 0 {
bot.CheckFriends()
c := time.Tick(30 * time.Second)
for range c {
bot.CheckFriends()
}
}
}