YouTube_API/youtube_api.py

156 lines
4.9 KiB
Python
Raw Normal View History

2023-12-09 18:35:19 +01:00
# -*- coding: utf-8 -*-
# Sample Python code for youtube.playlists.update
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/code-samples#python
import argparse
import os
2024-01-25 21:15:30 +01:00
import re
2023-12-09 18:35:19 +01:00
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
channels = {
2024-04-28 16:28:32 +02:00
"breakbeat_sesiones": "PLZFfy80_qguYVqbpQlX-aHdiYHTwc6-wW",
"breakbeat_temas": "PLZFfy80_qguZnpBYfSFlkMdjGIfVcz7e7",
2023-12-09 18:35:19 +01:00
"wods": "PLZFfy80_qguYCbTDQD0GSK4zUzEjbQMQT",
"rap_español": "PLZFfy80_qgub44wWWDcAykdQCJNCXo4jp",
}
2024-04-28 16:28:32 +02:00
2023-12-09 18:35:19 +01:00
def get_playlist_length(youtube, playlist_id):
2024-04-28 16:28:32 +02:00
items = youtube.playlists().list(part="snippet,contentDetails", id=playlist_id)
2023-12-09 18:35:19 +01:00
playlist_info = items.execute()
2024-04-28 16:28:32 +02:00
return playlist_info["items"][0]["contentDetails"]["itemCount"]
2023-12-09 18:35:19 +01:00
2024-01-27 17:31:59 +01:00
def list_songs(youtube, channel_id, stdout=False):
2024-01-25 21:15:30 +01:00
max_results = 50
request = youtube.playlistItems().list(
2024-04-28 16:28:32 +02:00
part="snippet,contentDetails", maxResults=max_results, playlistId=channel_id
2024-01-25 21:15:30 +01:00
)
response = request.execute()
print()
# Process the first page of results
2024-01-27 17:31:59 +01:00
deleted = 0
songs_list = []
2024-04-28 16:28:32 +02:00
for idx, item in enumerate(response["items"], start=1):
title = item["snippet"]["title"]
2024-01-27 17:31:59 +01:00
if title == "Deleted video":
deleted += 1
continue
songs_list.append(f"{idx-deleted:02d} - {title}")
2024-01-25 21:15:30 +01:00
# Continue making requests for additional pages using pageToken
new_starting = 51
2024-04-28 16:28:32 +02:00
while "nextPageToken" in response:
2024-01-25 21:15:30 +01:00
request = youtube.playlistItems().list(
2024-04-28 16:28:32 +02:00
part="snippet",
2024-01-25 21:15:30 +01:00
playlistId=channel_id,
maxResults=max_results,
2024-04-28 16:28:32 +02:00
pageToken=response["nextPageToken"],
2024-01-25 21:15:30 +01:00
)
response = request.execute()
2024-01-27 17:31:59 +01:00
2024-01-25 21:15:30 +01:00
# Process the results for the additional pages
2024-04-28 16:28:32 +02:00
for idx, item in enumerate(response["items"], start=new_starting):
title = item["snippet"]["title"]
2024-01-27 17:31:59 +01:00
if title == "Deleted video":
deleted += 1
2024-04-28 16:28:32 +02:00
continue
2024-01-27 17:31:59 +01:00
songs_list.append(f"{idx-deleted:02d} - {title}")
2024-01-25 21:15:30 +01:00
new_starting += 50
2024-04-28 16:28:32 +02:00
2024-01-27 17:31:59 +01:00
if stdout:
# Print to standard output
print("\n".join(songs_list))
2024-04-28 16:28:32 +02:00
# get_key_by_value = lambda dict, val: next(
# (k for k, v in dict.items() if v == val), None
# )
def _get_key_by_value(dict, val):
return next((k for k, v in dict.items() if v == val), None)
channel_name = _get_key_by_value(channels, channel_id)
2024-01-27 17:31:59 +01:00
# Save to file if output_file is provided
2024-04-28 16:28:32 +02:00
with open(f"{channel_name} songs", "w", encoding="utf-8") as file:
2024-01-27 17:31:59 +01:00
file.write("\n".join(songs_list))
2024-01-25 21:15:30 +01:00
2024-04-28 16:28:32 +02:00
print("\nList created successfully!")
2024-01-25 21:15:30 +01:00
def add_song(youtube, channel_id, song):
pos = get_playlist_length(youtube, channel_id)
request = youtube.playlistItems().insert(
part="snippet",
body={
"snippet": {
"playlistId": channel_id,
"position": pos,
2024-04-28 16:28:32 +02:00
"resourceId": {"kind": "youtube#video", "videoId": song},
2024-01-25 21:15:30 +01:00
}
2024-04-28 16:28:32 +02:00
},
2024-01-25 21:15:30 +01:00
)
2024-04-28 16:28:32 +02:00
# response = request.execute()
request.execute()
2024-01-25 21:15:30 +01:00
print("\nSong added successfully!")
2023-12-09 18:35:19 +01:00
def main():
2024-01-25 21:15:30 +01:00
parser = argparse.ArgumentParser(description="Manage YouTube playlist songs.")
2024-04-28 16:28:32 +02:00
parser.add_argument(
"-l", "--list", metavar="channel_name", help="List songs in the playlist"
)
parser.add_argument(
"-a", "--add", metavar="channel_name", help="Name of the playlist"
)
parser.add_argument("song", nargs="?", help="Name of the song")
2023-12-09 18:35:19 +01:00
args = parser.parse_args()
2024-04-28 16:28:32 +02:00
channel_name = args.add or args.list
2024-01-25 21:15:30 +01:00
channel_id = channels.get(channel_name)
2023-12-09 18:35:19 +01:00
2024-01-27 17:31:59 +01:00
if not args.list and not args.add:
parser.error("Please provide either -l or -a option.")
2024-01-25 21:15:30 +01:00
if not channel_id:
2023-12-09 18:35:19 +01:00
print(f"Error: Channel '{channel_name}' not found.")
return
# Disable OAuthlib's HTTPS verification when running locally.
# *DO NOT* leave this option enabled in production.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
2024-04-28 16:28:32 +02:00
# scopes is a global variable
2023-12-09 19:20:54 +01:00
client_secret = "./client_secrets.json"
2024-04-28 16:28:32 +02:00
flow = InstalledAppFlow.from_client_secrets_file(client_secret, scopes)
2023-12-09 18:35:19 +01:00
credentials = flow.run_local_server(port=0)
2024-04-28 16:28:32 +02:00
api_service_name = "youtube"
api_version = "v3"
youtube = build(api_service_name, api_version, credentials=credentials)
2023-12-09 18:35:19 +01:00
2024-01-25 21:15:30 +01:00
if args.list:
2024-01-27 17:31:59 +01:00
list_songs(youtube, channel_id, stdout=False)
2024-01-25 21:15:30 +01:00
elif args.add:
2024-04-28 16:28:32 +02:00
if not args.song:
parser.error("Please provide the name of the song with -a.")
song = args.song
# this assumes a song is passed as in either of the following ways
# https://youtu.be/eEnyi9L6KP4 --> split by "/"
# https://youtube.com/watch?v=Ez-gizOF0Wo --> split by "="
2024-01-25 21:15:30 +01:00
song = re.split(r"/|=", song)[-1]
2024-01-27 17:31:59 +01:00
add_song(youtube, channel_id, song)
2023-12-09 18:35:19 +01:00
2024-04-28 16:28:32 +02:00
2023-12-09 18:35:19 +01:00
if __name__ == "__main__":
2023-12-29 14:58:59 +01:00
main()