Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sextou handler #2

Merged
merged 7 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ FRONTEND_ROLE_ID=
BACKEND_ROLE_ID=
MOBILE_ROLE_ID=
FULLSTACK_ROLE_ID=
QA_ROLE_ID=
QA_ROLE_ID=
GTENOR_KEY=
11 changes: 11 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"log"
"os"
"strconv"
)
Expand All @@ -10,6 +11,7 @@ type Config struct {
GuildID string
ChannelID string
MessageID string
GTenorKey string
RemoveCommands bool
RoleMap map[string]string
}
Expand All @@ -24,6 +26,7 @@ func Load() (*Config, error) {
cfg.GuildID = os.Getenv("GUILD_ID")
cfg.ChannelID = os.Getenv("CHANNEL_ID")
cfg.MessageID = os.Getenv("MESSAGE_ID")
cfg.GTenorKey = os.Getenv("GTENOR_KEY")
cfg.RemoveCommands, err = strconv.ParseBool(os.Getenv("REMOVE_COMMANDS"))

if err != nil {
Expand All @@ -40,3 +43,11 @@ func Load() (*Config, error) {

return cfg, nil
}

func GetConfig() Config {
if cfg == nil {
log.Fatal("You must load the config")
}

return *cfg
}
172 changes: 172 additions & 0 deletions handlers/friday.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package handlers

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"

"github.com/bwmarrin/discordgo"
"github.com/liverday/medeiro-tech-bot/config"
)

var (
gTenorUrl = "https://g.tenor.com/v1"

fridayTrigger = "sextou"
fridayGifUrl = "https://media.tenor.com/zGlEbV_bTnIAAAAC/kowalski-familia.gif"
liverday marked this conversation as resolved.
Show resolved Hide resolved

fallbackGifUrl = "https://tenor.com/view/dancing-random-duck-gif-25973520"
)

var cfg config.Config

type GTenorMinimalReturn struct {
Results []struct {
ID string `json:"id"`
Title string `json:"title"`
ContentDescription string `json:"content_description"`
ContentRating string `json:"content_rating"`
H1Title string `json:"h1_title"`
Media []struct {
Mp4 struct {
Dims []int `json:"dims"`
Preview string `json:"preview"`
Size int `json:"size"`
URL string `json:"url"`
Duration float64 `json:"duration"`
} `json:"mp4"`
Gif struct {
Size int `json:"size"`
URL string `json:"url"`
Preview string `json:"preview"`
Dims []int `json:"dims"`
} `json:"gif"`
Tinygif struct {
Dims []int `json:"dims"`
Size int `json:"size"`
Preview string `json:"preview"`
URL string `json:"url"`
} `json:"tinygif"`
} `json:"media"`
BgColor string `json:"bg_color"`
Created float64 `json:"created"`
Itemurl string `json:"itemurl"`
URL string `json:"url"`
Tags []interface{} `json:"tags"`
Flags []interface{} `json:"flags"`
Shares int `json:"shares"`
Hasaudio bool `json:"hasaudio"`
Hascaption bool `json:"hascaption"`
SourceID string `json:"source_id"`
Composite interface{} `json:"composite"`
} `json:"results"`
Next string `json:"next"`
}

func FridayHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
cfg = config.GetConfig()

if !strings.Contains(m.Content, fridayTrigger) {
return
}

message := &discordgo.MessageSend{
Files: []*discordgo.File{},
}

switch time.Now().Weekday() {
case time.Friday:
message.Content = "Sextouu família"
liverday marked this conversation as resolved.
Show resolved Hide resolved

randomFridayGif := getRandomGif(fridayTrigger)
randomFridayGifUrl := extractGifFromGTenor(randomFridayGif, fridayGifUrl)

message.Files = append(message.Files, processGifUrl(randomFridayGifUrl))
case time.Thursday:
message.Content = "Quase, mas ainda não"

randomThursdayGif := getRandomGif("quase-la")
randomThursdayGifUrl := extractGifFromGTenor(randomThursdayGif, fallbackGifUrl)

message.Files = append(message.Files, processGifUrl(randomThursdayGifUrl))
default:
message.Content = fmt.Sprintf("Calma família ainda não é sexta! Falta %d dia(s)", daysRemainingToFriday())
liverday marked this conversation as resolved.
Show resolved Hide resolved

randomGif := getRandomGif(time.Now().Weekday().String())
randomGifUrl := extractGifFromGTenor(randomGif, fallbackGifUrl)

message.Files = append(message.Files, processGifUrl(randomGifUrl))
}

s.ChannelMessageSendComplex(m.ChannelID, message)
}

func getRandomGif(search string) (result GTenorMinimalReturn) {
req, err := http.NewRequest("GET", gTenorUrl+"/random", nil)
if err != nil {
fmt.Println("Cannot make a new http Request", err)
}

query := req.URL.Query()
query.Add("q", search)
query.Add("key", cfg.GTenorKey)
query.Add("media_filter", "minimal")
query.Add("limit", "1")

req.URL.RawQuery = query.Encode()

client := http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error on get a random gif", err)
}

body, _ := io.ReadAll(res.Body)
if err := json.Unmarshal(body, &result); err != nil {
fmt.Println("Can not unmarshall JSON", err)
}

return result
}

func extractGifFromGTenor(gTenor GTenorMinimalReturn, fallback string) string {
if len(gTenor.Results) > 0 && len(gTenor.Results[0].Media) > 0 {
return gTenor.Results[0].Media[0].Gif.URL
}

return fallback
}

func processGifUrl(url string) *discordgo.File {
res, err := http.Get(url)
if err != nil {
fmt.Println("Bad request", err)
}
defer res.Body.Close()

body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Println("Failed to get GIT", err)
}

gifFile := &discordgo.File{
Name: "sextou-familia.gif",
Reader: bytes.NewReader(body),
}

return gifFile
}

func daysRemainingToFriday() int {
today := time.Now()

if today.Weekday() > time.Friday {
return int(today.Weekday())
} else {
return int(time.Friday) - int(today.Weekday())
}
}
8 changes: 8 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ var (
"source": handlers.SourceHandler,
"short_url": handlers.ShortUrlHandler,
}
messageHandlers = map[string]func(s *discordgo.Session, m *discordgo.MessageCreate){
"friday": handlers.FridayHandler,
}
)

var bot *discordgo.Session
Expand Down Expand Up @@ -96,6 +99,11 @@ func addHandlers() {
handler(s, i)
}
})
bot.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
for _, handler := range messageHandlers {
handler(s, m)
}
})
}

func addCommands() []*discordgo.ApplicationCommand {
Expand Down