File size: 1,613 Bytes
06c5fb9
 
 
c37360f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d852d89
 
 
 
 
c37360f
 
d852d89
c37360f
 
 
d852d89
06c5fb9
 
c37360f
 
 
 
 
d852d89
 
 
 
c37360f
 
d852d89
c37360f
d852d89
c37360f
 
 
 
06c5fb9
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
from config import YOUTUBE_API_KEY


def _get_client():
    """Inisialisasi YouTube client di dalam fungsi, bukan module level."""
    if not YOUTUBE_API_KEY:
        print("⚠️  YOUTUBE_API_KEY tidak diset")
        return None
    try:
        from googleapiclient.discovery import build
        return build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
    except Exception as e:
        print(f"❌ Gagal init YouTube client: {e}")
        return None


def search_videos(keyword: str, max_results: int = 3) -> list:
    youtube = _get_client()
    if not youtube:
        return []
    try:
        res = youtube.search().list(
            part="snippet",
            q=keyword,
            type="video",
            maxResults=max_results,
            relevanceLanguage="id"
        ).execute()
        return [item['id']['videoId'] for item in res.get('items', [])]
    except Exception as e:
        print(f"❌ YouTube search error: {e}")
        return []


def get_comments(video_id: str, max_results: int = 50) -> list:
    youtube = _get_client()
    if not youtube:
        return []
    comments = []
    try:
        res = youtube.commentThreads().list(
            part="snippet",
            videoId=video_id,
            maxResults=max_results,
            textFormat="plainText"
        ).execute()
        for item in res.get('items', []):
            text = item['snippet']['topLevelComment']['snippet']['textDisplay']
            if text.strip():
                comments.append(text)
    except Exception as e:
        print(f"❌ YouTube get_comments error: {e}")
    return comments