From 5d96c929bb61aaf6884a970d61df09e6d09dab00 Mon Sep 17 00:00:00 2001 From: Seraphim Strub Date: Thu, 9 Mar 2023 23:37:01 +0100 Subject: [PATCH] refactor funbot to packages --- cmd/funbot/command/img.go | 46 ++++++++++ cmd/funbot/config/command.go | 63 +++++++++++++ cmd/funbot/config/config.go | 13 +++ cmd/funbot/imgur/imgur.go | 50 +++++++++++ cmd/funbot/main.go | 170 +++-------------------------------- 5 files changed, 182 insertions(+), 160 deletions(-) create mode 100644 cmd/funbot/command/img.go create mode 100644 cmd/funbot/config/command.go create mode 100644 cmd/funbot/config/config.go create mode 100644 cmd/funbot/imgur/imgur.go diff --git a/cmd/funbot/command/img.go b/cmd/funbot/command/img.go new file mode 100644 index 0000000..022e96d --- /dev/null +++ b/cmd/funbot/command/img.go @@ -0,0 +1,46 @@ +package command + +import ( + "errors" + "github.com/disgoorg/disgo/discord" + "github.com/disgoorg/disgo/events" + "grow.rievo.dev/discordBots/cmd/funbot/imgur" + "strings" +) + +func Listener(event *events.ApplicationCommandInteractionCreate) { + data := event.SlashCommandInteractionData() + if data.CommandName() == "img" { + handlerImg(event) + } +} + +func handlerImg(event *events.ApplicationCommandInteractionCreate) { + data := event.SlashCommandInteractionData() + value := data.String("type") + + link, err := func(value string) (string, error) { + switch { + case strings.HasPrefix(value, "imgur-"): + link, err := imgur.GetRandomImgur(strings.TrimPrefix(value, "imgur-")) + if err != nil { + return "", err + } + return link, nil + default: + return "", errors.New("value not found") + } + }(value) + if err != nil { + event.Client().Logger().Error("error on getting link: ", err) + return + } + + err = event.CreateMessage(discord.NewMessageCreateBuilder(). + SetContent(link). + SetEphemeral(false).Build()) + if err != nil { + event.Client().Logger().Error("error on sending response: ", err) + return + } +} diff --git a/cmd/funbot/config/command.go b/cmd/funbot/config/command.go new file mode 100644 index 0000000..9de2267 --- /dev/null +++ b/cmd/funbot/config/command.go @@ -0,0 +1,63 @@ +package config + +import "github.com/disgoorg/disgo/discord" + +var ( + Commands = []discord.ApplicationCommandCreate{ + discord.SlashCommandCreate{ + Name: "img", + Description: "get a funny or cute image", + Options: []discord.ApplicationCommandOption{ + discord.ApplicationCommandOptionString{ + Name: "type", + Description: "what do you want?", + Required: true, + Choices: []discord.ApplicationCommandOptionChoiceString{ + { + Name: "facedesk", + Value: "imgur-I5Q4U", + }, { + Name: "hug", + Value: "imgur-jHJOc", + }, { + Name: "pat", + Value: "imgur-WiPTl", + }, { + Name: "roll", + Value: "imgur-lrEwS", + }, { + Name: "wombat", + Value: "imgur-mnhzS", + }, { + Name: "capybara", + Value: "imgur-hfL80", + }, { + Name: "quokka", + Value: "imgur-WvjQA", + }, { + Name: "otter", + Value: "imgur-BL2MW", + }, { + Name: "seal", + Value: "imgur-jE3IoCU", + }, { + Name: "shepherd", + Value: "imgur-XSAIPVF", + }, { + Name: "firework", + Value: "imgur-g228Sf1", + }, { + Name: "marblefox", + Value: "imgur-yQlGBLE", + }, { + Name: "chibird", + Value: "imgur-zHsrxFr", + }, + }, + }, + }, + }, + } + + NoCommands []discord.ApplicationCommandCreate +) diff --git a/cmd/funbot/config/config.go b/cmd/funbot/config/config.go new file mode 100644 index 0000000..f6f3af3 --- /dev/null +++ b/cmd/funbot/config/config.go @@ -0,0 +1,13 @@ +package config + +import ( + "github.com/disgoorg/snowflake/v2" + "os" +) + +var ( + Token = os.Getenv("disgo_token") + ApiImgurKey = os.Getenv("disgo_imgur") + GlobalCommands = os.Getenv("disgo_global") + RegisterGuildID = snowflake.GetEnv("disgo_guild_id") +) diff --git a/cmd/funbot/imgur/imgur.go b/cmd/funbot/imgur/imgur.go new file mode 100644 index 0000000..e602465 --- /dev/null +++ b/cmd/funbot/imgur/imgur.go @@ -0,0 +1,50 @@ +package imgur + +import ( + "encoding/json" + "fmt" + "grow.rievo.dev/discordBots/cmd/funbot/config" + "io" + "math/rand" + "net/http" +) + +type imgurApiBody struct { + Data []struct { + Link string `json:"link"` + } `json:"data"` + Success bool `json:"success"` + Status int `json:"status"` +} + +func GetRandomImgur(album string) (string, error) { + apiUrl := fmt.Sprintf("https://api.imgur.com/3/album/%v/images", album) + + client := &http.Client{} + + req, err := http.NewRequest("GET", apiUrl, nil) + if err != nil { + return "", err + } + req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0") + req.Header.Set("Authorization", config.ApiImgurKey) + res, err := client.Do(req) + if err != nil { + return "", err + } + body, err := io.ReadAll(res.Body) + if err != nil { + return "", err + } + + var data imgurApiBody + err = json.Unmarshal(body, &data) + if err != nil { + return "", err + } + + randomIndex := rand.Intn(len(data.Data)) + link := data.Data[randomIndex].Link + + return link, nil +} diff --git a/cmd/funbot/main.go b/cmd/funbot/main.go index 20df443..ac77707 100644 --- a/cmd/funbot/main.go +++ b/cmd/funbot/main.go @@ -2,92 +2,19 @@ package main import ( "context" - "encoding/json" - "errors" - "fmt" "github.com/disgoorg/disgo" "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/cache" - "github.com/disgoorg/disgo/discord" - "github.com/disgoorg/disgo/events" "github.com/disgoorg/disgo/gateway" "github.com/disgoorg/log" - "github.com/disgoorg/snowflake/v2" - "io" - "math/rand" - "net/http" + "grow.rievo.dev/discordBots/cmd/funbot/command" + "grow.rievo.dev/discordBots/cmd/funbot/config" "os" "os/signal" "strings" "syscall" ) -var ( - token = os.Getenv("disgo_token") - apiImgurKey = os.Getenv("disgo_imgur") - globalComandsEnv = os.Getenv("disgo_global") - registerGuildID = snowflake.GetEnv("disgo_guild_id") - - // TODO: add jokes - commands = []discord.ApplicationCommandCreate{ - discord.SlashCommandCreate{ - Name: "img", - Description: "get a funny or cute image", - Options: []discord.ApplicationCommandOption{ - discord.ApplicationCommandOptionString{ - Name: "type", - Description: "what do you want?", - Required: true, - Choices: []discord.ApplicationCommandOptionChoiceString{ - { - Name: "facedesk", - Value: "imgur-I5Q4U", - }, { - Name: "hug", - Value: "imgur-jHJOc", - }, { - Name: "pat", - Value: "imgur-WiPTl", - }, { - Name: "roll", - Value: "imgur-lrEwS", - }, { - Name: "wombat", - Value: "imgur-mnhzS", - }, { - Name: "capybara", - Value: "imgur-hfL80", - }, { - Name: "quokka", - Value: "imgur-WvjQA", - }, { - Name: "otter", - Value: "imgur-BL2MW", - }, { - Name: "seal", - Value: "imgur-jE3IoCU", - }, { - Name: "shepherd", - Value: "imgur-XSAIPVF", - }, { - Name: "firework", - Value: "imgur-g228Sf1", - }, { - Name: "marblefox", - Value: "imgur-yQlGBLE", - }, { - Name: "chibird", - Value: "imgur-zHsrxFr", - }, - }, - }, - }, - }, - } - - noCommands []discord.ApplicationCommandCreate -) - func main() { log.SetLevel(log.LevelInfo) log.Info("starting funbot...") @@ -95,7 +22,7 @@ func main() { // permissions: // intent: - client, err := disgo.New(token, + client, err := disgo.New(config.Token, bot.WithGatewayConfigOpts( gateway.WithIntents(gateway.IntentsNone), ), @@ -104,7 +31,7 @@ func main() { cache.FlagsNone, ), ), - bot.WithEventListenerFunc(commandListener), + bot.WithEventListenerFunc(command.Listener), ) if err != nil { log.Fatal("error while building disgo instance: ", err) @@ -114,24 +41,24 @@ func main() { defer client.Close(context.TODO()) var globalComands bool - if strings.ToUpper(globalComandsEnv) == "TRUE" { + if strings.ToUpper(config.GlobalCommands) == "TRUE" { globalComands = true } if globalComands { - if _, err = client.Rest().SetGlobalCommands(client.ApplicationID(), commands); err != nil { + if _, err = client.Rest().SetGlobalCommands(client.ApplicationID(), config.Commands); err != nil { log.Fatal("error while registering commands: ", err) } - if registerGuildID != 0 { - if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), registerGuildID, noCommands); err != nil { + if config.RegisterGuildID != 0 { + if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), config.RegisterGuildID, config.NoCommands); err != nil { log.Info("error deleting guild commands", err) } } } else { - if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), registerGuildID, commands); err != nil { + if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), config.RegisterGuildID, config.Commands); err != nil { log.Fatal("error while registering commands: ", err) } - if _, err = client.Rest().SetGlobalCommands(client.ApplicationID(), noCommands); err != nil { + if _, err = client.Rest().SetGlobalCommands(client.ApplicationID(), config.NoCommands); err != nil { log.Info("error deleting global commands", err) } } @@ -145,80 +72,3 @@ func main() { signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-s } - -func commandListener(event *events.ApplicationCommandInteractionCreate) { - data := event.SlashCommandInteractionData() - if data.CommandName() == "img" { - commandHandlerImg(event) - } -} - -func commandHandlerImg(event *events.ApplicationCommandInteractionCreate) { - data := event.SlashCommandInteractionData() - value := data.String("type") - - link, err := func(value string) (string, error) { - switch { - case strings.HasPrefix(value, "imgur-"): - link, err := getRandomImgur(strings.TrimPrefix(value, "imgur-")) - if err != nil { - return "", err - } - return link, nil - default: - return "", errors.New("value not found") - } - }(value) - if err != nil { - event.Client().Logger().Error("error on getting link: ", err) - return - } - - err = event.CreateMessage(discord.NewMessageCreateBuilder(). - SetContent(link). - SetEphemeral(false).Build()) - if err != nil { - event.Client().Logger().Error("error on sending response: ", err) - return - } -} - -type imgurApiBody struct { - Data []struct { - Link string `json:"link"` - } `json:"data"` - Success bool `json:"success"` - Status int `json:"status"` -} - -func getRandomImgur(album string) (string, error) { - apiUrl := fmt.Sprintf("https://api.imgur.com/3/album/%v/images", album) - - client := &http.Client{} - - req, err := http.NewRequest("GET", apiUrl, nil) - if err != nil { - return "", err - } - req.Header.Set("User-Agent", "https://sst.place") - req.Header.Set("Authorization", apiImgurKey) - res, err := client.Do(req) - if err != nil { - return "", err - } - body, err := io.ReadAll(res.Body) - if err != nil { - return "", err - } - - var data imgurApiBody - err = json.Unmarshal(body, &data) - if err != nil { - return "", err - } - - randomIndex := rand.Intn(len(data.Data)) - link := data.Data[randomIndex].Link - - return link, nil -}