-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathyoutube.go
72 lines (53 loc) · 1.43 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
package youtube
import (
"context"
"errors"
"log"
"google.golang.org/api/option"
youtube "google.golang.org/api/youtube/v3"
)
type Order string
const (
OrderRelevance Order = "relevance"
OrderTime Order = "time"
)
type Client struct {
apiKey string
}
func New(apiKey string) *Client {
c := &Client{apiKey: apiKey}
return c
}
func (c *Client) GetComments(videoId string, order Order, maxComments int) ([]string, error) {
comments := []string{}
ctx := context.Background()
ctx, cancelCtxFunc := context.WithCancel(ctx)
youtubeService, err := youtube.NewService(ctx, option.WithAPIKey(c.apiKey))
if err != nil {
cancelCtxFunc()
return nil, err
}
commentThreadsService := youtube.NewCommentThreadsService(youtubeService)
// Get the instance with which we can do api calls to the youtube api
apiCall := commentThreadsService.List("snippet")
apiCall.TextFormat("plainText")
apiCall.VideoId(videoId)
apiCall.Order(string(order))
err = apiCall.Pages(ctx, func(resp *youtube.CommentThreadListResponse) error {
for _, item := range resp.Items {
c := item.Snippet.TopLevelComment.Snippet.TextDisplay
comments = append(comments, c)
lenComments := len(comments)
log.Printf("%d/%d comments fetched!", lenComments, maxComments)
if lenComments == maxComments {
cancelCtxFunc()
break
}
}
return nil
})
if err != nil && !errors.Is(err, context.Canceled) {
return nil, err
}
return comments, nil
}