From 564801b2761ba4dd1989e96898a4a4f85df03b50 Mon Sep 17 00:00:00 2001 From: "inu (Lucas DEBOUTE)" Date: Wed, 6 Mar 2024 13:49:29 -0800 Subject: [PATCH] chore(main) remove unused calls + use local cache by default --- cmd/shibesbot/dogequests.go | 75 -------------------------- cmd/shibesbot/main.go | 72 ++++++++++++++----------- cmd/shibesbot/monitoring/monitoring.go | 5 ++ 3 files changed, 47 insertions(+), 105 deletions(-) diff --git a/cmd/shibesbot/dogequests.go b/cmd/shibesbot/dogequests.go index 1e91781..e85299b 100644 --- a/cmd/shibesbot/dogequests.go +++ b/cmd/shibesbot/dogequests.go @@ -1,7 +1,6 @@ package main import ( - "errors" "math/rand" "net/http" @@ -53,80 +52,6 @@ type ShibesData struct { Wallpapers ShibesWallpapers } -func initWallpapers(t string) (wp ShibesWallpapers, err error) { - wpEmpty := ShibesWallpapers{ - Cursor: 0, - Total: 0, - Shibes: make([]WallpaperData, 0), - } - - if len(t) <= 0 { - return wpEmpty, errors.New("no alphacoders token provided, skipping") - } - req, err := http.NewRequest("GET", "https://wall.alphacoders.com/api2.0/get.php", nil) - if err != nil { - return wpEmpty, err - } - - q := req.URL.Query() - q.Add("auth", t) - q.Add("method", "search") - q.Add("term", "Shiba") - req.URL.RawQuery = q.Encode() - resp, err := http.Get(req.URL.String()) - if err != nil { - return wpEmpty, err - } - defer resp.Body.Close() - var res AlphacodersData - err = json.NewDecoder(resp.Body).Decode(&res) - if err != nil { - return wpEmpty, err - } - - wp.Shibes = make([]WallpaperData, len(res.Wallpapers)) - wp.Shibes = res.Wallpapers - wp.Total = len(res.Wallpapers) - - return wp, nil -} - -func initGifs(t string) (ShibesGifs, error) { - var gifs ShibesGifs - - if len(t) <= 0 { - return ShibesGifs{ - Cursor: 0, - Shibes: make([]giphy.Gif, 0), - Total: 0, - }, errors.New("no giphy token provided, skipping") - } - - gp := giphy.New(t) - gifs.Shibes, _ = gp.Search("shiba") - gifs.Total = len(gifs.Shibes) - gifs.Cursor = 0 - - return gifs, nil -} - -func (sb *Shibesbot) initRequests() { - var err error - - Shibes.Wallpapers, err = initWallpapers(sb.apiConfigurations.alphacodersToken) - sb.log.Info("retrieved ", Shibes.Wallpapers.Total, " wallpapers") - if err != nil { - sb.log.Warn("could not retrieve wallpapers: ", err.Error()) - } - - Shibes.Gifs, err = initGifs(sb.apiConfigurations.giphyToken) - sb.log.Info("retrieved ", Shibes.Gifs.Total, " gifs") - if err != nil { - sb.log.Warn("could not retrieve gifs: ", err.Error()) - } - -} - func (sb *Shibesbot) getShibes() string { if Shibes.Images.Cursor >= Shibes.Images.Total { Shibes.Images.Cursor = 0 diff --git a/cmd/shibesbot/main.go b/cmd/shibesbot/main.go index d7ea74a..04963ed 100644 --- a/cmd/shibesbot/main.go +++ b/cmd/shibesbot/main.go @@ -3,16 +3,17 @@ package main import ( "context" "fmt" - "log" "os" "os/signal" "strconv" + "strings" "sync" "syscall" "time" "github.com/codeinuit/shibesbot/cmd/shibesbot/monitoring" "github.com/codeinuit/shibesbot/pkg/cache" + "github.com/codeinuit/shibesbot/pkg/cache/localstorage" "github.com/codeinuit/shibesbot/pkg/cache/redis" "github.com/codeinuit/shibesbot/pkg/logger" "github.com/codeinuit/shibesbot/pkg/logger/logrus" @@ -23,10 +24,12 @@ import ( // ENV variables const ( + // Token configuration DISCORD_TOKEN = "SHIBESBOT_TOKEN" - ALPHACODERS_TOKEN = "ALPHACODERS_TOKEN" SHIBESONLINE_TOKEN = "SHIBESONLINE_TOKEN" - GIPHY_TOKEN = "GIPHY_TOKEN" + + // Flags + ENV_CACHE = "CACHE" // Redis configuration REDIS_ADDR = "REDIS_ADDR" @@ -37,9 +40,7 @@ const ( type ApiConfigurations struct { discordToken string - alphacodersToken string shibesolineToken string - giphyToken string } type Shibesbot struct { @@ -53,32 +54,39 @@ type Shibesbot struct { cache cache.Cache } -func initConfiguration() *Shibesbot { - port, err := strconv.Atoi(os.Getenv(REDIS_PORT)) - if err != nil { - port = 6379 - } +func NewShibesbot() (*Shibesbot, error) { + var cache cache.Cache = localstorage.NewLocalStorageCache() + var log logger.Logger = logrus.NewLogrusLogger() + var err error - r, err := redis.NewRedisCache(redis.RedisOptions{ - Address: os.Getenv(REDIS_ADDR), - Port: int32(port), - Password: os.Getenv(REDIS_PASS), - }) + // check if Redis is enabled; otherwise fallback to local storage + if c := os.Getenv(ENV_CACHE); strings.ToUpper(c) == "REDIS" { + var port int - if err != nil { - log.Fatal(err.Error()) + log.Info("Redis enabled") + + address := os.Getenv(REDIS_ADDR) + if port, err = strconv.Atoi(os.Getenv(REDIS_PORT)); err != nil { + log.Warnf("environnement variable %s is undefined; using default value", REDIS_PORT) + port = 6379 + } + log.Infof("using Redis on %s with port %d", address, port) + + cache, err = redis.NewRedisCache(redis.RedisOptions{ + Address: address, + Port: int32(port), + Password: os.Getenv(REDIS_PASS), + }) } return &Shibesbot{ - cache: r, - log: logrus.NewLogrusLogger(), + cache: cache, + log: log, apiConfigurations: ApiConfigurations{ discordToken: os.Getenv(DISCORD_TOKEN), - alphacodersToken: os.Getenv(ALPHACODERS_TOKEN), shibesolineToken: os.Getenv(SHIBESONLINE_TOKEN), - giphyToken: os.Getenv(GIPHY_TOKEN), }, - } + }, err } func (sb *Shibesbot) setDailyKey(t time.Time) { @@ -101,31 +109,35 @@ func (sb *Shibesbot) setDailyKey(t time.Time) { } func main() { - sb := initConfiguration() - sb.initRequests() - sb.log.Info("starting Shibesbot") + sb, err := NewShibesbot() + if err != nil { + fmt.Printf("could not initialize bot : %s", err.Error()) + os.Exit(1) + } + + sb.log.Info("starting bot") c := cron.New() monitor := monitoring.NewHTTPMonitorServer(sb.log) if len(sb.apiConfigurations.discordToken) <= 0 { - sb.log.Error("environnement variable SHIBESBOT_TOKEN is not provided") + sb.log.Errorf("environnement variable %s is not provided", SHIBESONLINE_TOKEN) return } if err := sb.initDiscord(); err != nil { sb.log.Error("connexion error: ", err.Error()) - return + os.Exit(1) } defer func() { if err := sb.session.Close(); err != nil { sb.log.Error("discord session could not close properly:", err.Error()) - return + os.Exit(1) } sb.log.Info("discord session closed successfully") }() - _, err := c.AddFunc("0 0 * * *", func() { + _, err = c.AddFunc("0 0 * * *", func() { sb.log.Info("updating usage count status") sb.setDailyKey(time.Now()) sb.setDailyCounter(0) @@ -133,7 +145,7 @@ func main() { if err != nil { sb.log.Error("could not create cronjob: ", err.Error()) - return + os.Exit(1) } c.Start() diff --git a/cmd/shibesbot/monitoring/monitoring.go b/cmd/shibesbot/monitoring/monitoring.go index 9f33f82..8c3f40b 100644 --- a/cmd/shibesbot/monitoring/monitoring.go +++ b/cmd/shibesbot/monitoring/monitoring.go @@ -8,6 +8,11 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" ) +type Monitoring interface { + Run() + Stop() +} + type HttpMonitor struct { log logger.Logger srv *http.Server