-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
220 lines (180 loc) · 6.52 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/sirupsen/logrus"
"github.com/bwmarrin/discordgo"
"github.com/servusdei2018/shards/v2"
)
type config struct {
Token string
}
var (
cfg config
Mgr *shards.Manager
)
func init() {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
fmt.Printf("Error loading .env file: %v\n", err)
}
// Get the BOT_TOKEN from the environment
cfg = config{
Token: os.Getenv("DISCORD_TOKEN"),
}
if cfg.Token == "" {
fmt.Println("DISCORD_TOKEN is required but not set in the environment")
}
}
func main() {
// Create a new router using Gorilla Mux
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://blazium.app", http.StatusMovedPermanently)
})
r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
// Set the content type to application/json
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// Define a health check response structure
response := map[string]string{"status": "healthy"}
// Encode the response as JSON and send it
json.NewEncoder(w).Encode(response)
})
embedHandler := embedMiddleware(r)
corsHandler := enableCORS(embedHandler)
runBotRoutine()
// Start the server
fmt.Println("Starting server on :8080")
err := http.ListenAndServe(":8080", corsHandler)
if err != nil {
logrus.Error("Error starting server:", err)
}
}
func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins, you can restrict this to a specific domain
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle preflight OPTIONS requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// Call the next handler
next.ServeHTTP(w, r)
})
}
func embedMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the User-Agent header and convert it to lowercase for case-insensitive comparison
userAgent := strings.ToLower(r.Header.Get("User-Agent"))
// Check if the User-Agent contains "discordbot" (case-insensitive)
if strings.Contains(userAgent, "discordbot") {
// Set appropriate headers for HTML content and caching
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "max-age=3600") // Cache the response for 1 hour
// Write the Open Graph meta tags for Discord embeds
w.Write([]byte(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta property="og:title" content="Blazium Engine">
<meta property="og:description" content="Blazium Engine forked from Godot.">
<meta property="og:image" content="https://blazium.app/static/assets/logo.png">
<meta property="og:url" content="https://blazium.app">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<meta property="og:site_name" content="Blazium Engine">
<title>Blazium Engine</title>
</head>
<body>
<h1>Welcome to Blazium Engine</h1>
</body>
</html>
`))
return
}
// If the User-Agent is not from Discord, pass the request to the next handler
next.ServeHTTP(w, r)
})
}
func onConnect(s *discordgo.Session, evt *discordgo.Connect) {
fmt.Printf("[INFO] Shard #%v connected.\n", s.ShardID)
}
func messageCreate(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
}
logrus.Debug(m.Content)
// If the message is "ping" reply with "Pong!"
if m.Content == "ping" {
s.ChannelMessageSend(m.ChannelID, "Pong!")
}
// If the message is "pong" reply with "Ping!"
if m.Content == "pong" {
s.ChannelMessageSend(m.ChannelID, "Ping!")
}
// If the message is "restart" restart the shard manager and rescale
// if necessary, all with zero down-time.
if m.Content == "restart" {
var err error
s.ChannelMessageSend(m.ChannelID, "[INFO] Restarting shard manager...")
fmt.Println("[INFO] Restarting shard manager...")
Mgr, err = Mgr.Restart()
if err != nil {
fmt.Println("[ERROR] Error restarting manager,", err)
} else {
s.ChannelMessageSend(m.ChannelID, "[SUCCESS] Manager successfully restarted.")
fmt.Println("[SUCCESS] Manager successfully restarted.")
}
}
}
func runBotRoutine() {
go func() {
logrus.Debug("Launching Bot now...")
// Create a new Discord session using the provided bot token.
Mgr, err := shards.New("Bot " + cfg.Token)
if err != nil {
fmt.Println("[ERROR] Error creating manager,", err)
return
}
logrus.Debug("Bot Launched...")
// Register the messageCreate func as a callback for MessageCreate events.
Mgr.AddHandler(messageCreate)
// Register the onConnect func as a callback for Connect events.
Mgr.AddHandler(onConnect)
// In this example, we only care about receiving message events.
Mgr.RegisterIntent(discordgo.IntentsGuildMessages)
fmt.Println("[INFO] Starting shard manager...")
// Open a websocket connection to Discord and begin listening.
err = Mgr.Start()
if err != nil {
fmt.Println("[ERROR] Error starting manager,", err)
return
}
// Wait here until CTRL-C or other term signal is received.
fmt.Println("[SUCCESS] Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// Cleanly close down the Discord session.
fmt.Println("[INFO] Stopping shard manager...")
Mgr.Shutdown()
fmt.Println("[SUCCESS] Shard manager stopped. Bot is shut down.")
}()
}