-
Notifications
You must be signed in to change notification settings - Fork 15
/
youtube.go
78 lines (67 loc) · 2.11 KB
/
youtube.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
package jarvisbot
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/tucnak/telebot"
)
const youtubeSearchEndpoint = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=4&type=video&q=%s&key=%s"
const youtubeVideoBaseURL = "https://www.youtube.com/watch?v="
func (j *JarvisBot) YoutubeSearch(msg *message) {
if len(msg.Args) == 0 {
so := &telebot.SendOptions{ReplyTo: *msg.Message, ReplyMarkup: telebot.ReplyMarkup{ForceReply: true, Selective: true}}
j.SendMessage(msg.Chat, "/youtube: Does a Youtube search\nHere are some commands to try: \n* unbelievable spouse for house\n* okgo\n\n\U0001F4A1 You could also use this format for faster results:\n/yt okgo", so)
return
}
rawQuery := ""
for _, v := range msg.Args {
rawQuery = rawQuery + v + " "
}
rawQuery = strings.TrimSpace(rawQuery)
q := url.QueryEscape(rawQuery)
key := j.keys.YoutubeAPIKey
if key == "" {
j.log.Printf("[%s] tried to do a video search, but no Youtube api key!", time.Now().Format(time.RFC3339))
return
}
urlString := fmt.Sprintf(youtubeSearchEndpoint, q, key)
resp, err := http.Get(urlString)
if err != nil {
j.log.Printf("failure retrieving videos from Youtube for query '%s': %s", q, err)
return
}
jsonBody, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
j.log.Printf("failure reading json results from Youtube video search for query '%s': %s", q, err)
return
}
searchRes := struct {
Items []struct {
Id struct {
VideoId string `json:"videoId"`
} `json:"id"`
Snippet struct {
Title string `json:"title"`
} `json:"snippet"`
} `json:"items"`
}{}
err = json.Unmarshal(jsonBody, &searchRes)
if err != nil {
j.log.Printf("failure unmarshalling json for Youtube search query '%s': %s", q, err)
return
}
resMsg := ""
if len(searchRes.Items) > 0 {
for _, v := range searchRes.Items {
resMsg = resMsg + fmt.Sprintf("%s%s - %s\n", youtubeVideoBaseURL, v.Id.VideoId, v.Snippet.Title)
}
j.SendMessage(msg.Chat, resMsg, nil)
} else {
j.SendMessage(msg.Chat, "My Youtube search returned nothing. \U0001F622", nil)
}
}