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
|
package main
import (
"github.com/bwmarrin/discordgo"
"sync"
"os"
"os/signal"
"fmt"
"regexp"
"strings"
)
var (
WORD_REGEX = regexp.MustCompile(`[a-z'’]+`)
mu = sync.RWMutex{}
words = map[string]struct{}{}
channel string
)
func getWords(m *discordgo.Message) []string {
result := WORD_REGEX.FindAllString(strings.ToLower(m.Content), -1)
return result
}
func add(m *discordgo.Message) {
if m.ChannelID != channel || m.Author.Bot {
return
}
mu.Lock()
for _, word := range getWords(m) {
words[word] = struct{}{}
}
mu.Unlock()
}
func report() {
mu.RLock()
fmt.Printf("at %d words now\n", len(words))
mu.RUnlock()
}
func confer(s *discordgo.Session, m *discordgo.Message) {
if m.ChannelID != channel || m.Author.Bot {
return
}
mu.RLock()
abominable := []string{}
for _, word := range getWords(m) {
if _, ok := words[word]; ok {
abominable = append(abominable, word)
}
}
mu.RUnlock()
if len(abominable) > 0 {
builder := strings.Builder{}
for i, abomination := range abominable {
if i > 0 {
builder.WriteString(", ")
}
fmt.Fprintf(&builder, "**%s**", abomination)
}
_, e := s.ChannelMessageSendReply(m.ChannelID, builder.String(), m.Reference())
yell(e)
}
}
func must(e error) {
if e != nil {
panic(e)
}
}
func yell(e error) {
if e != nil {
fmt.Fprintln(os.Stderr, e)
}
}
func respond(session *discordgo.Session, message *discordgo.Message) {
switch message.Type {
case discordgo.MessageTypeDefault, discordgo.MessageTypeReply:
confer(session, message)
go func() {
add(message)
report()
}()
}
}
func main() {
var ok bool
channel, ok = os.LookupEnv("CHANNEL")
if !ok {
panic(ok)
}
session, e := discordgo.New(fmt.Sprintf("Bot %s", os.Getenv("TOKEN")))
must(e)
session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
respond(s, m.Message)
})
session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageUpdate) {
respond(s, m.Message)
})
must(session.Open())
var (
last string
count = 0
)
for {
got, e := session.ChannelMessages(channel, 100, last, "", "")
if e != nil {
yell(e)
continue
}
if len(got) == 0 {
break
}
last = got[len(got)-1].ID
count += len(got)
fmt.Printf("msgs: %d >= %s\n", count, last)
go func() {
for _, m := range got {
add(m)
}
report()
}()
}
fmt.Printf("done! (%d msgs)\n", count)
mu.RLock()
for k := range words {
fmt.Printf("%s ", k)
}
fmt.Println()
mu.RUnlock()
broken := make(chan os.Signal, 1)
signal.Notify(broken, os.Interrupt, os.Kill)
<-broken
must(session.Close())
}
|