-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (90 loc) · 2.19 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
package main
import (
"context"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/corentings/stouuf-bot/commands"
"github.com/corentings/stouuf-bot/database"
"github.com/joho/godotenv"
"log"
"os"
"os/signal"
)
var (
Token string
GuildID string
)
func loadVar() {
// Load the .env file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
Token = os.Getenv("TOKEN")
GuildID = os.Getenv("GUILD_ID")
}
func init() {
loadVar()
}
func main() {
// Try to connect to the database
if err := database.Connect(); err != nil {
log.Panic("Can't connect database:", err.Error())
}
log.Println("Connected to database successfully")
defer func() {
fmt.Println("Disconnect from database")
err := database.Mg.Client.Disconnect(context.TODO())
if err != nil {
return
}
}()
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + Token)
if err != nil {
log.Println("error creating Discord session,", err)
return
}
dg.Identify.Presence = discordgo.GatewayStatusUpdate{
Game: discordgo.Activity{
Name: "By CorentinGS",
Type: discordgo.ActivityTypeCompeting,
},
}
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
log.Println("error opening connection,", err)
return
}
commandHandlers := commands.GetCommandHandlers()
dg.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
appCommands := commands.GetCommands()
_, err = dg.ApplicationCommandBulkOverwrite(dg.State.User.ID, GuildID, appCommands)
if err != nil {
log.Panicf("Error overwriting commands: %v", err)
}
defer func(dg *discordgo.Session) {
err := dg.Close()
if err != nil {
return
}
}(dg)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Println("Press Ctrl+C to exit")
<-stop
if true {
log.Println("Removing commands...")
_, err := dg.ApplicationCommandBulkOverwrite(dg.State.User.ID, GuildID, nil)
if err != nil {
log.Panicf("Cannot delete a command: %v", err)
}
log.Println("Removed commands")
}
log.Println("Gracefully shutting down.")
}