package main import ( "github.com/disgoorg/disgo" "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/cache" "github.com/disgoorg/snowflake/v2" "io" "log/slog" "net/http" "os" "strings" ) var ( token = os.Getenv("disgo_token") avatarCache map[snowflake.ID][]byte ) var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil)) func init() { avatarCache = make(map[snowflake.ID][]byte) } func main() { logger.Info("starting dealsbot...") mux := http.NewServeMux() client, err := disgo.New(token, bot.WithCacheConfigOpts( cache.WithCaches(cache.FlagsAll)), ) if err != nil { logger.Error("error initializing disgo client", slog.Any("error", err)) return } rest := client.Rest() mux.HandleFunc("/api/v1/discord/avatar/", func(w http.ResponseWriter, r *http.Request) { flake, err := snowflake.Parse(strings.TrimPrefix(r.URL.Path, "/api/v1/discord/avatar/")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } avatar, ok := avatarCache[flake] if !ok { user, err := rest.GetUser(flake) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } avatarUrl := user.EffectiveAvatarURL() res, err := http.Get(avatarUrl) if err != nil || res.StatusCode != http.StatusOK { http.Error(w, err.Error(), http.StatusInternalServerError) return } // cache entry avatarCache[flake], err = io.ReadAll(res.Body) avatar = avatarCache[flake] if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) w.Header().Add("Content-Type", http.DetectContentType(avatar)) _, _ = w.Write(avatar) return }) err = http.ListenAndServe(":8080", mux) logger.Error("error from http listener", slog.Any("error", err)) }