85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
package discord
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
"github.com/leolionad58/ticketbot/internal/config"
|
|
"github.com/leolionad58/ticketbot/internal/db"
|
|
)
|
|
|
|
type Bot struct {
|
|
Session *discordgo.Session
|
|
Config *config.Provider
|
|
Tickets *db.TicketRepo
|
|
Claims *db.ClaimMessageRepo
|
|
GuildID string
|
|
AllowedGuilds map[string]bool // set of allowed guild IDs; if empty, all guilds allowed
|
|
}
|
|
|
|
func New(token string, cfg *config.Provider, tickets *db.TicketRepo, claims *db.ClaimMessageRepo, guildID string, allowedGuilds []string) (*Bot, error) {
|
|
s, err := discordgo.New("Bot " + token)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create session: %w", err)
|
|
}
|
|
s.Identify.Intents = discordgo.IntentsGuilds |
|
|
discordgo.IntentsGuildMembers |
|
|
discordgo.IntentsGuildMessages |
|
|
discordgo.IntentsMessageContent
|
|
|
|
allowed := make(map[string]bool, len(allowedGuilds))
|
|
for _, id := range allowedGuilds {
|
|
if id != "" {
|
|
allowed[id] = true
|
|
}
|
|
}
|
|
return &Bot{
|
|
Session: s,
|
|
Config: cfg,
|
|
Tickets: tickets,
|
|
Claims: claims,
|
|
GuildID: guildID,
|
|
AllowedGuilds: allowed,
|
|
}, nil
|
|
}
|
|
|
|
func (b *Bot) IsGuildAllowed(guildID string) bool {
|
|
if len(b.AllowedGuilds) == 0 {
|
|
return true
|
|
}
|
|
return b.AllowedGuilds[guildID]
|
|
}
|
|
|
|
func (b *Bot) Open() error {
|
|
return b.Session.Open()
|
|
}
|
|
|
|
func (b *Bot) Close() {
|
|
b.Session.Close()
|
|
}
|
|
|
|
func (b *Bot) RegisterCommands(appID string) error {
|
|
cmds := ApplicationCommands()
|
|
for guildID := range b.AllowedGuilds {
|
|
for _, cmd := range cmds {
|
|
_, err := b.Session.ApplicationCommandCreate(appID, guildID, cmd)
|
|
if err != nil {
|
|
return fmt.Errorf("register %s in guild %s: %w", cmd.Name, guildID, err)
|
|
}
|
|
slog.Info("registered command", "name", cmd.Name, "guild_id", guildID)
|
|
}
|
|
}
|
|
// If no allowed guilds configured, register globally (or in default guild)
|
|
if len(b.AllowedGuilds) == 0 {
|
|
for _, cmd := range cmds {
|
|
_, err := b.Session.ApplicationCommandCreate(appID, b.GuildID, cmd)
|
|
if err != nil {
|
|
return fmt.Errorf("register %s: %w", cmd.Name, err)
|
|
}
|
|
slog.Info("registered command", "name", cmd.Name)
|
|
}
|
|
}
|
|
return nil
|
|
}
|