Spaces:
Sleeping
Sleeping
Update services/youtube.py
Browse files- services/youtube.py +34 -16
services/youtube.py
CHANGED
|
@@ -1,35 +1,53 @@
|
|
| 1 |
-
from googleapiclient.discovery import build
|
| 2 |
from config import YOUTUBE_API_KEY
|
| 3 |
|
| 4 |
-
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
|
| 5 |
|
| 6 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
try:
|
| 8 |
res = youtube.search().list(
|
| 9 |
part="snippet",
|
| 10 |
q=keyword,
|
| 11 |
type="video",
|
| 12 |
-
maxResults=max_results
|
|
|
|
| 13 |
).execute()
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
return []
|
| 18 |
|
| 19 |
-
def get_comments(video_id):
|
| 20 |
-
comments = []
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
try:
|
| 23 |
res = youtube.commentThreads().list(
|
| 24 |
part="snippet",
|
| 25 |
videoId=video_id,
|
| 26 |
-
maxResults=
|
|
|
|
| 27 |
).execute()
|
| 28 |
-
|
| 29 |
-
for item in res['items']:
|
| 30 |
text = item['snippet']['topLevelComment']['snippet']['textDisplay']
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
return comments
|
|
|
|
|
|
|
| 1 |
from config import YOUTUBE_API_KEY
|
| 2 |
|
|
|
|
| 3 |
|
| 4 |
+
def _get_client():
|
| 5 |
+
"""Inisialisasi YouTube client di dalam fungsi, bukan module level."""
|
| 6 |
+
if not YOUTUBE_API_KEY:
|
| 7 |
+
print("⚠️ YOUTUBE_API_KEY tidak diset")
|
| 8 |
+
return None
|
| 9 |
+
try:
|
| 10 |
+
from googleapiclient.discovery import build
|
| 11 |
+
return build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
|
| 12 |
+
except Exception as e:
|
| 13 |
+
print(f"❌ Gagal init YouTube client: {e}")
|
| 14 |
+
return None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def search_videos(keyword: str, max_results: int = 3) -> list:
|
| 18 |
+
youtube = _get_client()
|
| 19 |
+
if not youtube:
|
| 20 |
+
return []
|
| 21 |
try:
|
| 22 |
res = youtube.search().list(
|
| 23 |
part="snippet",
|
| 24 |
q=keyword,
|
| 25 |
type="video",
|
| 26 |
+
maxResults=max_results,
|
| 27 |
+
relevanceLanguage="id"
|
| 28 |
).execute()
|
| 29 |
+
return [item['id']['videoId'] for item in res.get('items', [])]
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"❌ YouTube search error: {e}")
|
| 32 |
return []
|
| 33 |
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
def get_comments(video_id: str, max_results: int = 50) -> list:
|
| 36 |
+
youtube = _get_client()
|
| 37 |
+
if not youtube:
|
| 38 |
+
return []
|
| 39 |
+
comments = []
|
| 40 |
try:
|
| 41 |
res = youtube.commentThreads().list(
|
| 42 |
part="snippet",
|
| 43 |
videoId=video_id,
|
| 44 |
+
maxResults=max_results,
|
| 45 |
+
textFormat="plainText"
|
| 46 |
).execute()
|
| 47 |
+
for item in res.get('items', []):
|
|
|
|
| 48 |
text = item['snippet']['topLevelComment']['snippet']['textDisplay']
|
| 49 |
+
if text.strip():
|
| 50 |
+
comments.append(text)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"❌ YouTube get_comments error: {e}")
|
| 53 |
return comments
|