2023-10-13 18:25:03 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/disgoorg/disgo"
|
|
|
|
"github.com/disgoorg/disgo/bot"
|
|
|
|
"github.com/disgoorg/disgo/cache"
|
|
|
|
"github.com/disgoorg/snowflake/v2"
|
|
|
|
"io"
|
2023-11-05 16:03:52 +00:00
|
|
|
"log/slog"
|
2023-10-13 18:25:03 +00:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
token = os.Getenv("disgo_token")
|
|
|
|
avatarCache map[snowflake.ID][]byte
|
|
|
|
)
|
|
|
|
|
2023-11-05 16:03:52 +00:00
|
|
|
var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
|
|
|
|
2023-10-13 18:25:03 +00:00
|
|
|
func init() {
|
|
|
|
avatarCache = make(map[snowflake.ID][]byte)
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2023-11-05 16:03:52 +00:00
|
|
|
|
|
|
|
logger.Info("starting dealsbot...")
|
|
|
|
|
2023-10-13 18:25:03 +00:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
2023-11-05 16:03:52 +00:00
|
|
|
client, err := disgo.New(token,
|
|
|
|
bot.WithCacheConfigOpts(
|
|
|
|
cache.WithCaches(cache.FlagsAll)),
|
2023-10-13 18:25:03 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2023-11-05 16:03:52 +00:00
|
|
|
logger.Error("error initializing disgo client", slog.Any("error", err))
|
2023-10-13 18:25:03 +00:00
|
|
|
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
|
|
|
|
})
|
|
|
|
|
2023-11-05 16:03:52 +00:00
|
|
|
err = http.ListenAndServe(":8080", mux)
|
|
|
|
logger.Error("error from http listener", slog.Any("error", err))
|
2023-10-13 18:25:03 +00:00
|
|
|
}
|