If your app follows creators, like a clip tool, a search index over a channel or an archive, you need each new upload as a file soon after it's posted, and nobody should be pasting links. The easy part is finding the new videos. YouTube gives every channel a public Atom feed, no API key needed:
https://www.youtube.com/feeds/videos.xml?channel_id=UC_x5XG1OV2P6uZZ5FSM9Ttw
It lists the 15 most recent uploads with their video ids, newest first. Run something more often than the channel posts 15 videos and you never miss one.
The hard part is the download. It works on a laptop, then the same code runs on a server and the requests get blocked, because sites block datacenter IPs. I built Importly for that, so that's what this script calls: you send it one video link and get the file in your own bucket, plus the captions. It works from servers. Whatever you call, the shape of the job is the same, and that's most of this post.
The rules the script follows
- Each video is sent once. The video id is the primary key in SQLite, so a re-run skips anything already started, finished or failed.
- No run waits on a long download. Each run first collects the imports that finished since last time, then reads the feed, then starts up to 5 new videos.
- Each video has a cost cap (
maxCostDollars), so a 6-hour stream can't eat the budget. - Live streams show up in the feed while they're live. They fail, and the script tries them again an hour later, up to 3 times.
- Shorts are in the same feed with
/shorts/links. The script skips them unless you setSKIP_SHORTS=0.
The code
import os
import sqlite3
import sys
import time
import feedparser
import httpx
CHANNEL_ID = sys.argv[1] # the UC... id from the channel page's URL or page source
FEED_URL = f"https://www.youtube.com/feeds/videos.xml?channel_id={CHANNEL_ID}"
MAX_COST = float(os.environ.get("MAX_COST_PER_VIDEO", "1.00")) # about an hour of 720p
SKIP_SHORTS = os.environ.get("SKIP_SHORTS", "1") == "1"
MAX_NEW_PER_RUN = 5
RETRY_LATER = {"LIVE_NOT_SUPPORTED": 3600, "SOURCE_THROTTLED": 300} # code -> seconds to wait
MAX_ATTEMPTS = 3
api = httpx.Client(
base_url="https://api.importly.io",
headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
timeout=30,
)
db = sqlite3.connect("channel.db")
db.execute("""
create table if not exists videos (
video_id text primary key,
title text,
url text,
status text, -- waiting, queued, running, completed, failed
job_id text,
attempts integer default 0,
not_before real default 0,
bucket_key text,
media_url text,
transcript text,
cost real,
error text
)
""")
def add_new_videos() -> None:
"""Add each video in the feed that isn't in the table yet."""
feed = feedparser.parse(FEED_URL)
for entry in feed.entries:
video_id = entry.get("yt_videoid")
if not video_id:
continue
if SKIP_SHORTS and "/shorts/" in entry.link:
continue
db.execute(
"insert or ignore into videos (video_id, title, url, status) values (?, ?, ?, 'waiting')",
(video_id, entry.title, f"https://www.youtube.com/watch?v={video_id}"),
)
db.commit()
def start_waiting() -> None:
rows = db.execute(
"select video_id, url from videos where status = 'waiting' and not_before <= ? limit ?",
(time.time(), MAX_NEW_PER_RUN),
).fetchall()
for video_id, url in rows:
res = api.post("/import", json={
"url": url,
"videoQuality": "720p", # a ceiling: lower if the source has no 720p
"maxCostDollars": MAX_COST, # the most one video may cost, captions included
"includeTranscript": True, # the video's captions, $0.003
"store": True, # copy the file to your bucket
"storagePath": f"youtube/{CHANNEL_ID}",
"storageFilename": video_id,
})
body = res.json()
if res.status_code in (402, 429):
# Out of credits, or the hourly or in-progress limit: try the rest next run
print(f"Stopping for this run: {body.get('code')} {body.get('error')}")
return
if not res.is_success or not body.get("success"):
db.execute("update videos set status = 'failed', error = ? where video_id = ?",
(body.get("error"), video_id))
else:
db.execute("update videos set status = 'queued', job_id = ? where video_id = ?",
(body["data"]["jobId"], video_id))
print(f"Started: {video_id}")
db.commit()
def collect_finished() -> None:
pending = db.execute(
"select video_id, job_id, attempts from videos where status in ('queued', 'running')"
).fetchall()
for video_id, job_id, attempts in pending:
data = api.get("/import/status", params={"id": job_id}).json()["data"]
if data["status"] == "completed":
result = data["result"]
transcript = result.get("transcript") or {}
db.execute(
"""update videos set status = 'completed', bucket_key = ?, media_url = ?,
transcript = ?, cost = ?, error = ? where video_id = ?""",
(
(result.get("s3Storage") or {}).get("key"),
result["mediaUrl"], # expires after 7 days
transcript.get("text"), # None when the video has no captions
result["totalCostInDollars"],
result.get("s3StorageError"), # set if the copy to your bucket failed
video_id,
),
)
elif data["status"] == "failed":
code = data.get("code")
if code in RETRY_LATER and attempts + 1 < MAX_ATTEMPTS:
# Still live, or the source asked us to slow down: send it again later
db.execute(
"update videos set status = 'waiting', attempts = ?, not_before = ? where video_id = ?",
(attempts + 1, time.time() + RETRY_LATER[code], video_id),
)
else:
db.execute("update videos set status = 'failed', error = ? where video_id = ?",
(f"{code}: {data.get('message')}", video_id))
else:
db.execute("update videos set status = ? where video_id = ?", (data["status"], video_id))
db.commit()
collect_finished()
add_new_videos()
start_waiting()
pip install feedparser httpx
export IMPORTLY_API_KEY=your_api_key
# Run it every 15 minutes with the channel's id
python import_channel.py UC_x5XG1OV2P6uZZ5FSM9Ttw
Put it in cron every 15 minutes (*/15 * * * *), or in whatever scheduler your app already has.
Things that bit me
The first run starts the 5 newest videos and the rest of the feed follows over the next two runs. If you only want videos from today on, insert the current feed's ids as completed before the first run.
A 402 (out of credit) or 429 (rate limit) on the start request isn't a reason to mark the video failed. The script stops starting videos for that run and the next run picks them up.
The download link in the result expires after 7 days, so if you need the file later, store it in your bucket (that's what store: True does) rather than saving the link.
If your host has no persistent disk, channel.db disappears on the next deploy. Keep the same table in your app's database instead.
The full recipe, with the response you get back and the errors to handle, is in the Importly docs. It's free to try, no card required.
Top comments (0)