Skip to content

Instantly share code, notes, and snippets.

@samvignoli
Created July 25, 2024 15:37
Show Gist options
  • Save samvignoli/6661ae278c695acdd1a85ce52c67675e to your computer and use it in GitHub Desktop.
Save samvignoli/6661ae278c695acdd1a85ce52c67675e to your computer and use it in GitHub Desktop.
import os
import google.auth
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Define o escopo e o ID do canal
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
CHANNEL_ID = 'UCpypU2XLYmOsf36xgcgrW3w'
LANGUAGE = 'pt-BR'
def authenticate_youtube():
creds = None
# O arquivo token.json armazena os tokens de acesso e atualização do usuário e é
# criado automaticamente quando o fluxo de autorização é concluído pela primeira vez.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# Se não houver credenciais (ou se forem inválidas), faça login para obtê-las.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json', SCOPES)
creds = flow.run_local_server(port=0)
# Salva as credenciais para uso futuro
with open('token.json', 'w') as token:
token.write(creds.to_json())
return build('youtube', 'v3', credentials=creds)
def get_all_videos(youtube, channel_id):
videos = []
request = youtube.search().list(
part='id',
channelId=channel_id,
maxResults=50,
type='video'
)
response = request.execute()
while response:
for item in response['items']:
videos.append(item['id']['videoId'])
if 'nextPageToken' in response:
request = youtube.search().list(
part='id',
channelId=channel_id,
maxResults=50,
pageToken=response['nextPageToken'],
type='video'
)
response = request.execute()
else:
break
return videos
def update_video_language(youtube, video_id, language):
# Primeiro, obtenha os detalhes do snippet atual do vídeo
video_details = youtube.videos().list(
part='snippet',
id=video_id
).execute()
if 'items' in video_details and len(video_details['items']) > 0:
snippet = video_details['items'][0]['snippet']
snippet['defaultLanguage'] = language
youtube.videos().update(
part='snippet',
body={
'id': video_id,
'snippet': snippet
}
).execute()
def main():
youtube = authenticate_youtube()
videos = get_all_videos(youtube, CHANNEL_ID)
for video_id in videos:
update_video_language(youtube, video_id, LANGUAGE)
print(f'Updated video {video_id} to language {LANGUAGE}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment