I am trying to set up a program that will automatically change my YouTube banner. I thought it would be really cool to have if swap between multiple different banner images that people might make for me. But the implementation I found requires the user to input the authorization code from.
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.http import MediaFileUpload
CLIENT_SECRET_FILE = 'client_secret.json'
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
credentials = flow.run_console()
youtube = build('youtube', 'v3', api_key=apikey)
request = youtube.channelBanners().insert(
channelId="",
body={},
media_body=MediaFileUpload("image.jpg")
)
response = request.execute()
print(response)
Short hand: Is there a good way to update a YouTube banner with a basic script running on a server?
If you run something like this locally once and authorize it. it will store the user credentials in token.json. As long as you upload that along with your code to your server the next time it runs it should just load the authorization from that.
from __future__ import print_function
import os.path
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
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
def main():
"""Shows basic usage of the YouTube API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('youtube', 'v3', credentials=creds)
# Call the Youtube v3 API
request = service.channelBanners().insert(
channelId="",
body={},
media_body=MediaFileUpload("image.jpg")
)
response = request.execute()
print(response)
if __name__ == '__main__':
main()