sgbaird commited on
Commit
c99920e
·
verified ·
1 Parent(s): 1f18424

Create yt_utils.py

Browse files
Files changed (1) hide show
  1. yt_utils.py +48 -0
yt_utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ def get_latest_video_from_device_playlist(channel_id, device_name=None, playlist_id=None):
4
+
5
+ if device_name is None and playlist_id is None:
6
+ raise Exception("Must specify either device_name or playlist_id")
7
+
8
+ if device_name is not None and playlist_id is not None:
9
+ print("Both device_name and playlist_id entered.. device_name will be ignored.")
10
+
11
+ if playlist_id is None:
12
+ # Step 1: get all playlists from the channel (note that 'playlists' in url)
13
+ url = 'https://www.googleapis.com/youtube/v3/playlists'
14
+ params = {
15
+ 'part': 'snippet',
16
+ 'channelId': CHANNEL_ID,
17
+ 'maxResults': 50,
18
+ 'key': API_KEY
19
+ }
20
+ res = requests.get(url, params=params)
21
+ res.raise_for_status()
22
+ playlists = res.json().get("items", [])
23
+
24
+ for p in playlists:
25
+ if device_name.lower() in p["snippet"]["title"].lower():
26
+ playlist_id = p["id"]
27
+ break
28
+
29
+ if not playlist_id:
30
+ raise Exception(f"No playlist found matching device name '{device_name}'")
31
+
32
+ # Step 2: get the most recent video from the playlist
33
+ # NOTE: (This grabs the video most recently *added* to the playlist)
34
+ url = 'https://www.googleapis.com/youtube/v3/playlistItems'
35
+ params = {
36
+ 'part': 'snippet',
37
+ 'playlistId': playlist_id,
38
+ 'maxResults': 1,
39
+ 'key': API_KEY
40
+ }
41
+ res = requests.get(url, params=params)
42
+ res.raise_for_status()
43
+ items = res.json().get("items", [])
44
+
45
+ if not items:
46
+ return None
47
+
48
+ return items[0]["snippet"]["resourceId"]["videoId"]