discordBots/cmd/funbot/main.go

203 lines
4.5 KiB
Go
Raw Normal View History

2023-01-25 23:37:53 +00:00
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"
"os"
"os/signal"
"strings"
"syscall"
)
var (
token = os.Getenv("disgo_token")
apiImgurKey = os.Getenv("disgo_imgur")
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",
},
},
},
},
},
}
)
func main() {
log.SetLevel(log.LevelDebug)
log.Info("starting funbot...")
log.Info("disgo version: ", disgo.Version)
// permissions:
// intent:
client, err := disgo.New(token,
bot.WithGatewayConfigOpts(
gateway.WithIntents(gateway.IntentsNone),
),
bot.WithCacheConfigOpts(
cache.WithCaches(
cache.FlagsNone,
),
),
bot.WithEventListenerFunc(commandListener),
)
if err != nil {
log.Fatal("error while building disgo instance: ", err)
return
}
defer client.Close(context.TODO())
if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), registerGuildID, commands); err != nil {
log.Fatal("error while registering commands: ", err)
}
if err = client.OpenGateway(context.TODO()); err != nil {
log.Fatal("error while connecting to gateway: ", err)
}
log.Infof("funbot is now running. Press CTRL-C to exit.")
s := make(chan os.Signal, 1)
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
}