-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
236 lines (215 loc) · 6.21 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main
import (
"context"
"database/sql"
"fmt"
"io"
"net/url"
"os"
"os/signal"
"path/filepath"
"plugin"
"runtime"
"slices"
"strconv"
"syscall"
"time"
_ "github.com/lib/pq"
"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/bot"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/gateway"
"github.com/joho/godotenv"
"github.com/sirupsen/logrus"
"github.com/vaporvee/acecore/log2webhook"
"github.com/vaporvee/acecore/shared"
"github.com/vaporvee/acecore/web"
)
var (
db *sql.DB
)
var pluginNames []string
func main() {
logrusInitFile()
var err error
godotenv.Load()
connStr := "postgresql://" + os.Getenv("DB_USER") + ":" + url.QueryEscape(os.Getenv("DB_PASSWORD")) + "@" + os.Getenv("DB_SERVER") + ":" + string(os.Getenv("DB_PORT")) + "/" + os.Getenv("DB_NAME") + "?sslmode=disable&application_name=Discord Bot"
db, err = sql.Open("postgres", connStr)
if err != nil {
logrus.Fatal(err)
}
err = loadPlugins("plugins/")
if err != nil {
logrus.Warn(err)
}
shared.BotConfigs = append(shared.BotConfigs,
bot.WithEventListenerFunc(applicationCommandInteractionCreate),
bot.WithEventListenerFunc(autocompleteInteractionCreate),
bot.WithEventListenerFunc(componentInteractionCreate),
bot.WithEventListenerFunc(modalSubmitInteractionCreate),
bot.WithGatewayConfigOpts(
gateway.WithIntents(
gateway.IntentGuilds,
gateway.IntentGuildEmojisAndStickers,
gateway.IntentGuildMessages,
gateway.IntentGuildMembers,
gateway.IntentDirectMessages,
),
))
client, err := disgo.New(os.Getenv("BOT_TOKEN"),
shared.BotConfigs...,
)
if err != nil {
logrus.Fatal("error creating Discord session,", err)
return
} else {
logrus.Info("Discord session created")
}
if err = client.OpenGateway(context.TODO()); err != nil {
logrus.Error("error opening connection,", err)
return
}
app, err := client.Rest().GetCurrentApplication()
if err != nil {
logrus.Error(err)
}
logrus.Infof("Bot is now running as '%s'!", app.Bot.Username)
registerCommands(client)
go web.HostRoutes(app.Bot.ID.String())
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
logrus.Info("Shutting down...")
}
func registerCommands(c bot.Client) {
logrus.Info("Starting up...")
removeOldCommandFromAllGuilds(c)
var existingCommandNames []string
existingCommands, err := c.Rest().GetGlobalCommands(c.ApplicationID(), false)
if err != nil {
logrus.Errorf("error fetching existing global commands: %v", err)
} else {
for _, existingCommand := range existingCommands {
existingCommandNames = append(existingCommandNames, existingCommand.Name())
}
}
globalCommands := []discord.ApplicationCommandCreate{}
for _, command := range commands {
if !slices.Contains(existingCommandNames, command.Definition.CommandName()) || slices.Contains(os.Args, "--update-all") || slices.Contains(os.Args, "--clean") {
globalCommands = append(globalCommands, command.Definition)
logrus.Infof("Appending command \"%s\"", command.Definition.CommandName())
}
}
if len(globalCommands) > 0 {
logrus.Infof("Attempting to add global commands %s", fmt.Sprint(globalCommands))
_, err = c.Rest().SetGlobalCommands(c.ApplicationID(), globalCommands)
if err != nil {
logrus.Errorf("error creating global commands '%s'", err)
} else {
logrus.Infof("Added global commands sucessfully!")
}
}
logrus.Info("Successfully started the Bot!")
}
func removeOldCommandFromAllGuilds(c bot.Client) {
app, err := c.Rest().GetCurrentApplication()
if err != nil {
logrus.Error(err)
}
globalCommands, err := c.Rest().GetGlobalCommands(app.Bot.ID, false)
if err != nil {
logrus.Errorf("error fetching existing global commands: %v", err)
return
}
var commandNames []string
for _, command := range commands {
commandNames = append(commandNames, command.Definition.CommandName())
}
for _, existingCommand := range globalCommands {
if !slices.Contains(commandNames, existingCommand.Name()) {
logrus.Infof("Deleting command '%s'", existingCommand.Name())
err := c.Rest().DeleteGlobalCommand(c.ApplicationID(), existingCommand.ID())
if err != nil {
logrus.Errorf("error deleting command %s: %v", existingCommand.Name(), err)
}
}
}
}
func logrusInitFile() {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetReportCaller(true)
timestamp := time.Now().Unix()
var file_name string = "logs/bot." + strconv.FormatInt(timestamp, 10) + ".log"
if _, err := os.Stat("logs"); os.IsNotExist(err) {
err := os.Mkdir("logs", 0755)
if err != nil {
logrus.Error(err)
return
}
}
log, err := os.OpenFile(file_name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
logrus.Error(err)
return
}
mw := io.MultiWriter(os.Stdout, log, &log2webhook.WebhookWriter{})
logrus.SetOutput(mw)
}
func loadPlugins(directory string) error {
files, err := os.ReadDir(directory)
if err != nil {
return err
}
// Determine the appropriate file extension for dynamic libraries
var ext string
switch runtime.GOOS {
case "windows":
ext = ".dll"
case "linux":
ext = ".so"
case "darwin":
ext = ".dylib"
default:
return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
}
for _, file := range files {
if filepath.Ext(file.Name()) == ext {
p, err := plugin.Open(filepath.Join(directory, file.Name()))
if err != nil {
return err
}
symPlugin, err := p.Lookup("Plugin")
if err != nil {
logrus.Errorf("Error looking up symbol 'Plugin' in %s: %v", file.Name(), err)
continue
}
pluginPtr, ok := symPlugin.(**shared.Plugin)
if !ok {
logrus.Errorf("Plugin does not match expected type")
continue
}
plugin := *pluginPtr
if plugin.Name == "" {
logrus.Warn("Plugin is unnamed")
pluginNames = append(pluginNames, "UNNAMED PLUGIN")
} else {
pluginNames = append(pluginNames, plugin.Name)
}
if plugin.Commands != nil {
commands = append(commands, plugin.Commands...)
} else {
logrus.Errorf("Plugin %s has no commands set", plugin.Name)
continue
}
if plugin.Init != nil {
err = plugin.Init(db)
if err != nil {
logrus.Errorf("Error running plugin register %s function: %v", plugin.Name, err)
continue
}
}
}
}
return nil
}