60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package bot
|
|
|
|
import (
|
|
"log"
|
|
"velox-bot/internal/commands"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
)
|
|
|
|
type Bot struct {
|
|
Session *discordgo.Session
|
|
AppID string
|
|
GuildID string
|
|
Commands []*discordgo.ApplicationCommand
|
|
registeredCommands []*discordgo.ApplicationCommand
|
|
}
|
|
|
|
func NewBot(token, appID, guildID string, cmds []*discordgo.ApplicationCommand) (*Bot, error) {
|
|
session, err := discordgo.New("Bot " + token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &Bot{
|
|
Session: session,
|
|
AppID: appID,
|
|
GuildID: guildID,
|
|
Commands: cmds,
|
|
}, nil
|
|
}
|
|
|
|
func (b *Bot) Start() error {
|
|
if err := b.Session.Open(); err != nil {
|
|
return err
|
|
}
|
|
|
|
b.registeredCommands = make([]*discordgo.ApplicationCommand, len(b.Commands))
|
|
for _, cmd := range b.Commands {
|
|
created, err := b.Session.ApplicationCommandCreate(b.AppID, b.GuildID, cmd)
|
|
if err != nil {
|
|
log.Printf("Cannot create '%v' command: %v", cmd.Name, err)
|
|
continue
|
|
}
|
|
b.registeredCommands = append(b.registeredCommands, created)
|
|
}
|
|
|
|
b.Session.AddHandler(commands.HandleInteraction)
|
|
return nil
|
|
|
|
}
|
|
|
|
func (b *Bot) Close() error {
|
|
for _, cmd := range b.registeredCommands {
|
|
if err := b.Session.ApplicationCommandDelete(b.AppID, b.GuildID, cmd.ID); err != nil {
|
|
log.Printf("cannot delete '%s' command: %v", cmd.Name, err)
|
|
}
|
|
}
|
|
return b.Session.Close()
|
|
}
|