41 lines
1.6 KiB
Python
41 lines
1.6 KiB
Python
from youtube import util
|
|
import flask
|
|
import os
|
|
|
|
def get_youtube_cookies():
|
|
"""Read cookies.txt and return a dict of cookies for YouTube requests."""
|
|
cookies_path = os.path.join(os.path.dirname(__file__), 'cookies.txt')
|
|
cookies = {}
|
|
if os.path.isfile(cookies_path):
|
|
with open(cookies_path, 'r', encoding='utf-8') as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if not line or line.startswith('#') or '=' not in line:
|
|
continue
|
|
k, v = line.split('=', 1)
|
|
cookies[k.strip()] = v.strip()
|
|
return cookies
|
|
|
|
def get_recommended_videos():
|
|
# Use YouTube's browse API to get the home feed (recommended videos)
|
|
data = {"browseId": "FEwhat_to_watch"}
|
|
cookies = get_youtube_cookies()
|
|
response = util.call_youtube_api("web", "browse", data, cookies=cookies)
|
|
response_json = flask.json.loads(response)
|
|
# Extract video list from response_json
|
|
try:
|
|
contents = response_json["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][0]["tabRenderer"]["content"]["richGridRenderer"]["contents"]
|
|
videos = []
|
|
for item in contents:
|
|
renderer = item.get("richItemRenderer", {}).get("content", {}).get("videoRenderer")
|
|
if renderer:
|
|
videos.append(renderer)
|
|
# If no videos found, check for nudge/empty feed
|
|
if not videos:
|
|
print("No recommended videos found. YouTube may require login or watch history.")
|
|
return videos
|
|
except Exception as e:
|
|
print("Error extracting recommended videos:", e)
|
|
print("Response JSON:", response_json)
|
|
return []
|