Develop a system for capturing my youtube history and creating a google sheet using…
- User
Develop a system for capturing my youtube history and creating a google sheet using automation
- Assistant
Develop a system for capturing my youtube history and creating a google sheet using automation
Certainly! Capturing your YouTube watch history and automating it into a Google Sheet involves interacting with the YouTube Data API and Google Sheets API. Below is a step-by-step guide to set up an automated system using Python. This system will:
google-authgoogle-auth-oauthlibgoogle-auth-httplib2google-api-python-clientpandascredentials.json file.Open your terminal and run:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib pandas
Below is a Python script that:
/d/ and before /edit, like 1A2B3C4D5E6F7G8H9I0J.Replace 'YOUR_SPREADSHEET_ID' in the script with your actual Spreadsheet ID.
SPREADSHEET_ID = '1A2B3C4D5E6F7G8H9I0J' # Replace with your Spreadsheet ID
credentials.json.python your_script_name.py
To automate the script to run periodically:
cron.For example, to run the script daily at 9 AM, add the following line to your crontab (on Linux/macOS):
0 9 * * * /usr/bin/python /path/to/your_script_name.py
credentials.json file secure.If you prefer to keep everything within Google's ecosystem, you can use Google Apps Script to:
However, as of my knowledge cutoff in September 2021, Google Apps Script does not provide direct access to the YouTube watch history due to API limitations.
By following the steps above, you will have an automated system that captures your YouTube watch history and updates a Google Sheet. This setup can be expanded or modified to suit more specific needs, such as filtering certain videos or pulling additional metadata.
Note: Be sure to check the latest documentation for the YouTube Data API and Google Sheets API, as there may have been updates or changes after my last update in September 2021.
Not yet included in a published release.
import os
import pickle
import pandas as pd
from datetime import datetime
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Scopes required for YouTube and Google Sheets
YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
SHEETS_SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
# Authenticate and build the YouTube service
def youtube_authenticate():
creds = None
if os.path.exists('youtube_token.pickle'):
with open('youtube_token.pickle', 'rb') as token:
creds = pickle.load(token)
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', YOUTUBE_SCOPES)
creds = flow.run_local_server(port=0)
with open('youtube_token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('youtube', 'v3', credentials=creds)
# Authenticate and build the Sheets service
def sheets_authenticate():
creds = None
if os.path.exists('sheets_token.pickle'):
with open('sheets_token.pickle', 'rb') as token:
creds = pickle.load(token)
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', SHEETS_SCOPES)
creds = flow.run_local_server(port=0)
with open('sheets_token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('sheets', 'v4', credentials=creds)
# Retrieve watch history from YouTube
def get_watch_history(youtube):
request = youtube.activities().list(
part="snippet,contentDetails",
mine=True,
maxResults=50
)
response = request.execute()
items = response.get('items', [])
watch_history = []
for item in items:
if item['snippet']['type'] == 'watch':
video_title = item['snippet']['title']
video_id = item['contentDetails']['upload']['videoId']
published_at = item['snippet']['publishedAt']
watch_history.append({
'Video Title': video_title,
'Video ID': video_id,
'Watched At': published_at
})
return watch_history
# Update data to Google Sheet
def update_google_sheet(sheets_service, spreadsheet_id, data):
sheet_range = 'Sheet1!A1'
value_range_body = {
'values': [list(data[0].keys())] + [list(d.values()) for d in data]
}
request = sheets_service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id,
range=sheet_range,
valueInputOption='RAW',
body=value_range_body
)
response = request.execute()
print(f"{response.get('updatedCells')} cells updated.")
def main():
youtube_service = youtube_authenticate()
sheets_service = sheets_authenticate()
print("Retrieving YouTube watch history...")
watch_history = get_watch_history(youtube_service)
if not watch_history:
print("No watch history found.")
return
print(f"Retrieved {len(watch_history)} watched videos.")
# TODO: Replace with your actual Spreadsheet ID
SPREADSHEET_ID = 'YOUR_SPREADSHEET_ID'
print("Updating data to Google Sheet...")
update_google_sheet(sheets_service, SPREADSHEET_ID, watch_history)
print("Data updated successfully.")
if __name__ == '__main__':
main()