71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
|
package run
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"os/signal"
|
||
|
"syscall"
|
||
|
|
||
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/discord"
|
||
|
"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()
|
||
|
|
||
|
cfg, err := newBotConfig()
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("newBotConfig: %w", err)
|
||
|
}
|
||
|
|
||
|
bot, err := discord.NewBot(cfg.Token)
|
||
|
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()
|
||
|
}
|