File size: 2,721 Bytes
fa7aa9f c4ad43e fa7aa9f c4ad43e 87738ea fa7aa9f |
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 73 74 75 76 77 78 79 |
import os
import googleapiclient.discovery
import googleapiclient.errors
from dotenv import load_dotenv
# from dotenv import load_dotenv
import streamlit as st
load_dotenv()
api_key = os.getenv("API_KEY")
# api_key = st.secrets["API_KEY"]
def get_comments(youtube, **kwargs):
comments = []
results = youtube.commentThreads().list(**kwargs).execute()
while results:
for item in results["items"]:
comment = item["snippet"]["topLevelComment"]["snippet"]["textDisplay"]
comments.append(comment)
# check if there are more comments
if "nextPageToken" in results:
kwargs["pageToken"] = results["nextPageToken"]
results = youtube.commentThreads().list(**kwargs).execute()
else:
break
return comments
def main(video_id, api_key):
# Disable OAuthlib's HTTPs verification when running locally.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
youtube = googleapiclient.discovery.build("youtube", "v3", developerKey=api_key)
video_title = "N/A" # Provide a default title
try:
# Get video details using the videos().list endpoint
print(f"DEBUG (youtube.py): Fetching video details for ID: {video_id}")
video_response = (
youtube.videos()
.list(
part="snippet", # 'snippet' contains title, description, channel etc.
id=video_id, # The ID of the video we want info for
)
.execute()
)
# Extract the title from the response
# It's usually nested like this, good to check if 'items' exists
if video_response.get("items"):
video_title = video_response["items"][0]["snippet"]["title"]
print(f"DEBUG (youtube.py): Found title: '{video_title}'") # Just a check
else:
print(f"WARN (youtube.py): No video items found for ID: {video_id}")
video_title = "Video Not Found or Private" # More informative default
except Exception as e:
print(
f"ERROR (youtube.py): Failed to fetch video title for ID {video_id}. Error: {e}"
)
video_title = "Error Fetching Title" # Error specific default
# Depending on requirements, maybe we still want to proceed to get comments?
comments = get_comments(
youtube, part="snippet", videoId=video_id, textFormat="plainText"
)
# return comments
# Return a dictionary containing both title and comments
return {"title": video_title, "comments": comments}
def get_video_comments(video_id):
return main(video_id, api_key)
|