|
|
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': 50, |
|
|
'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/playlistItems' |
|
|
params = { |
|
|
'part': 'snippet', |
|
|
'playlistId': playlist_id, |
|
|
'maxResults': 1, |
|
|
'key': YT_API_KEY |
|
|
} |
|
|
res = requests.get(url, params=params) |
|
|
res.raise_for_status() |
|
|
items = res.json().get("items", []) |
|
|
|
|
|
if not items: |
|
|
return None |
|
|
|
|
|
return items[0]["snippet"]["resourceId"]["videoId"] |