From f463209191035c41a10ce29dccad3ad8f6fa015b Mon Sep 17 00:00:00 2001 From: Mitchell Gerber Date: Wed, 29 Mar 2017 22:09:48 -0500 Subject: [PATCH] added giphy roulette support --- makefile | 2 +- server/bothandlers/gif.go | 58 +++++++++++++++++++++++++++++++++++++++ server/main.go | 1 + 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 server/bothandlers/gif.go diff --git a/makefile b/makefile index c368bb4..3387e09 100644 --- a/makefile +++ b/makefile @@ -5,7 +5,7 @@ install: go get ./server && yarn install build: - go build -o ./dist/soundbot ./server/main.go + go build -o ./dist/bot ./server/main.go clean: rm -rf ./dist diff --git a/server/bothandlers/gif.go b/server/bothandlers/gif.go new file mode 100644 index 0000000..cd8e697 --- /dev/null +++ b/server/bothandlers/gif.go @@ -0,0 +1,58 @@ +package bothandlers + +import ( + "io/ioutil" + "net/http" + "strings" + + "github.com/bwmarrin/discordgo" + "github.com/tidwall/gjson" +) + +const ( + gifPrefix string = "!gif " + userAgent string = "go-discord-bot" + giphyURL string = "http://api.giphy.com/v1/stickers/random?api_key=dc6zaTOxFJmzC&rating=r&tag=" +) + +// GifHandler - handler for giphy api +func GifHandler(s *discordgo.Session, m *discordgo.MessageCreate) { + + // check if valid command + if strings.HasPrefix(m.Content, gifPrefix) { + + searchText := strings.TrimPrefix(m.Content, gifPrefix) + + gifLink := getGiphy(searchText) + + if gifLink == "null" { + gifLink = "No gif found." + } + + s.ChannelMessageSend(m.ChannelID, gifLink) + + } +} + +// send http request to reddit +func getGiphy(searchTerm string) string { + client := &http.Client{} + + req, err := http.NewRequest("GET", giphyURL+searchTerm, nil) + + response, err := client.Do(req) + if err != nil { + return err.Error() + } + + defer response.Body.Close() + + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err.Error() + } + + data := gjson.Get(string(body), "data.url") + + return data.String() +} diff --git a/server/main.go b/server/main.go index 55501c8..aff8e26 100644 --- a/server/main.go +++ b/server/main.go @@ -16,6 +16,7 @@ func main() { //add handlers bot.AddHandler(bothandlers.SoundsHandler) + bot.AddHandler(bothandlers.GifHandler) // start new go routine for the discord websockets go bot.Start()