lofibeats/youtube.py

81 regels
2.2 KiB
Python

2021-05-01 09:54:06 -07:00
""" Wrapper to the YouTube API """
import logging
2021-04-30 10:53:01 -07:00
import googleapiclient.discovery
import wordfilter
2021-04-30 10:53:01 -07:00
import config
LOGGER = logging.getLogger(__name__)
2021-04-30 10:53:01 -07:00
2021-05-09 20:39:43 -07:00
YTAPI = googleapiclient.discovery.build('youtube', 'v3',
2021-05-11 09:58:20 -07:00
developerKey=config.API_KEY,
cache_discovery=False)
2023-04-26 13:35:34 -07:00
2023-01-28 01:03:25 -08:00
def get_region_codes():
""" get a list of all region codes """
# pylint:disable=no-member
request = YTAPI.i18nRegions().list(part="snippet")
response = request.execute()
return [item['id'] for item in response['items']]
2023-04-26 13:35:34 -07:00
2023-01-28 01:03:25 -08:00
def get_topic_id(region, name):
""" try to find the music category """
# pylint:disable=no-member
2023-04-26 13:35:34 -07:00
request = YTAPI.videoCategories().list(part="snippet", regionCode=region)
response = request.execute()
if 'items' not in response:
LOGGER.warning("No categories found")
return None
for item in response['items']:
if name in item['snippet']['title'].lower():
return item['id']
LOGGER.warning(f"No {name} category found")
return None
2021-04-30 10:53:01 -07:00
2023-01-28 01:03:25 -08:00
def get_videos(query, **kwargs):
2021-05-09 20:39:43 -07:00
""" Given a search query, return a list of video IDs """
2021-05-11 09:58:20 -07:00
# pylint:disable=no-member
2021-05-09 20:39:43 -07:00
request = YTAPI.search().list(
2021-04-30 10:53:01 -07:00
part="snippet",
q=query,
2023-01-28 01:03:25 -08:00
maxResults=100,
**kwargs
2021-04-30 10:53:01 -07:00
)
response = request.execute()
2021-05-01 09:54:06 -07:00
if 'items' not in response:
LOGGER.warning("No items found")
return []
wfilter = wordfilter.Wordfilter()
2021-05-09 20:39:43 -07:00
return [(item["id"]["videoId"], item['snippet'])
2021-05-01 09:54:06 -07:00
for item in response['items']
if 'id' in item
and 'videoId' in item['id']
and not wfilter.blacklisted(
item['snippet'].get('title', '')
+ item['snippet'].get('description', ''))]
2021-04-30 10:53:01 -07:00
2021-05-11 09:58:20 -07:00
2021-05-09 20:39:43 -07:00
def get_details(vid):
""" Given a video ID, get the content details """
2021-05-11 09:58:20 -07:00
# pylint:disable=no-member
2021-05-09 20:39:43 -07:00
request = YTAPI.videos().list(part="contentDetails",
2021-05-11 09:58:20 -07:00
id=vid)
2021-05-09 20:39:43 -07:00
response = request.execute()
for item in response['items']:
if item['id'] == vid:
return item['contentDetails']
return None
2021-04-30 10:53:01 -07:00
if __name__ == "__main__":
2021-05-01 09:54:06 -07:00
print(get_videos("+lofi beats to chill and relax to"))