package gifmeme import ( "fmt" "github.com/jmoiron/sqlx" "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/config" "github.com/velour/catbase/plugins/meme" "net/url" "path" "regexp" "strings" ) type gifMap map[string][]byte // Plugin creates gifs with text type Plugin struct { b bot.Bot c *config.Config db *sqlx.DB h bot.HandlerTable gifs gifMap } // New creates a new Plugin func New(b bot.Bot) *Plugin { p := &Plugin{ b: b, c: b.Config(), db: b.DB(), gifs: make(gifMap), } p.register() p.registerWeb() return p } func (p *Plugin) register() { p.h = bot.HandlerTable{ { Kind: bot.Message, IsCmd: true, Regex: regexp.MustCompile(`(?i)^gifmeme (?P\S+) (?P.+)$`), Handler: p.gifmemeCmd, }, } p.b.RegisterTable(p, p.h) } func (p *Plugin) gifmemeCmd(r bot.Request) bool { gifs := p.c.GetMap("gifmeme.memes", map[string]string{ "key": "https://media.giphy.com/media/3o6Zt4HU9uwXmXSAuI/giphy.gif", }) u, err := url.Parse(gifs[r.Values["gif"]]) if checkErr(p.b, r, err) { return true } texts := strings.Split(r.Values["text"], "||") configs := []meme.Text{} // do this till we have configs for _, t := range texts { configs = append(configs, meme.Text{ XPerc: 0.5, YPerc: 0.9, Text: t, Caps: true, }) } s := meme.Specification{ ImageURL: u.String(), Configs: configs, } gif, w, h, err := getGif(p.c, s) if checkErr(p.b, r, err) { return true } log.Debug().Msgf("Saving gif %s, len: %d", s.ID(), len(gif)) p.gifs[s.ID()] = gif u = p.urlForGif(s) p.b.Send(r.Conn, bot.Message, r.Msg.Channel, u.String()) p.b.Send(r.Conn, bot.Message, r.Msg.Channel, "", bot.ImageAttachment{ URL: u.String(), AltTxt: fmt.Sprintf("%v", texts), Width: w, Height: h, }) return true } func (p *Plugin) urlForGif(s meme.Specification) *url.URL { baseURL := p.c.Get("BaseURL", "") u, _ := url.Parse(baseURL) u.Path = path.Join(u.Path, "gifmeme", "api", "gif", s.ID()+".gif") return u } func checkErr(b bot.Bot, r bot.Request, err error) bool { if err != nil { msg := fmt.Sprintf("Error: %s", err) b.Send(r.Conn, bot.Message, r.Msg.Channel, msg) return true } return false }