2022-10-02 06:29:23 +00:00
|
|
|
package run
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
|
2022-10-03 05:19:33 +00:00
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/cmd/dcbot/internal"
|
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/bundb"
|
2022-10-02 06:29:23 +00:00
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/discord"
|
2022-10-03 05:19:33 +00:00
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/service"
|
2022-10-02 06:29:23 +00:00
|
|
|
"github.com/kelseyhightower/envconfig"
|
|
|
|
"github.com/urfave/cli/v2"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
healthyFilePath = "/tmp/healthy"
|
|
|
|
healthyFilePerm = 0644
|
|
|
|
)
|
|
|
|
|
|
|
|
func New() *cli.Command {
|
|
|
|
return &cli.Command{
|
|
|
|
Name: "run",
|
|
|
|
Usage: "Runs the dc bot",
|
|
|
|
Action: func(c *cli.Context) error {
|
|
|
|
logger := zap.L()
|
|
|
|
|
2022-10-03 05:19:33 +00:00
|
|
|
db, err := internal.NewBunDB()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("internal.NewBunDB: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
groupRepo := bundb.NewGroup(db)
|
|
|
|
|
|
|
|
groupSvc := service.NewGroup(groupRepo)
|
|
|
|
|
2022-10-02 06:29:23 +00:00
|
|
|
cfg, err := newBotConfig()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("newBotConfig: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-10-03 05:19:33 +00:00
|
|
|
bot, err := discord.NewBot(cfg.Token, groupSvc)
|
2022-10-02 06:29:23 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("discord.NewBot: %w", err)
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
_ = bot.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
if err := os.WriteFile(healthyFilePath, []byte("healthy"), healthyFilePerm); err != nil {
|
|
|
|
return fmt.Errorf("couldn't create file (path=%s): %w", healthyFilePath, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Info("Bot is up and running")
|
|
|
|
|
|
|
|
waitForSignal(c.Context)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type botConfig struct {
|
|
|
|
Token string `envconfig:"TOKEN" required:"true"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func newBotConfig() (botConfig, error) {
|
|
|
|
var cfg botConfig
|
|
|
|
if err := envconfig.Process("BOT", &cfg); err != nil {
|
|
|
|
return botConfig{}, fmt.Errorf("envconfig.Process: %w", err)
|
|
|
|
}
|
|
|
|
return cfg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func waitForSignal(ctx context.Context) {
|
|
|
|
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
|
|
|
|
defer stop()
|
|
|
|
<-ctx.Done()
|
|
|
|
}
|