forked from st3v/go-plugins
/
animate.go
84 lines (66 loc) · 1.45 KB
/
animate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package animate
/*
Animate command for the Micro Bot
usage: animate [text]
*/
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/micro/go-bot/command"
)
var (
// public giphy key
key = "dc6zaTOxFJmzC"
)
func init() {
command.Commands["^animate "] = Animate()
}
func Animate() command.Command {
usage := "animate [text]"
desc := "Returns an animation"
type Meta struct {
Status int `json:"status"`
Msg string `json:"msg"`
}
type Image struct {
Url string `json:"url"`
}
type Images struct {
FixedHeight Image `json:"fixed_height"`
}
type Result struct {
Images Images `json:"images"`
}
type Results struct {
Data []Result `json:"data"`
Meta Meta `json:"meta"`
}
return command.NewCommand("animate", usage, desc, func(args ...string) ([]byte, error) {
if len(args) < 2 {
return []byte("animate what?"), nil
}
u := url.Values{}
u.Set("q", strings.Join(args[1:], " "))
u.Set("limit", "1")
u.Set("api_key", key)
rsp, err := http.Get("http://api.giphy.com/v1/gifs/search?" + u.Encode())
if err != nil {
return nil, err
}
defer rsp.Body.Close()
var res Results
if err := json.NewDecoder(rsp.Body).Decode(&res); err != nil {
return nil, err
}
if res.Meta.Status != 200 {
return nil, fmt.Errorf("returned status: %d %s", res.Meta.Status, res.Meta.Msg)
}
if len(res.Data) == 0 {
return nil, nil
}
return []byte(res.Data[0].Images.FixedHeight.Url), nil
})
}