papibot/pkg/bot/bot.go

98 lines
2.1 KiB
Go

package bot
import (
"fmt"
"log"
dg "github.com/bwmarrin/discordgo"
)
type Bot struct {
token string
appId string
isPlaying bool
session *dg.Session
slashCommands map[string]func(s *dg.Session, i *dg.InteractionCreate)
}
func New(token, appId string) *Bot {
return &Bot{
token: token,
appId: appId,
slashCommands: make(map[string]func(s *dg.Session, i *dg.InteractionCreate)),
}
}
// TODO: Let's get some custom error types going
// at some point
func (b *Bot) Start() error {
var err error
b.session, err = dg.New(fmt.Sprintf("Bot %s", b.token))
if err != nil {
return err
}
b.session.AddHandler(b.ready)
b.session.Identify.Intents = dg.IntentsGuilds | dg.IntentsGuildMessages | dg.IntentsGuildVoiceStates
err = b.session.Open()
if err != nil {
return err
}
// Register slash commands
b.session.AddHandler(b.handleSlashCommand)
return nil
}
// TODO: Don't hard code the server. We can
// register the commands globally
func (b *Bot) Stop() {
cmds, _ := b.session.ApplicationCommands(b.appId, "338782945110392832")
for _, cmd := range cmds {
b.session.ApplicationCommandDelete(b.appId, "338782945110392832", cmd.ID)
}
b.session.Close()
}
func (b *Bot) AddSlashCommand(name string, handler func(*dg.Session, *dg.InteractionCreate)) {
b.slashCommands[name] = handler
}
func (b *Bot) handleSlashCommand(s *dg.Session, i *dg.InteractionCreate) {
log.Println("Command received?")
if h, ok := b.slashCommands[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
}
func (b *Bot) ready(s *dg.Session, event *dg.Ready) {
commands := []*dg.ApplicationCommand{
{
Name: "play",
Description: "Play a song from youtube, spotify, apple music, etc",
Options: []*dg.ApplicationCommandOption{
{
Type: dg.ApplicationCommandOptionString,
Name: "url",
Description: "URL to the song",
Required: true,
},
},
},
}
log.Println("Bot is ready")
log.Println("Bulk registering commands")
_, err := s.ApplicationCommandBulkOverwrite(b.appId, "338782945110392832", commands)
if err != nil {
log.Fatal(err)
}
log.Println("Done")
}