if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
list = f""""
"""
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Liking changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}\{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
if name == "main":
youtube = authenticate_youtube()
media_folder = r"C:\Users\kogut\PYTHONIK\AI_shorts-main\Films_ready"
media_file = r"Would You Rather Part 1.mp4"
upload_youtube_short(youtube, media_folder, media_file)
I want to upload short on specified date
Assistant
To schedule the upload of a YouTube short on a specified date, you'll need to incorporate a scheduling approach into your script. Python's built-in datetime module and the time module can work together to facilitate this. Below is a revised version of your script that includes a scheduling mechanism to wait until your desired upload date and time:
python
User
I mean I want to upload a file now, but I want it to be public on specified date
Assistant
To upload a video to YouTube now but schedule it to be publicly accessible on a specific future date, you'll need to utilize the publishAt parameter of the YouTube API. This feature requires you to first set the video's privacy status as private and when you want the video to become public, specify the schedule with publishAt.
Here is how you can modify your script to achieve this:
python
import os
import google_auth_oauthlib
import googleapiclient.discovery
import googleapiclient.errors
import googleapiclient.http
from googleapiclient.http import MediaFileUpload
import random
from datetime import datetime, timedelta, timezone
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
TOKEN_FILE = 'token.json'
def authenticate_youtube():
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Liking changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
def upload_youtube_short(youtube, media_folder, media_file, publish_datetime):
request_body = {
"snippet": {
"categoryId": "24",
"title": f"{media_file}",
"description": f"{desc()}",
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "private", # Initially upload as private
"publishAt": publish_datetime.isoformat() # Schedule to be public
}
}
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
if __name__ == "__main__":
youtube = authenticate_youtube()
media_folder = r"C:\Users\kogut\PYTHONIK\AI_shorts-main\Films_ready"
media_file = r"Would You Rather Part 1.mp4"
# Specify the datetime when you want the video to be public (in UTC)
publish_datetime = datetime(2023, 11, 1, 10, 0, 0, tzinfo=timezone.utc)
upload_youtube_short(youtube, media_folder, media_file, publish_datetime)
User
import os
import google_auth_oauthlib
import googleapiclient.discovery
import googleapiclient.errors
import googleapiclient.http
from googleapiclient.http import MediaFileUpload
import random
from datetime import datetime, timedelta, timezone
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Liking changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
def upload_youtube_short(youtube, media_folder, media_file, publish_datetime):
request_body = {
"snippet": {
"categoryId": "24",
"title": f"{media_file}",
"description": f"{desc()}",
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "private", # Initially upload as private
"publishAt": publish_datetime.isoformat() # Schedule to be public
}
}
code
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
if name == "main":
youtube = authenticate_youtube()
media_folder = r"C:\Users\kogut\PYTHONIK\AI_shorts-main\Films_ready"
media_file = r"Would You Rather Part 1.mp4"
code
# Specify the datetime when you want the video to be public (in UTC)
publish_datetime = datetime(2024, 11, 1, 10, 0, 0, tzinfo=timezone.utc)
upload_youtube_short(youtube, media_folder, media_file, publish_datetime)
I want to publish it 2024.11.15 20:00
Assistant
To schedule the video to become public on November 15, 2024, at 20:00 (8:00 PM), you'll need to ensure that you're using the correct UTC time. If 20:00 is your local time, you'll need to convert it to UTC, as YouTube's publishAt parameter requires UTC.
Here's how you can modify the script to schedule the video at the desired datetime:
python
import os
import google_auth_oauthlib
import googleapiclient.discovery
import googleapiclient.errors
import googleapiclient.http
from googleapiclient.http import MediaFileUpload
import random
from datetime import datetime, timezone
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
TOKEN_FILE = 'token.json'
def authenticate_youtube():
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Liking changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
def upload_youtube_short(youtube, media_folder, media_file, publish_datetime):
request_body = {
"snippet": {
"categoryId": "24",
"title": f"{media_file}",
"description": f"{desc()}",
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "private", # Initially upload as private
"publishAt": publish_datetime.isoformat() # Schedule to be public
}
}
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
if __name__ == "__main__":
youtube = authenticate_youtube()
media_folder = r"C:\Users\kogut\PYTHONIK\AI_shorts-main\Films_ready"
media_file = r"Would You Rather Part 1.mp4"
# Specify the datetime when you want the video to be public (in UTC)
# Assuming 20:00 is your local time and is UTC+0, adjust the hours accordingly if needed.
publish_datetime = datetime(2024, 11, 15, 20, 0, 0, tzinfo=timezone.utc)
upload_youtube_short(youtube, media_folder, media_file, publish_datetime)
User
how to update date by 1 day in loop
Assistant
If you want to update a date by one day in a loop, you can use Python's datetime module. By incrementing a datetime object representing a specific date, you can loop through a desired range of days or simply update the date by one day in each iteration.
Here's an example demonstrating how to increment a date by one day in a loop:
python
from datetime import datetime, timedelta
# Initial date (for example, November 15, 2024 at 20:00 UTC)
current_date = datetime(2024, 11, 15, 20, 0, 0)
# Number of days to loop over
days_to_increment = 5 # Adjust as needed
for _ in range(days_to_increment):
# Print current date
print("Current scheduled date:", current_date)
# Here, you can call your function to schedule a video with `current_date`
# upload_youtube_short(youtube, media_folder, media_file, current_date)
# Increment the date by one day
current_date += timedelta(days=1)
Key Components in the Script:
datetime Object: A datetime object is created for the starting date. In this example, it starts on November 15, 2024, at 20:00.
timedelta: The timedelta object is used to represent the difference of one day. By adding it to the current date, you move forward by one day.
Loop Structure: The loop runs for a specified number of days (days_to_increment). During each iteration, the current_date is updated by one day.
Inside the Loop: You can include any functionality inside the loop that utilizes the updated date, such as scheduling an upload.
This structure allows you to iterate over a sequence of days, with current_date being updated to represent each new day. You may adapt the number of iterations (days_to_increment) and initial settings to suit your specific use case.
User
how to get data rn in utc
Assistant
To get the current date and time in UTC using Python, you can utilize the datetime module, along with its timezone class. Here's how you can do it:
python
from datetime import datetime, timezone
# Get the current date and time in UTC
current_utc_datetime = datetime.now(timezone.utc)
# Print the result
print("Current UTC date and time:", current_utc_datetime)
Explanation:
datetime.now(timezone.utc): This function call gets the current date and time and sets the timezone to UTC. It returns a timezone-aware datetime object.
timezone.utc: This is a timezone object that represents Coordinated Universal Time (UTC).
With this approach, you ensure that the datetime object you're working with is aligned with UTC, which is particularly useful for applications that require standardized and globally recognized timestamps.
User
import os
import google_auth_oauthlib
import googleapiclient.discovery
import googleapiclient.errors
import googleapiclient.http
from googleapiclient.http import MediaFileUpload
import random
from datetime import datetime, timedelta, timezone
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Like changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
def upload_youtube_short(youtube, media_folder, media_file, publish_datetime):
request_body = {
"snippet": {
"categoryId": "24",
"title": f"What would you rather?",
"description": f"{desc()}",
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "private", # Initially upload as private
"publishAt": publish_datetime.isoformat() # Schedule to be public
}
}
code
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
import sys
import shutil
if name == "main":
youtube = authenticate_youtube()
publish_datetime = datetime.now(timezone.utc)+timedelta(minutes=10)
if not os.path.exists("Uploaded"):
os.makedirs("Uploaded", exist_ok=True)
Assistant
To set a video as not made for kids using the YouTube Data API, you need to specify the selfDeclaredMadeForKids field in the video's status resource. This field should be set to False to indicate that the video is not made for kids.
Here's how you can modify your upload_youtube_short function to include this setting:
python
def upload_youtube_short(youtube, media_folder, media_file, publish_datetime):
request_body = {
"snippet": {
"categoryId": "24",
"title": "What would you rather?",
"description": desc(),
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "private", # Initially upload as private
"publishAt": publish_datetime.isoformat(), # Schedule to be public
"selfDeclaredMadeForKids": False # Set video as not made for kids
}
}
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
Key Additions:
selfDeclaredMadeForKids: This parameter is added to the status dictionary of the request_body. Setting it to False explicitly declares that the video is not intended for children under the age of 13.
This change ensures compliance with the Children's Online Privacy Protection Act (COPPA) and assists YouTube in determining age-appropriate content handling. Ensure that this setting accurately reflects the intended audience for your content.
import os
import google_auth_oauthlib
import googleapiclient.discovery
import googleapiclient.errors
import googleapiclient.http
from googleapiclient.http import MediaFileUpload
import random
from datetime import datetime, timedelta
import time
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
TOKEN_FILE = 'token.json'
def authenticate_youtube():
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
if os.path.exists(TOKEN_FILE):
os.remove(TOKEN_FILE)
# Load client secrets file, put the path of your file
client_secrets_file = "client.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_local_server()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def desc():
list_of_desc = ["Click share and like to get a heart",
"Like to get a cookie",
"Like to be lucky",
"Like to find a 10$",
"Sharing changes your :) emoji",
"Liking changes your :D emoji"]
return list_of_desc[random.randint(0, len(list_of_desc)-1)]
def upload_youtube_short(youtube, media_folder, media_file):
request_body = {
"snippet": {
"categoryId": "24",
"title": f"{media_file}",
"description": f"{desc()}",
"tags": ["quiz", "shorts", "Yes or no"]
},
"status": {
"privacyStatus": "public"
}
}
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=MediaFileUpload(f"{media_folder}/{media_file}", chunksize=-1, resumable=True)
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
print(f"Video uploaded with ID: {response['id']}")
def wait_until_target(target_datetime):
current_time = datetime.now()
while current_time < target_datetime:
time_diff = (target_datetime - current_time).total_seconds()
print(f"Waiting for {int(time_diff)} seconds before starting the upload...")
time.sleep(min(time_diff, 60)) # Sleep in chunks to allow for possible interruptions
current_time = datetime.now()
if __name__ == "__main__":
target_datetime = datetime(2023, 11, 1, 10, 0, 0) # Target date/time to upload
wait_until_target(target_datetime)
youtube = authenticate_youtube()
media_folder = r"C:\Users\kogut\PYTHONIK\AI_shorts-main\Films_ready"
media_file = r"Would You Rather Part 1.mp4"
upload_youtube_short(youtube, media_folder, media_file)
Key Changes:
Scheduling: A new function wait_until_target(target_datetime) is added, which waits until the specified target date and time. The script uses datetime.now() to determine the current time and delays execution in a loop until the target time is met.
Invoking Scheduler: Before proceeding with YouTube authentication and video upload, the script waits for the specified datetime to be reached.
Custom Target Date/Time: You specify your desired upload date and time with the target_datetime variable in the main portion of the script. Adjust the datetime() values to your target date/time.
By using this setup, your script will automatically wait until the desired upload time, then proceed to authenticate and upload the video using the YouTube Data API.
Key Components:
publishAt Parameter: The publishAt parameter accepts an ISO 8601 formatted date string specifying when the video should be made public.
ISO 8601 Format:publish_datetime.isoformat() is used to convert the datetime object to a string in the required format. Ensure that the datetime object is timezone-aware for accuracy, typically set to UTC.
Privacy Status: The video is initially uploaded with a privacyStatus of private, which is necessary when scheduling a publishAt time.
UTC Time: Ensure that publish_datetime is specified in UTC to match YouTube's expectations for scheduled publish times.
By using this configuration, your script will upload a video and set it to become public on the specified future date.
Considerations:
Timezone Conversion: Ensure that 20:00 is correctly represented in UTC. If your local time zone differs from UTC, convert the time accordingly.
Video Upload: This script uploads the video as private and schedules it for publication at the specified date and time using the publishAt attribute.
Client Secrets and Token File: Ensure your client.json and access to Google's API are correctly set up before running the script.
Double-check your local time against UTC to ensure the correct publication time. Adjust publish_datetime if necessary to account for any timezone differences.