File size: 1,646 Bytes
c99920e
359d9e4
 
 
c99920e
ea47c47
c99920e
 
 
 
 
 
 
 
 
 
 
 
 
 
359d9e4
c99920e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359d9e4
c99920e
 
 
 
 
 
 
 
 
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
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:
      # Step 1: get all playlists from the channel (note that 'playlists' in url)
      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}'")

    # Step 2: get the most recent video from the playlist
    # NOTE: (This grabs the video most recently *added* to the playlist)
    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"]