YouTube_API/youtube_api.py

137 lines
4.1 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
import googleapiclient.errors
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
channels = {
2023-12-29 14:58:59 +01: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",
}
def get_playlist_length(youtube, playlist_id):
items = youtube.playlists().list(
part="snippet,contentDetails",
id=playlist_id
)
playlist_info = items.execute()
return playlist_info['items'][0]['contentDetails']['itemCount']
2024-01-25 21:15:30 +01:00
def list_songs(youtube, channel_id):
max_results = 50
request = youtube.playlistItems().list(
part="snippet,contentDetails",
maxResults=max_results,
playlistId=channel_id
)
response = request.execute()
print()
# Process the first page of results
for idx, item in enumerate(response['items'], start=1):
title = item['snippet']['title']
print(f"{idx:02d} - {title}")
# Continue making requests for additional pages using pageToken
new_starting = 51
while 'nextPageToken' in response:
request = youtube.playlistItems().list(
part='snippet',
playlistId=channel_id,
maxResults=max_results,
pageToken=response['nextPageToken']
)
response = request.execute()
# Process the results for the additional pages
for idx, item in enumerate(response['items'], start=new_starting):
title = item['snippet']['title']
print(f"{idx:02d} - {title}")
new_starting += 50
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,
"resourceId": {
"kind": "youtube#video",
"videoId": song
}
}
}
)
response = request.execute()
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.")
2023-12-09 18:35:19 +01:00
parser.add_argument("channel_name", help="Name of the YouTube channel")
2024-01-25 21:15:30 +01:00
parser.add_argument(
"--list",
action="store_true",
help="List all songs in the playlist"
)
parser.add_argument(
"--add",
nargs=2,
metavar=("channel", "song"),
help="Add to the playlist a song"
)
2023-12-09 18:35:19 +01:00
args = parser.parse_args()
channel_name = args.channel_name
2024-01-25 21:15:30 +01:00
channel_id = channels.get(channel_name)
2023-12-09 18:35:19 +01:00
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"
api_service_name = "youtube"
api_version = "v3"
2023-12-09 19:20:54 +01:00
client_secret = "./client_secrets.json"
2023-12-09 18:35:19 +01:00
flow = InstalledAppFlow.from_client_secrets_file(
client_secret, scopes)
credentials = flow.run_local_server(port=0)
youtube = build(
api_service_name, api_version,
credentials=credentials)
2024-01-25 21:15:30 +01:00
if args.list:
list_songs(youtube, channel_id)
elif args.add:
target_channel, song = args.add
# # 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 "="
song = re.split(r"/|=", song)[-1]
add_song(youtube, channels.get(target_channel), song)
else:
print("Invalid command. Use --list or --add.")
2023-12-09 18:35:19 +01:00
if __name__ == "__main__":
2023-12-29 14:58:59 +01:00
main()