-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
198 lines (158 loc) · 4.29 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
"github.com/joho/godotenv"
)
const (
errCacheEmpty = "There are currently no servers in the cache, please wait a moment and try again."
)
var (
config = &Config{}
extractIPRegex = regexp.MustCompile(`([a-fA-F:.0-9]{7,40}):(\d+)`)
)
type ipPort struct {
IP string
Port string
}
func init() {
env, err := godotenv.Read(".env")
if err != nil {
log.Fatal(err)
}
discordToken := env["DISCORD_TOKEN"]
if discordToken == "" {
log.Fatal("error: no DISCORD_TOKEN specified")
}
config, err = NewBotConfig(discordToken)
if err != nil {
log.Fatal(err)
}
config.Admin = env["DISCORD_ADMIN"]
config.DefaultGameTypeFilter = strings.ToLower(strings.TrimSpace(env["DEFAULT_GAMETYPE_FILTER"]))
fileName := ""
flag.StringVar(&fileName, "f", "", "pass the file that contains the IPs that the bot is allowed to ping for infos.")
flag.Parse()
if fileName == "" {
flag.Usage()
log.Fatal("")
}
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
config.FilePath = fileName
addressSet := make(map[ipPort]bool, 1)
sc := bufio.NewScanner(file)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if strings.HasPrefix(line, "#") {
continue
}
matches := extractIPRegex.FindStringSubmatch(line)
if len(matches) != 3 {
log.Printf("'%s' invalid line format, skipping..\n", line)
continue
}
address := ipPort{matches[1], matches[2]}
addressSet[address] = true
}
config.ServerList = NewConcurrentServerList(len(addressSet))
for addr := range addressSet {
// validate IP
ip := net.ParseIP(addr.IP)
if ip == nil {
log.Printf("invalid IP '%s', with port '%s", ip, addr.Port)
continue
}
// validate Port
port, err := strconv.Atoi(addr.Port)
if err != nil || port < 1024 {
log.Printf("invalid port '%d', with IP '%s", port, ip)
continue
}
// add server to list
config.ServerList.Add(fmt.Sprintf("%s:%d", ip, port))
}
responseTimeoutMsStr := env["SERVER_RESPONSE_TIMEOUT_MS"]
responseTimeoutMs, err := strconv.Atoi(responseTimeoutMsStr)
if err != nil || responseTimeoutMs < 5 {
responseTimeoutMs = 500
}
config.ResponseTimeout = time.Millisecond * time.Duration(responseTimeoutMs)
config.DiscordSession.AddHandler(DiscordMessageCreateHandler)
}
// DiscordMessageLineCreateHandler checks every line for commands
func DiscordMessageLineCreateHandler(s *discordgo.Session, m *discordgo.MessageCreate, line string) {
if !strings.HasPrefix(line, "!") {
return
}
ss := strings.SplitN(line[1:], " ", 2)
if len(ss) == 0 {
return
}
command := strings.ToLower(ss[0])
arguments := ""
if len(ss) > 1 {
arguments = strings.TrimSpace(ss[1])
}
switch command {
case "h", "help":
HelpHandler(s, m, arguments)
case "o", "online":
OnlineHandler(s, m, arguments)
case "s", "servers":
ServersHandler(s, m, arguments)
case "add":
AdminMessageCreateMiddleware(AddHandler)(s, m, arguments)
case "save":
AdminMessageCreateMiddleware(SaveHandler)(s, m, arguments)
case "delete":
AdminMessageCreateMiddleware(DeleteHandler)(s, m, arguments)
case "c", "clean", "clear":
AdminMessageCreateMiddleware(ClearHandler)(s, m, arguments)
default:
return
}
}
// DiscordMessageCreateHandler handles server messages sent by users.
func DiscordMessageCreateHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}
lines := strings.Split(m.Content, "\n")
for _, line := range lines {
DiscordMessageLineCreateHandler(s, m, line)
// only the admin is allowed to execute multiple commands at once.
if m.Author.String() != config.Admin {
break
}
}
}
func main() {
err := config.Open()
if err != nil {
log.Fatalf("error: could not establish a connection to the discord api, please check your credentials")
}
defer config.Close()
// Wait here until CTRL-C or other term signal is received.
log.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
<-sc
log.Println("Shutting down, please wait...")
}