2022-10-02 06:29:23 +00:00
|
|
|
package discord
|
|
|
|
|
|
|
|
import (
|
2022-10-03 05:19:33 +00:00
|
|
|
"context"
|
2022-10-02 06:29:23 +00:00
|
|
|
"fmt"
|
|
|
|
|
2022-10-03 05:19:33 +00:00
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/domain"
|
2022-10-09 06:31:38 +00:00
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/twhelp"
|
2022-10-02 06:29:23 +00:00
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
|
)
|
|
|
|
|
2022-10-03 05:19:33 +00:00
|
|
|
type GroupService interface {
|
|
|
|
Create(ctx context.Context, params domain.CreateGroupParams) (domain.Group, error)
|
2022-10-10 05:16:40 +00:00
|
|
|
SetTWServer(ctx context.Context, id, versionCode, serverKey string) (domain.Group, error)
|
2022-10-10 03:59:46 +00:00
|
|
|
List(ctx context.Context, params domain.ListGroupsParams) ([]domain.Group, error)
|
2022-10-03 05:19:33 +00:00
|
|
|
}
|
|
|
|
|
2022-10-09 06:31:38 +00:00
|
|
|
type TWHelpClient interface {
|
|
|
|
ListVersions(ctx context.Context) ([]twhelp.Version, error)
|
|
|
|
}
|
|
|
|
|
2022-10-02 06:29:23 +00:00
|
|
|
type Bot struct {
|
2022-10-03 05:19:33 +00:00
|
|
|
s *discordgo.Session
|
|
|
|
groupSvc GroupService
|
2022-10-09 06:31:38 +00:00
|
|
|
client TWHelpClient
|
2022-10-02 06:29:23 +00:00
|
|
|
}
|
|
|
|
|
2022-10-09 06:31:38 +00:00
|
|
|
func NewBot(token string, groupSvc GroupService, client TWHelpClient) (*Bot, error) {
|
2022-10-02 06:29:23 +00:00
|
|
|
s, err := discordgo.New("Bot " + token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("discordgo.New: %w", err)
|
|
|
|
}
|
|
|
|
if err = s.Open(); err != nil {
|
|
|
|
return nil, fmt.Errorf("s.Open: %w", err)
|
|
|
|
}
|
2022-10-09 06:31:38 +00:00
|
|
|
b := &Bot{s: s, groupSvc: groupSvc, client: client}
|
2022-10-03 05:19:33 +00:00
|
|
|
if err = b.registerCommands(); err != nil {
|
|
|
|
_ = s.Close()
|
|
|
|
return nil, fmt.Errorf("couldn't register commands: %w", err)
|
|
|
|
}
|
|
|
|
return b, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Bot) registerCommands() error {
|
2022-10-09 06:31:38 +00:00
|
|
|
if err := b.registerCommand(&groupCommand{svc: b.groupSvc, client: b.client}); err != nil {
|
2022-10-03 05:19:33 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Bot) registerCommand(cmd command) error {
|
|
|
|
if err := cmd.register(b.s); err != nil {
|
|
|
|
return fmt.Errorf("couldn't register command '%s': %w", cmd.name(), err)
|
|
|
|
}
|
|
|
|
return nil
|
2022-10-02 06:29:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Bot) Close() error {
|
|
|
|
return b.s.Close()
|
|
|
|
}
|