forked from jbpratt/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
497 lines (442 loc) · 12.3 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
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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/MemeLabs/dggchat"
"google.golang.org/api/calendar/v3"
)
type bot struct {
failTimeout time.Duration
sgg *dggchat.Session
lastCheck time.Time
cal *calendar.Service
calList *calendar.CalendarList
emoteSwitch bool
lastPublicFail time.Time
msgBuffer chan msg
}
type msg struct {
message string
private bool
recipient dggchat.User
}
type config struct {
AuthToken string `json:"auth_token"`
Address string `json:"address"`
CalendarClientID string `json:"calendar_client_ID"`
CalendarClientSecret string `json:"calendar_client_secret"`
}
var configFile string
func main() {
flag.Parse()
logFile, err := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer logFile.Close()
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)
config, err := readConfig()
if err != nil {
log.Fatal(err)
}
bot := newBot(config)
log.Println("[INFO] trying to establish connection...")
err = bot.sgg.Open()
if err != nil {
log.Fatal("[FATAL]", err)
}
log.Println("[INFO] connected")
bot.sgg.AddPMHandler(bot.onPM)
bot.sgg.AddMessageHandler(bot.onMessage)
bot.sgg.AddErrorHandler(onError)
for {
msg := <-bot.msgBuffer
if msg.private {
err := bot.sgg.SendPrivateMessage(msg.recipient.Nick, msg.message)
if err != nil {
log.Printf("[ERROR] could not send private messate: %s", err)
}
} else {
emote := "PepoG"
if bot.emoteSwitch {
emote = "PepoG:wide"
}
bot.emoteSwitch = !bot.emoteSwitch
err := bot.sgg.SendMessage(fmt.Sprintf("%s %s", emote, msg.message))
if err != nil {
log.Printf("[ERROR] could not send message: %s", err)
}
}
time.Sleep(time.Millisecond * 450)
}
}
func (b *bot) onPM(dm dggchat.PrivateMessage, s *dggchat.Session) {
m := dggchat.Message{Sender: dm.User, Timestamp: dm.Timestamp, Message: dm.Message}
b.answer(m, true)
}
func (b *bot) onMessage(m dggchat.Message, s *dggchat.Session) {
if strings.HasPrefix(strings.TrimSpace(m.Message), "whenis") {
b.answer(m, false)
}
}
//noinspection GoUnusedParameter
func onError(e string, session *dggchat.Session) {
log.Printf("[ERROR] %s", e)
}
func readConfig() (*config, error) {
file, err := os.Open(configFile)
if err != nil {
return nil, err
}
defer file.Close()
bv, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
var c *config
c = new(config)
err = json.Unmarshal(bv, &c)
if err != nil {
return nil, err
}
return c, err
}
func newBot(config *config) *bot {
var b bot
b.failTimeout = time.Second * 30
sgg, err := dggchat.New(";jwt=" + config.AuthToken)
if err != nil {
log.Fatalf("Unable to get connect to chat: %v", err)
}
b.sgg = sgg
u, err := url.Parse(config.Address)
if err != nil {
log.Fatalf("[ERROR] can't parse url %v", err)
}
b.sgg.SetURL(*u)
b.retrieveCalendar(nil)
b.calList, err = getCalendars(b.cal)
if err != nil {
log.Fatalf("Unable to get calendars: %v", err)
}
b.msgBuffer = make(chan msg, 100)
return &b
}
func (b *bot) answer(message dggchat.Message, private bool) {
if time.Since(b.lastCheck).Minutes() > 5 {
cals, err := getCalendars(b.cal)
if err != nil {
log.Printf("Unable to get calendars: %v", err)
} else {
b.lastCheck = time.Now()
b.calList = cals
}
}
prvt := "public"
if private {
prvt = "private"
}
searchText := strings.TrimSpace(strings.Replace(message.Message, "whenis", "", -1))
lowerText := strings.ToLower(searchText)
log.Printf("[INFO] received %s request from [%s]: %q", prvt, message.Sender.Nick, searchText)
if strings.Contains(lowerText, "-next") || searchText == "" {
b.replyNextEvent(private, message.Sender)
return
} else if strings.Contains(lowerText, "-multi") {
b.replyMultiSearch(searchText, message.Sender)
return
} else if strings.Contains(lowerText, "help") {
b.replyHelp(message.Sender)
return
} else if strings.Contains(lowerText, "-ongoing") {
b.replyOngoingEvents(private, message.Sender)
return
} else if strings.Contains(lowerText, "-start") {
b.setEvent(searchText, message.Sender)
return
} else if strings.Contains(lowerText, "-calendars") {
b.listCalendars(message.Sender, private)
return
}
b.replySingleSearch(searchText, private, message.Sender)
}
func timeDiff(e *calendar.Event) time.Duration {
return eventStartTime(e).Sub(time.Now())
}
func eventStartTime(e *calendar.Event) time.Time {
date := e.Start.DateTime
t, _ := time.Parse(time.RFC3339, date)
if date == "" {
date = e.Start.Date
t, _ = time.Parse("2006-01-02", date)
}
return t
}
func eventEndTime(e *calendar.Event) time.Time {
date := e.End.DateTime
t, _ := time.Parse(time.RFC3339, date)
if date == "" {
date = e.End.Date
t, _ = time.Parse("2006-01-02", date)
}
return t
}
func generateResponse(diff time.Duration, item *calendar.Event) string {
var response string
if diff.Round(time.Minute).Minutes() == 0 {
response = fmt.Sprintf("%v is starting now", item.Summary)
} else if diff.Minutes() < 0 {
diff *= -1
response = fmt.Sprintf("%v started %v ago", item.Summary, fmtDuration(diff))
} else {
response = fmt.Sprintf("%v is in %v", item.Summary, fmtDuration(diff))
}
return response
}
func fmtDuration(d time.Duration) string {
d = d.Round(time.Minute)
h := d / time.Hour
hours := h % 24
days := (h - hours) / 24
d -= h * time.Hour
m := d / time.Minute
response := ""
if days > 0 {
dayString := "days"
sep := ","
if days == 1 {
dayString = "day"
}
if m == 0 || hours == 0 {
sep = " and"
}
if m == 0 && hours == 0 {
sep = ""
}
response += fmt.Sprintf("%d %v%v ", days, dayString, sep)
}
if hours > 0 {
hourString := "hours"
sep := "and"
if hours == 1 {
hourString = "hour"
}
if m == 0 {
sep = ""
}
response += fmt.Sprintf("%d %v %v ", hours, hourString, sep)
}
if m > 0 {
minuteString := "minutes"
if m == 1 {
minuteString = "minute"
}
response += fmt.Sprintf("%d %v", m, minuteString)
}
return response
}
func init() {
flag.StringVar(&configFile, "config", "./config/config.json", "location of config")
}
func (b *bot) multiSendMsg(messages []string, user dggchat.User) {
for _, message := range messages {
b.sendMsg(message, true, user)
}
}
func (b *bot) sendMsg(message string, private bool, user dggchat.User) {
var m msg
m.private = private
m.recipient = user
m.message = message
b.msgBuffer <- m
}
func (b *bot) replySingleSearch(search string, private bool, user dggchat.User) {
var response string
events, err := query(b.cal, b.calList, search, 1)
if err != nil {
log.Printf("error searching for event: %v", err)
b.sendMsg("There was an error searching for your query. If this persists please contact SoMuchForSubtlety", true, user)
return
}
if len(events) == 0 {
ev, err := queryCalTitles(b.cal, b.calList, search, 1)
if err != nil {
log.Printf("error searching for event: %v", err)
b.sendMsg("There was an error searching for your query. If this persists please contact SoMuchForSubtlety", true, user)
return
}
if ev == nil || len(ev.Items) == 0 {
private = private || !b.canFailPublicly()
b.sendMsg(fmt.Sprintf("No upcoming events found for '%s'", search), private, user)
return
}
events = ev.Items
}
event := events[0]
response = generateResponse(timeDiff(event), event)
b.sendMsg(response, private, user)
}
func (b *bot) replyNextEvent(private bool, user dggchat.User) {
var response string
event, err := getNextEvent(b.cal, b.calList)
if err != nil {
log.Printf("error searching for event: %v", err)
b.sendMsg("There was an error searching for your query. If this persists please contact SoMuchForSubtlety", true, user)
return
}
if event == nil {
private = private || !b.canFailPublicly()
response = "No upcoming events found."
} else {
response = generateResponse(timeDiff(event), event)
}
b.sendMsg(response, private, user)
}
func (b *bot) canFailPublicly() (response bool) {
response = time.Since(b.lastPublicFail).Seconds() > b.failTimeout.Seconds()
b.lastPublicFail = time.Now()
return
}
func (b *bot) replyMultiSearch(search string, user dggchat.User) {
var responses []string
var i int
start := 0
split := strings.Fields(search)
for j, s := range split {
if s == "-multi" {
start = j
break
}
}
start += 2
i, err := strconv.Atoi(split[start-1])
if err != nil {
if _, err := strconv.ParseFloat(split[start-1], 64); err == nil {
b.sendMsg("WeirdChamp", true, user)
return
}
start--
i = 5
} else if i > 15 {
i = 15
} else if i < 0 {
b.sendMsg("Don't be so negative haHAA", true, user)
return
} else if i == 0 {
b.sendMsg("Nice one haHAA", true, user)
return
}
search = strings.Join(split[start:], " ")
events, err := query(b.cal, b.calList, search, int64(i))
if err != nil {
log.Printf("error searching for event: %v", err)
b.sendMsg("There was an error searching for your query. If this persists please contact SoMuchForSubtlety", true, user)
return
}
if events == nil || len(events) == 0 {
b.sendMsg(fmt.Sprintf("No upcoming events found for '%s'", search), true, user)
return
}
for _, event := range events {
responses = append(responses, generateResponse(timeDiff(event), event))
}
b.multiSendMsg(responses, user)
}
func (b *bot) replyHelp(user dggchat.User) {
responses := []string{
"`/msg whenis -help` to display this info",
"`/msg whenis Formula 1` to search for an event (in this case F1)",
"`/msg whenis -multi 5 Formula 1` to search for the next 5 F1 events",
"`/msg whenis -next` to show the next scheduled event",
"`/msg whenis -ongoing` to show a list of all ongoing events",
"`/msg whenis -start 20 Session Title` adds a session to the calendar with a duration of 20 minutes and the title 'Session Title' (abusing this will get you blacklisted)",
"`/msg whenis -calendars` to get a list of active calendars",
"All of these also work in public chat, but some will only reply with private messages",
}
b.multiSendMsg(responses, user)
}
func (b *bot) replyOngoingEvents(private bool, user dggchat.User) {
var responses []string
events, err := getOngoingEvents(b.cal, b.calList)
if err != nil {
log.Printf("error searching for event: %v", err)
b.sendMsg("There was an error searching for your query. If this persists please contact SoMuchForSubtlety", true, user)
return
}
if events == nil || len(events) == 0 {
b.sendMsg("No ongoing events found.", true, user)
return
}
for _, event := range events {
if !regexp.MustCompile(`Week [0-9]{1,2} of [0-9]{4}`).Match([]byte(event.Summary)) {
responses = append(responses, generateResponse(timeDiff(event), event))
}
}
if len(responses) == 1 {
b.sendMsg(responses[0], private, user)
return
}
b.multiSendMsg(responses, user)
}
func (b *bot) retrieveCalendar(err error) {
if err != nil {
log.Println("[ERROR]", err)
}
b.cal, err = getCalendar()
if err != nil {
log.Fatalf("Unable to get calendar: %v", err)
}
}
func (b *bot) setEvent(input string, user dggchat.User) {
duration := time.Minute * 120
var remainder string
split := strings.Split(input, " ")
if strings.ToLower(split[0]) != "-start" {
b.sendMsg("invalid syntax", true, user)
return
}
if i, err := strconv.Atoi(split[1]); err == nil {
duration = time.Minute * time.Duration(int32(i))
if len(split) >= 3 {
remainder = strings.Join(split[2:], " ")
}
} else {
if len(split) >= 2 {
remainder = strings.Join(split[1:], " ")
}
}
if duration.Minutes() >= 2880 || duration.Minutes() <= 0 {
b.sendMsg("PepoBan", true, user)
return
}
err := b.insertSession(remainder, user.Nick, duration)
if err != nil {
b.sendMsg("Error insertion your session, please contact SoMuchForSubtlety", true, user)
return
}
b.sendMsg(fmt.Sprintf("Added '%v' with a duration of %v successfully.", remainder, fmtDuration(duration)), true, user)
}
func (b *bot) listCalendars(user dggchat.User, private bool) {
var response string
for _, calendarListEntry := range b.calList.Items {
if !calendarListEntry.Primary {
if calendarListEntry.SummaryOverride != "" {
response += fmt.Sprintf(" `%s`", calendarListEntry.SummaryOverride)
} else {
response += fmt.Sprintf(" `%s`", calendarListEntry.Summary)
}
}
}
b.sendMsg(response, private, user)
}