forked from kubastick/MC-Server-Status-Discord-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (81 loc) · 1.99 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
package main
import (
"fmt"
"github.com/bwmarrin/discordgo"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var (
config = loadConfig()
)
func main() {
configureLogger()
session := connectToDiscord(config.DiscordSecret)
session.AddHandler(messageRouter)
go postServerCountToDiscordBotAPI(session)
go statusLoop(session)
defer session.Close()
log.Println("Minecraft status bot is ready!")
// Wait for something that look like sigkill
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
log.Println("Received SIGKILL, exiting")
}
func connectToDiscord(secret string) *discordgo.Session {
discord, err := discordgo.New("Bot " + secret)
if err != nil {
log.Fatalf("Failed to connect, reasen: %s", err.Error())
}
err = discord.Open()
if err != nil {
log.Fatalf("Fatal to establish websocket connection with discord.io, reason: %s", err.Error())
}
return discord
}
func messageRouter(s *discordgo.Session, m *discordgo.MessageCreate) {
// Do not parse own and bot messages
if s.State.User.ID == m.Author.ID || m.Author.Bot {
return
}
// Get content of message
userMessage := m.Content
// Commands routing
if strings.HasPrefix(userMessage, "!status ") {
handleStatus(s, m)
}
if strings.HasPrefix(userMessage, "!ping") {
handlePing(s, m)
}
if strings.HasPrefix(userMessage, "!help") {
handleHelp(s, m)
}
}
func configureLogger() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func statusLoop(s *discordgo.Session) {
if config.DisableStatus {
log.Println("Status has been disabled in config file")
return
}
for {
log.Println("Updating status")
statusData := discordgo.UpdateStatusData{
Status: "online",
Game: &discordgo.Game{
Type: discordgo.GameTypeWatching,
Name: fmt.Sprintf("%d servers", len(s.State.Guilds)),
},
}
err := s.UpdateStatusComplex(statusData)
if err != nil {
log.Println("Warning, failed to update discord status")
}
time.Sleep(5 * time.Minute)
}
}