-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
80 lines (62 loc) · 2.01 KB
/
bot.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
package discog
import (
"log"
"os"
"os/signal"
"github.com/bwmarrin/discordgo"
)
// Bot is the main struct for interacting with Discord. It holds the bot's token and command manager.
type Bot struct {
token string
CommandManager *CommandManager
Session *discordgo.Session
}
// NewBot creates a new Bot with the provided token and command manager.
func NewBot(token string, manager *CommandManager) (*Bot, error) {
session, err := discordgo.New("Bot " + token)
if err != nil {
return nil, err
}
session.Identify.Intents = discordgo.IntentsAllWithoutPrivileged
return &Bot{token: "Bot " + token, Session: session, CommandManager: manager}, nil
}
// Run starts the Discord bot with the provided callback function.
func (b *Bot) Run(callback func(session *discordgo.Session, err error)) {
err := b.Session.Open()
if err != nil {
callback(nil, err)
return
}
callback(b.Session, nil)
b.CommandManager.register(b)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
b.CommandManager.unregister(b)
log.Println("Graceful shutdown")
}
// OnReady is a callback function that is called when the bot is ready. It logs the bot's status and registers the interaction handlers.
func (b *Bot) OnReady(callback func(r *discordgo.Ready)) {
b.Session.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
callback(r)
})
if len(b.CommandManager.groups) != 0 {
b.Session.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Interaction.Type == discordgo.InteractionModalSubmit && b.CommandManager.modalHandler != nil {
ctx := newCtx(s, i)
b.CommandManager.modalHandler(ctx)
return
}
if i.Interaction.Type == discordgo.InteractionMessageComponent && b.CommandManager.messageComponentHandler != nil {
ctx := newCtx(s, i)
b.CommandManager.messageComponentHandler(ctx)
return
}
handler := b.CommandManager.FindCommand(i.ApplicationCommandData().Name)
if handler != nil {
ctx := newCtx(s, i)
handler(ctx)
}
})
}
}