-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl_xkcd.go
69 lines (54 loc) · 1.3 KB
/
url_xkcd.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
package url
import (
"io"
"net/http"
"net/url"
"regexp"
"github.com/seabird-chat/seabird-go/pb"
"github.com/yhat/scrape"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var xkcdRegex = regexp.MustCompile(`^/([^/]+)$`)
var xkcdPrefix = "[XKCD]"
func NewXKCDProvider() *XKCDProvider {
return &XKCDProvider{}
}
type XKCDProvider struct{}
func (p *XKCDProvider) GetCallbacks() map[string]URLCallback {
return map[string]URLCallback{
"xkcd.com": handleXKCD,
}
}
func (p *XKCDProvider) GetMessageCallback() MessageCallback {
return nil
}
func handleXKCD(c *Client, source *pb.ChannelSource, u *url.URL) bool {
if u.Path != "" && !xkcdRegex.MatchString(u.Path) {
return false
}
resp, err := http.Get(u.String())
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false
}
// We search the first 1K and if a title isn't in there, we deal with it
z, err := html.Parse(io.LimitReader(resp.Body, 1024*1024))
if err != nil {
return false
}
// Scrape the tree for the first title node we find
n, ok := scrape.Find(z, scrape.ById("comic"))
if !ok {
return false
}
n, ok = scrape.Find(n, scrape.ByTag(atom.Img))
if !ok {
return false
}
c.Replyf(source, "%s %s: %s", xkcdPrefix, scrape.Attr(n, "alt"), scrape.Attr(n, "title"))
return true
}