-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyt_api.py
54 lines (40 loc) · 1.47 KB
/
yt_api.py
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
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import re
import streamlit as st
def extract_video_id(url):
regex = (
r'(?:https?://)?(?:www\.)?(?:youtube\.com/(?:watch\?v=|embed/|v/|shorts/|.+\?v=)|youtu\.be/)' +
r'([a-zA-Z0-9_-]{11})'
)
match = re.search(regex, url)
if match:
return match.group(1)
return None
def video_comments(video_id):
all_comments = []
try:
# api_key = st.secrets["api_keys"]["AIzaSyB0gTkqh5TE0uUBGwt6vUW211pAFnT6p-s"]
youtube = build('youtube', 'v3', developerKey="AIzaSyB0gTkqh5TE0uUBGwt6vUW211pAFnT6p-s")
video_response = youtube.commentThreads().list(
part='snippet',
videoId=video_id,
maxResults=100
).execute()
while video_response:
for item in video_response['items']:
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
all_comments.append(comment)
if 'nextPageToken' in video_response:
video_response = youtube.commentThreads().list(
part='snippet',
videoId=video_id,
pageToken=video_response['nextPageToken'],
maxResults=100
).execute()
else:
break
except HttpError as e:
print(f"An error occurred: {e}")
return []
return all_comments