-
Notifications
You must be signed in to change notification settings - Fork 6
/
commands.go
601 lines (510 loc) · 13.9 KB
/
commands.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package main
import (
"errors"
"fmt"
"log"
"math"
"math/rand"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/MemeLabs/dggchat"
)
var (
mutex sync.Mutex
commands = map[string]string{}
)
func isMod(user dggchat.User) bool {
return user.HasFeature("moderator") || user.HasFeature("admin")
}
// TODO
func (b *bot) sendMessageDedupe(m string, s *dggchat.Session) {
if logOnly {
log.Printf("[##] LOGONLY reply: %s\n", m)
return
}
b.randomizer++
rnd := " " + strings.Repeat(".", b.randomizer%2)
err := s.SendMessage(m + rnd)
if err != nil {
log.Printf("[##] send error: %s\n", err.Error())
}
}
func (b *bot) staticMessage(m dggchat.Message, s *dggchat.Session) {
for command, response := range commands {
if strings.HasPrefix(m.Message, command) {
b.sendMessageDedupe(response, s)
// only handle the first match
return
}
}
}
// !nuke str, !nukeregex regexp
func (b *bot) nuke(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!nuke") {
return
}
parts := strings.SplitN(m.Message, " ", 2)
if len(parts) <= 1 {
return
}
isRegexNuke := parts[0] == "!nukeregex"
badstr := parts[1]
badregexp, err := regexp.Compile(badstr) // TODO when is error not nil??
if isRegexNuke && err != nil {
b.sendMessageDedupe("regexp error", s)
return
}
// find anyone saying badstr
// TODO limit by time, not amout of messages...
victimNames := []string{}
// the command itself will be last in the log and caught, exclude that one.
// TODO: except if the command was issued via PM...
for _, m := range b.log[:len(b.log)-1] {
// don't nuke mods.
if isMod(m.Sender) {
continue
}
var isBad bool
if isRegexNuke {
isBad = badregexp.MatchString(m.Message)
} else {
isBad = strings.Contains(m.Message, badstr)
}
if isBad {
// TODO dont collect duplicates...
// collect names in case we want to revert nuke
victimNames = append(victimNames, m.Sender.Nick)
log.Printf("[##] Nuking '%s' because of message '%s' with nuke '%s'\n",
m.Sender.Nick, m.Message, badstr)
// TODO duration, -1 means server default
s.SendMute(m.Sender.Nick, -1)
}
// TODO print/send summary?
}
if b.lastNukeVictims == nil {
b.lastNukeVictims = []string{}
}
// combine array so we are able to undo all past nukes at once, if necessary
b.lastNukeVictims = append(b.lastNukeVictims, victimNames...)
}
func (b *bot) sudoku(m dggchat.Message, s *dggchat.Session) {
if !strings.HasPrefix(m.Message, "!sudoku") {
return
}
// TODO duration, -1 means server default
s.SendMute(m.Sender.Nick, -1)
}
// !aegis - undo (all) past nukes
func (b *bot) aegis(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!aegis") || b.lastNukeVictims == nil {
return
}
for _, nick := range b.lastNukeVictims {
s.SendUnmute(nick)
}
b.lastNukeVictims = nil
}
// !rename - change a chatter's username
func (b *bot) rename(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!rename") {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) < 3 {
return
}
oldName := parts[1]
newName := parts[2]
err := b.renameUser(oldName, newName)
if err != nil {
msg := fmt.Sprintf("'%s' to '%s' by %s failed with '%s'",
oldName, newName, m.Sender.Nick, err.Error())
log.Printf("[##] rename: %s\n", msg)
s.SendPrivateMessage(m.Sender.Nick, msg)
b.sendMessageDedupe("rename error, check logs", s)
return
}
log.Printf("[##] rename: '%s' to '%s' by '%s' success!\n",
oldName, newName, m.Sender.Nick)
b.sendMessageDedupe(fmt.Sprintf("name changed, %s please reconnect", oldName), s)
}
// !say - say a message
func (b *bot) say(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!say") {
return
}
// message itself can contain spaces
parts := strings.SplitN(m.Message, " ", 2)
if len(parts) != 2 {
return
}
b.sendMessageDedupe(parts[1], s)
}
// !mute - mute a chatter for a given time
func (b *bot) mute(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!mute") {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) < 2 {
return
}
var duration time.Duration = -1
if len(parts) >= 3 {
dur, err := time.ParseDuration(parts[2])
if err != nil {
log.Printf("failed to parse duration %q: %v. Using default time", parts[2], err)
} else {
duration = dur
}
}
s.SendMute(parts[1], duration)
}
// !unmute - unmute a chatter
func (b *bot) unmute(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!unmute") {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) < 2 {
return
}
s.SendUnmute(parts[1])
}
// !addcommand command response
func (b *bot) addCommand(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!addcommand") {
return
}
// message itself can contain spaces
parts := strings.Split(m.Message, " ")
if len(parts) < 3 {
return
}
cmnd := parts[1]
if !strings.HasPrefix(cmnd, "!") {
cmnd = "!" + cmnd
}
resp := strings.Join(parts[2:], " ")
mutex.Lock()
defer mutex.Unlock()
// TODO workaround to enable deletion
if resp == "_" {
delete(commands, cmnd)
b.sendMessageDedupe("deleted commands if it existed", s)
} else {
commands[cmnd] = resp
success := saveStaticCommands()
if success {
b.sendMessageDedupe(fmt.Sprintf("added new command %s", cmnd), s)
return
}
b.sendMessageDedupe("failed saving command, check logs", s)
}
}
// TOOD clean up...
func isCommunityStream(path string) bool {
// "/twitch/test" it not. "/memer" is.
return strings.Count(path, "/") == 1 || strings.Contains(path, "angelthump")
}
// !stream or !strim(s) -- show top streams in chat
func (b *bot) printTopStreams(m dggchat.Message, s *dggchat.Session) {
if !strings.HasPrefix(m.Message, "!stream") && !strings.HasPrefix(m.Message, "!strim") {
return
}
sd, err := b.getStreamList()
if err != nil {
log.Printf("%v\n", err)
b.sendMessageDedupe("error getting api data", s)
return
}
// filter hidden streams
allStreams := sd.StreamList
filteredStreams := streamData{}
for _, v := range allStreams {
if !v.Hidden {
filteredStreams.StreamList = append(filteredStreams.StreamList, v)
}
}
// handle case that less than 3 streams are being watched...
maxlen := len(filteredStreams.StreamList)
if maxlen == 0 {
b.sendMessageDedupe("no streams are being watched", s)
return
}
if maxlen > 3 {
maxlen = 3
}
alreadyPrinted := 0
// - assumption: API gives json data sorted by "rustlers".
// - first pass: give community streams preference
// - data.URL has leading slash
for i := 0; i < len(filteredStreams.StreamList) && alreadyPrinted < maxlen; i++ {
data := filteredStreams.StreamList[i]
if isCommunityStream(data.URL) {
nsfw := ""
if data.Nsfw {
nsfw = " [nsfw]"
}
out := fmt.Sprintf("%d %s%s%s", data.Rustlers, websiteURL, data.URL, nsfw)
b.sendMessageDedupe(out, s)
alreadyPrinted++
}
}
// TODO clean me up...
for i := 0; alreadyPrinted < maxlen; i++ {
data := filteredStreams.StreamList[i]
if !isCommunityStream(data.URL) {
nsfw := ""
if data.Nsfw {
nsfw = " [nsfw]"
}
data := filteredStreams.StreamList[i]
out := fmt.Sprintf("%d %s%s%s", data.Rustlers, websiteURL, data.URL, nsfw)
b.sendMessageDedupe(out, s)
alreadyPrinted++
}
}
}
func parseModifiers(s []string) (streamModifier, error) {
var sm streamModifier
for _, part := range s {
switch part {
case "nsfw":
sm.Nsfw = "true"
case "!nsfw":
sm.Nsfw = "false"
case "hidden":
sm.Hidden = "true"
case "!hidden":
sm.Hidden = "false"
case "afk":
sm.Afk = "true"
case "!afk":
sm.Afk = "false"
case "promoted":
sm.Promoted = "true"
case "!promoted":
sm.Promoted = "false"
default:
return streamModifier{}, fmt.Errorf("invalid modifier: '%s'", part)
}
}
return sm, nil
}
func (b *bot) modifyStream(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || !strings.HasPrefix(m.Message, "!modify") {
return
}
// parts[2:], ...
// !modify youtube/memes nsfw !hidden ...
parts := strings.Split(m.Message, " ")
if len(parts) < 3 {
return
}
sm, err := parseModifiers(parts[2:])
if err != nil {
b.sendMessageDedupe(fmt.Sprintf("%s %s", err.Error(), ominousEmote), s)
return
}
identifier := parts[1]
err = b.setStreamAttributes(identifier, sm)
if err != nil {
log.Printf("[##] modify: '%s' with modifier '%+v' by '%s' failed with '%s'\n",
identifier, sm, m.Sender.Nick, err.Error())
// TODO chat message less verbose
b.sendMessageDedupe(fmt.Sprintf("modify: %s %s", err, ominousEmote), s)
return
}
log.Printf("[##] modify: '%s' with modifier '%+v' by '%s' success!\n",
identifier, sm, m.Sender.Nick)
b.sendMessageDedupe(fmt.Sprintf("modify success %s", ominousEmote), s)
}
// !check ATusername
func (b *bot) checkAT(m dggchat.Message, s *dggchat.Session) {
if !strings.HasPrefix(m.Message, "!check") {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) != 2 {
return
}
username := parts[1]
atd, err := b.getATUserData(username)
if err != nil {
log.Printf("[##] checkAT error1: '%s'\n",
err.Error())
// workaround... depends on content of error message
if strings.Contains(err.Error(), "404") {
log.Printf("[##] check: not found\n")
return
}
b.sendMessageDedupe("error getting api data", s)
return
}
// additionally check strim data
sd, err := b.getStreamList()
if err != nil {
log.Printf("[##] checkAT error2: '%s'\n",
err.Error())
b.sendMessageDedupe("error getting api data", s)
return
}
var url string
viewerCount := 0
for _, strim := range sd.StreamList {
if strim.Service == "angelthump" && strings.EqualFold(strim.Channel, username) {
viewerCount = strim.Rustlers
url = fmt.Sprintf("%s%s", websiteURL, strim.URL)
if strim.Hidden {
log.Printf("[##] check: not found\n")
return
}
}
}
// might be live on AT, but no rustlers: disregard.
if viewerCount == 0 {
log.Printf("[##] check: not found\n")
return
}
output := fmt.Sprintf("%s is live for %s with %d rustlers and %d viewers at %s",
atd.User.Username, humanizeDuration(time.Since(atd.CreatedAt)),
viewerCount, atd.ViewerCount, url)
if atd.User.Nsfw {
output += " nsfw"
}
b.sendMessageDedupe(output, s)
}
// !(un)drop atUser
func (b *bot) dropAT(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || (!strings.HasPrefix(m.Message, "!drop") && !strings.HasPrefix(m.Message, "!undrop")) {
return
}
parts := strings.SplitN(m.Message, " ", 3)
if len(parts) < 2 {
return
}
doBan := parts[0] == "!drop"
username := parts[1]
reason := ""
if doBan && len(parts) < 3 {
s.SendPrivateMessage(m.Sender.Nick,
fmt.Sprintf("%s - please provide a ban reason", m.Sender.Nick))
return
}
if doBan {
reason = parts[2]
}
reply, err := b.banATuser(username, reason, doBan)
if err != nil {
log.Println(fmt.Sprintf("[##] drop error: '%s'", err.Error()))
return
}
// b.sendMessageDedupe(reply, s)
s.SendPrivateMessage(m.Sender.Nick, reply)
}
// https://gist.github.com/harshavardhana/327e0577c4fed9211f65
func humanizeDuration(duration time.Duration) string {
days := int64(duration.Hours() / 24)
hours := int64(math.Mod(duration.Hours(), 24))
minutes := int64(math.Mod(duration.Minutes(), 60))
// seconds := int64(math.Mod(duration.Seconds(), 60))
chunks := []struct {
singularName string
amount int64
}{
{"day", days},
{"hour", hours},
{"min", minutes},
//{"sec", seconds},
}
parts := []string{}
for _, chunk := range chunks {
switch chunk.amount {
case 0:
continue
case 1:
parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.singularName))
default:
parts = append(parts, fmt.Sprintf("%d%ss", chunk.amount, chunk.singularName))
}
}
return strings.Join(parts, " ")
}
// !(un)ban -- ban a user
func (b *bot) ban(m dggchat.Message, s *dggchat.Session) {
if !isMod(m.Sender) || (!strings.HasPrefix(m.Message, "!ban") && !strings.HasPrefix(m.Message, "!unban")) {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) < 2 {
return
}
if parts[0] == "!ban" {
reason := ""
if len(parts) == 3 {
reason = parts[2]
}
s.SendBan(parts[1], reason, 0, false)
} else if parts[0] == "!unban" {
s.SendUnban(parts[1])
}
}
var errInputFormat = errors.New("invalid input format")
var errInputBounds = errors.New("input out of bounds")
var errResultRangeBounds = errors.New("result range out of bounds")
func computeRoll(input string) (int, error) {
// Define a regular expression to extract dice rolling information
regexPattern := `^!rolls?\s+(\d+)(?:d(\d+))?\s*([+\-]\s*\d+)?`
regex := regexp.MustCompile(regexPattern)
// Match the regular expression against the input string
matches := regex.FindStringSubmatch(input)
if matches == nil {
return 0, fmt.Errorf("%w: %s", errInputFormat, input)
}
// Extract matched values
numDice, _ := strconv.Atoi(matches[1])
numSides, _ := strconv.Atoi(matches[2])
if matches[2] == "" {
numSides = numDice
numDice = 1
}
modifier, _ := strconv.Atoi(matches[3])
checkMod := modifier != 0
if numSides <= 0 || numDice <= 0 || numDice > 1000 {
return 0, errInputBounds
}
if math.MaxInt64/numSides < numDice ||
(modifier > 0 && math.MaxInt64-numSides*numDice < modifier) ||
(modifier < 0 && math.MinInt64+numSides*numDice > modifier) {
return 0, errResultRangeBounds
}
// Roll the dice
result := 0
for i := 0; i < numDice; i++ {
result += rand.Intn(numSides) + 1
}
// Apply the modifier if present
if checkMod {
result += modifier
}
return result, nil
}
// !roll sides [count] - roll dice
func (b *bot) roll(m dggchat.Message, s *dggchat.Session) {
if !strings.HasPrefix(m.Message, "!roll") {
return
}
parts := strings.Split(m.Message, " ")
if len(parts) < 2 {
return
}
var sum, err = computeRoll(m.Message)
if err != nil {
return
}
b.sendMessageDedupe(fmt.Sprintf("%s rolled %d", m.Sender.Nick, sum), s)
}