/
images.go
60 lines (47 loc) · 1.37 KB
/
images.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
package bing
import (
"encoding/json"
"fmt"
"github.com/0x263b/porygon2"
"io/ioutil"
"net/http"
"net/url"
)
const (
imageURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=%s&count=1&mkt=en-us&safeSearch=Off"
)
type ImageResults struct {
Value []struct {
ContentURL string `json:"contentUrl"`
ContentSize string `json:"contentSize"`
EncodingFormat string `json:"encodingFormat"`
} `json:"value"`
}
func image(command *bot.Cmd, matches []string) (msg string, err error) {
client := &http.Client{}
request, _ := http.NewRequest("GET", fmt.Sprintf(imageURL, url.QueryEscape(matches[1])), nil)
request.Header.Set("Ocp-Apim-Subscription-Key", bot.Config.Bing)
response, _ := client.Do(request)
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
var results ImageResults
json.Unmarshal(body, &results)
if err != nil {
return fmt.Sprintf("No results for %s", matches[1]), nil
}
if len(results.Value) == 0 {
return fmt.Sprintf("No results for %s", matches[1]), nil
}
pageURL := results.Value[0].ContentURL
transport := http.Transport{}
request, _ = http.NewRequest("HEAD", pageURL, nil)
response, _ = transport.RoundTrip(request)
pageURL = response.Header.Get("Location")
output := fmt.Sprintf("Bing | %s | %s", matches[1], pageURL)
return output, nil
}
func init() {
bot.RegisterCommand(
"^img (.+)$",
image)
}