From f43426bbee4f852b7529b453534bfa07461d8106 Mon Sep 17 00:00:00 2001 From: Denis Zheleztsov Date: Sat, 16 Jan 2021 13:33:30 +0300 Subject: [PATCH] Gif support ^_^ --- main.go | 48 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 8ccda63..acb34b0 100644 --- a/main.go +++ b/main.go @@ -3,8 +3,11 @@ package main import ( "fmt" "log" + "math/rand" + "net/http" "os" "regexp" + "time" "github.com/go-chat-bot/plugins/web" irc "github.com/thoj/go-ircevent" @@ -14,7 +17,8 @@ const channel = "#ctf" const ( pattern = "(?i)\\b(cat|gato|miau|meow|garfield|lolcat)[s|z]{0,1}\\b" - msgPrefix = "I love cats! Here's a fact: %s" + msgPrefix = "I love cats! Here's a fact: %s ^_^" + gifPrefix = "Meow! Here's a gif: %s ^_^" ) type catFact struct { @@ -41,15 +45,16 @@ func main() { e.Connection.Privmsg("nickserv", "identify "+os.Getenv("CTF2021PASS")) e.Connection.Join(channel) - e.Connection.Privmsg(channel, `I'm a cat facts bot!`) + e.Connection.Privmsg(channel, `I'm a cat bot!`) e.Connection.Privmsg(channel, `Inspired from https://github.com/go-chat-bot/plugins/blob/master/catfacts/catfacts.go`) - e.Connection.Privmsg(channel, `Try cat /etc/passwd ^_^`) + e.Connection.Privmsg(channel, `Try cat /etc/passwd :p`) e.Connection.Privmsg(channel, `Source code and issue tracker: https://gitea.difrex.ru/CTF2021/irc_bot`) + e.Connection.Privmsg(channel, `Now with gifs! ^_^`) }) irccon.AddCallback("PRIVMSG", func(e *irc.Event) { log.Printf("Message from %s received: %s", e.Nick, e.Message()) - catFacts(e.Message(), e.Connection) + doCommand(e.Message(), e.Connection) }) irccon.AddCallback("", func(e *irc.Event) {}) @@ -61,10 +66,39 @@ func main() { irccon.Loop() } -func catFacts(command string, con *irc.Connection) (string, error) { - if !re.MatchString(command) { - return "", nil +func doCommand(command string, con *irc.Connection) { + if ok := checkCommad(command, con); !ok { + return } + + rand.Seed(time.Now().UnixNano()) + i := rand.Intn(50) + fmt.Println(i) + if i > 30 { + catGif(con) + return + } + catFacts(con) +} + +func checkCommad(command string, con *irc.Connection) bool { + if !re.MatchString(command) { + return false + } + return true +} + +func catGif(con *irc.Connection) (string, error) { + res, err := http.Get("http://thecatapi.com/api/images/get?format=src&type=gif") + if err != nil { + return "", err + } + con.Privmsg(channel, fmt.Sprintf(gifPrefix, res.Request.URL.String())) + return fmt.Sprintf(gifPrefix, res.Request.URL.String()), nil +} + +func catFacts(con *irc.Connection) (string, error) { + data := &catFact{} err := web.GetJSON(catFactsURL, data) if err != nil {