-
Notifications
You must be signed in to change notification settings - Fork 0
/
googlesearch.go
81 lines (70 loc) · 1.79 KB
/
googlesearch.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
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/osm/irc"
)
// initGoogleSearchDefaults initializes the default properties for the google
// search command
func (b *bot) initGoogleSearchDefaults() {
if b.IRC.GoogleSearchCmd == "" {
b.IRC.WeatherCmd = "!g"
}
}
// googleSearchCommandHandler handles the google search command.
func (b *bot) googleSearchCommandHandler(m *irc.Message) {
a := b.parseAction(m).(*privmsgAction)
if !a.validChannel {
return
}
if a.cmd != b.IRC.GoogleSearchCmd {
return
}
if b.shouldIgnore(m) {
return
}
if len(a.args) < 1 {
return
}
// Initialize a new client that doesn't follow redirects.
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
// Construct the I'm lucky URL.
url := fmt.Sprintf(
`https://www.google.com/search?q=%s&btnI=Jag+har+tur'`,
url.QueryEscape(strings.Join(a.args, " ")),
)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
b.logger.Printf("googleSearch: %v", err)
return
}
// Google doesn't allow us to search unless we have a "real" user
// agent.
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36")
req.Header.Set("Referer", "https://www.google.com/")
// Perform the request.
res, err := client.Do(req)
if err != nil {
b.logger.Printf("googleSearch: %v", err)
return
}
// Extract the location from the response.
l, err := res.Location()
if err != nil || l == nil {
b.logger.Printf("googleSearch: %v", err)
return
}
// The response should include a "q" parameter which holds the URL of
// the "I'm lucky" response.
p := l.Query()
if q, ok := p["q"]; ok && len(q) == 1 {
b.privmsg(q[0])
return
}
}