|
import requests |
|
import os |
|
|
|
YT_API_KEY = os.getenv("YT_API_KEY") |
|
|
|
def get_latest_video_id(channel_id, device_name=None, playlist_id=None): |
|
if device_name is None and playlist_id is None: |
|
raise Exception("Must specify either device_name or playlist_id") |
|
|
|
if device_name is not None and playlist_id is not None: |
|
print("Both device_name and playlist_id entered.. device_name will be ignored.") |
|
|
|
if playlist_id is None: |
|
|
|
url = 'https://www.googleapis.com/youtube/v3/playlists' |
|
params = { |
|
'part': 'snippet', |
|
'channelId': channel_id, |
|
'maxResults': 1000, |
|
'key': YT_API_KEY |
|
} |
|
res = requests.get(url, params=params) |
|
res.raise_for_status() |
|
playlists = res.json().get("items", []) |
|
|
|
for p in playlists: |
|
if device_name.lower() in p["snippet"]["title"].lower(): |
|
playlist_id = p["id"] |
|
break |
|
|
|
if not playlist_id: |
|
raise Exception(f"No playlist found matching device name '{device_name}'") |
|
|
|
|
|
url = 'https://www.googleapis.com/youtube/v3/search' |
|
params = { |
|
'part': 'snippet', |
|
'channelId': channel_id, |
|
'maxResults': 1, |
|
'order': 'date', |
|
'type': 'video', |
|
'key': YT_API_KEY |
|
} |
|
|
|
|
|
|
|
if playlist_id: |
|
|
|
playlist_url = 'https://www.googleapis.com/youtube/v3/playlistItems' |
|
playlist_params = { |
|
'part': 'snippet,contentDetails', |
|
'playlistId': playlist_id, |
|
'maxResults': 10, |
|
'key': YT_API_KEY |
|
} |
|
|
|
playlist_res = requests.get(playlist_url, params=playlist_params) |
|
playlist_res.raise_for_status() |
|
playlist_items = playlist_res.json().get("items", []) |
|
|
|
if not playlist_items: |
|
return None |
|
|
|
|
|
sorted_items = sorted( |
|
playlist_items, |
|
key=lambda x: x["snippet"].get("publishedAt", ""), |
|
reverse=True |
|
) |
|
|
|
|
|
return sorted_items[0]["snippet"]["resourceId"]["videoId"] |
|
|
|
|
|
res = requests.get(url, params=params) |
|
res.raise_for_status() |
|
items = res.json().get("items", []) |
|
|
|
if not items: |
|
return None |
|
|
|
return items[0]["id"]["videoId"] |