|
|
|
import os |
|
import googleapiclient.discovery |
|
import googleapiclient.errors |
|
import streamlit as st |
|
|
|
api_key = st.secrets['API_KEY'] |
|
|
|
|
|
def get_comments(youtube, **kwargs): |
|
""" |
|
Fetch comments from a YouTube video using the YouTube API. |
|
Parameters: |
|
youtube (Resource): A resource object for interacting with the YouTube API. |
|
**kwargs: Additional parameters for the API request. |
|
Returns: |
|
list: A list of comments from the video. |
|
""" |
|
comments = [] |
|
results = youtube.commentThreads().list(**kwargs).execute() |
|
|
|
while results: |
|
for item in results['items']: |
|
comment = item['snippet']['topLevelComment']['snippet']['textDisplay'] |
|
comments.append(comment) |
|
|
|
|
|
if 'nextPageToken' in results: |
|
kwargs['pageToken'] = results['nextPageToken'] |
|
results = youtube.commentThreads().list(**kwargs).execute() |
|
else: |
|
break |
|
|
|
return comments |
|
|
|
|
|
def main(video_id, api_key): |
|
""" |
|
Main function to retrieve comments from a specific YouTube video. |
|
Parameters: |
|
video_id (str): The ID of the YouTube video. |
|
api_key (str): The API key for accessing YouTube API. |
|
Returns: |
|
list: A list of comments from the specified video. |
|
""" |
|
|
|
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" |
|
|
|
|
|
youtube = googleapiclient.discovery.build( |
|
"youtube", "v3", developerKey=api_key) |
|
|
|
|
|
comments = get_comments(youtube, part="snippet", videoId=video_id, textFormat="plainText") |
|
return comments |
|
|
|
|
|
def get_video_comments(video_id): |
|
""" |
|
Wrapper function to get comments for a video using the main function. |
|
Parameters: |
|
video_id (str): The ID of the YouTube video. |
|
Returns: |
|
list: A list of comments from the specified video. |
|
""" |
|
|
|
return main(video_id, api_key) |
|
|