-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
323 lines (264 loc) · 8.6 KB
/
main.go
File metadata and controls
323 lines (264 loc) · 8.6 KB
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
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
"github.com/go-co-op/gocron"
_ "github.com/lib/pq"
)
var (
token string
verbose bool
httpPort int
guildID string
modChannelID string
databaseHost string
databaseUser string
databasePass string
urlRegex *regexp.Regexp
db *sql.DB
discord *discordgo.Session
commandMap = make(map[string]commandHandler)
messageStreamHandlers = make([]func(*discordgo.Session, *discordgo.MessageCreate), 0)
)
type commandHandler struct {
commandString string
description string
modOnly bool
handleFunc func(*discordgo.Session, *discordgo.MessageCreate)
}
func init() {
token = os.Getenv("VPBOT_TOKEN")
guildID = os.Getenv("VPBOT_GUILD_ID")
modChannelID = os.Getenv("VPBOT_MOD_CHAN_ID")
verbose, _ = strconv.ParseBool(os.Getenv("VPBOT_VERBOSE"))
httpPort, _ = strconv.Atoi(os.Getenv("VPBOT_HTTP_PORT"))
databaseHost = os.Getenv("VPBOT_DB_HOST")
databaseUser = os.Getenv("VPBOT_DB_USER")
databasePass = os.Getenv("VPBOT_DB_PASS")
flag.StringVar(&token, "t", token, "Bot Token")
flag.BoolVar(&verbose, "v", false, "Verbose Output")
flag.IntVar(&httpPort, "p", 13373, "HTTP port")
flag.Parse()
}
func dbPrepare(db *sql.DB, query string) *sql.Stmt {
stmt, err := db.Prepare(query)
if err != nil {
log.Println(err, query)
}
return stmt
}
func main() {
log.SetFlags(log.Lshortfile)
if token == "" {
log.Println("No token provided. Please run: vpbot -t <bot token> or set the VPBOT_TOKEN environment variable")
os.Exit(1)
}
urlRegex, _ = regexp.Compile(urlRegexString)
var err error
db, err = sql.Open("postgres", fmt.Sprintf("host=%s port=5432 user=%s password=%s dbname=vpbot sslmode=disable", databaseHost, databaseUser, databasePass))
if err != nil {
log.Panic(err)
}
cron := gocron.NewScheduler(time.UTC)
discord, err = discordgo.New("Bot " + token)
if err != nil {
fmt.Println("error creating Discord session,", err)
os.Exit(1)
}
discord.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAllWithoutPrivileged | discordgo.IntentsGuildMembers)
log.Println("Opening up connection to discord...")
err = discord.Open()
if err != nil {
fmt.Println("Error opening Discord session: ", err)
os.Exit(1)
}
//NOTE(Hoej): Needs to be after discord.Open()
discord.StateEnabled = true
initPoliceChannel(discord)
initMathSentence(db)
initUserTracking(discord, db, cron)
initIdeasChannel(discord)
initGithubChannel(discord)
//initOdin()
//initMarkov(db, cron)
discord.AddHandler(messageCreate)
discord.AddHandler(discordReady)
discord.AddHandler(ideasQueueReactionAdd)
discord.AddHandler(clonexBanProcedure)
handleCommand("ack", "Will make bot say 'ACK'", false, discordAckHandler)
handleCommand("help", "Will print a message with all available commands to the user", false, helpHandler)
handleCommand("version", "Will print the version of VPBot", false, versionCommandHandler)
handleCommand("usercount", "Post the current user count for this guild", true, userCountCommandHandler)
handleCommand("addidea",
"Suggest an idea to add to the server's idea channel, will go into a manual review queue before being posted",
false,
addIdeasHandler)
handleCommand("addmathsentence",
"Will add a math related sentence that VPBot can say, make sure to make them about hating math",
false,
addMathSentenceHandler)
//handleCommand("odinrun", "Will compile an odin code block and run it", true, odinRunHandle)
//handleCommand("markovsave", "Force a save of the markov chain", true, markovForceSave)
//handleCommand("markovsay", "Force a message generation in markov", false, markovForceSay)
addMessageStreamHandler(msgStreamMathMessageHandler)
addMessageStreamHandler(msgStreamPoliceHandler)
addMessageStreamHandler(msgStreamGithubMessageHandler)
//addMessageStreamHandler(msgStreamMarkovTrainHandler)
//addMessageStreamHandler(msgStreamMarkovSayHandler)
setupHTTP()
log.Printf("Starting HTTP server on port %d...\n", httpPort)
go func() {
err := http.ListenAndServe(fmt.Sprintf(":%d", httpPort), nil)
if err != nil {
panic("Unable to start HTTP server!")
}
}()
log.Println("Starting CRON services...")
cron.StartAsync()
log.Println("VPBot is now running.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, syscall.SIGTERM)
<-sc
log.Println("VPBot is terminating...")
cron.Stop()
_ = discord.Close()
}
func setupHTTP() {
log.Println("Setting up HTTP handlers")
http.HandleFunc("/github-webhook", githubWebhookHandler)
http.HandleFunc("/ack", ackHandler)
}
func ackHandler(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprintf(w, "ACK")
}
func addMessageStreamHandler(handler func(*discordgo.Session, *discordgo.MessageCreate)) {
messageStreamHandlers = append(messageStreamHandlers, handler)
}
func handleCommand(cmdString string,
desc string,
modOnly bool,
handler func(*discordgo.Session, *discordgo.MessageCreate)) {
if _, ok := commandMap[cmdString]; ok == false {
cmdH := commandHandler{
cmdString,
desc,
modOnly,
handler,
}
commandMap[cmdString] = cmdH
} else {
log.Fatalf("Tried adding handler for '%s' when it already has one!", cmdString)
}
}
func discordAckHandler(session *discordgo.Session, msg *discordgo.MessageCreate) {
_, _ = session.ChannelMessageSend(msg.ChannelID, "ACK")
}
func helpHandler(session *discordgo.Session, msg *discordgo.MessageCreate) {
var sb strings.Builder
user := msg.Author
if len(msg.Mentions) > 0 {
user = msg.Mentions[0]
}
sb.WriteString("Following commands are available to ")
sb.WriteString(user.Mention())
sb.WriteString(";\n")
for _, h := range commandMap {
if h.modOnly == false || userAllowedAdminBotCommands(session, msg.GuildID, msg.ChannelID, user.ID) {
if len(h.description) > 0 {
sb.WriteString("`!")
sb.WriteString(h.commandString)
sb.WriteString("` ")
sb.WriteString(h.description)
sb.WriteString("\n")
}
}
}
_, _ = session.ChannelMessageSend(msg.ChannelID, sb.String())
}
func discordReady(s *discordgo.Session, _ *discordgo.Ready) {
activity := discordgo.Activity{
Name: "users for fools, one stupid message at a time",
Type: discordgo.ActivityTypeGame,
URL: "",
}
usd := discordgo.UpdateStatusData{Status: "online", AFK: false, Activities: []*discordgo.Activity{&activity}}
err := s.UpdateStatusComplex(usd)
if err != nil {
fmt.Println("error updating status on discord,", err)
}
}
func clonexBanProcedure(s *discordgo.Session, e *discordgo.GuildMemberAdd) {
if strings.Contains(strings.ToLower(e.User.Username), "clonex") {
err := s.GuildBanCreateWithReason(guildID, e.User.ID, "auto ban cause scam bots for clonex", 7)
if err != nil {
s.ChannelMessageSend(modChannelID, fmt.Sprintf("Unable to ban %v, %v", e.User.Username, err))
} else {
s.ChannelMessageSend(modChannelID, fmt.Sprintf("Auto banned %v", e.User.Username))
}
}
}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
guild, _ := s.State.Guild(m.GuildID)
channel, _ := s.State.Channel(m.ChannelID)
log.Printf("[%s|%s|%s#%s] (%s) %s\n",
guild.Name,
channel.Name,
m.Author.Username,
m.Author.Discriminator,
m.ID,
m.Content)
if strings.HasPrefix(m.Content, "!") {
message := strings.SplitN(m.Content, " ", 2)
cmd := strings.TrimPrefix(message[0], "!")
log.Printf("Trying to find %s command for %s", cmd, m.Author.String())
if handler, ok := commandMap[cmd]; ok {
log.Printf("Found %s command for %s", cmd, m.Author.String())
if handler.modOnly && userAllowedAdminBotCommands(s, m.GuildID, m.ChannelID, m.Author.ID) == false {
log.Printf("User %s tried to use command %s but is not allowed (not a MOD)", m.Author.String(), cmd)
_, _ = s.ChannelMessageSend(m.ChannelID, "Sorry, but we're not that type of friends </3")
return
}
log.Printf("Running %s command handler for %s", cmd, m.Author.String())
handler.handleFunc(s, m)
return
}
}
for _, h := range messageStreamHandlers {
h(s, m)
}
}
func userAllowedAdminBotCommands(s *discordgo.Session, guildID string, channelID string, userID string) bool {
perm, _ := s.UserChannelPermissions(userID, channelID)
if perm&discordgo.PermissionAdministrator != 0 {
return true
}
hasRole := false
member, _ := s.GuildMember(guildID, userID)
if member != nil {
guild, _ := s.State.Guild(guildID)
for _, x := range guild.Roles {
for _, y := range member.Roles {
if x.ID == y {
if x.Name == "Mod" || x.Name == "mod" {
hasRole = true
}
}
}
}
}
return hasRole
}