> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Import each new video from a YouTube channel on a schedule in Python

> A Python script you run from cron: it reads a YouTube channel's public feed, imports each new upload once into your own bucket with its captions, caps the cost per video, and retries live streams after they end.

Apps that follow creators, such as a clip tool, a search index over a channel, or an archive, need every new upload as a file soon after it's posted, without anyone pasting links. Importly takes one link per video and rejects channel and playlist pages, so the job is to turn the channel into links and send each one once. This script reads the channel's public feed, sends each new video to [`POST /import`](/docs/endpoints/import) with its captions, and records the result in SQLite. Run it from cron or a scheduled worker every 10 to 20 minutes: each run collects the imports that finished and starts the videos that are new.

## The code

```python import_channel.py theme={null}
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()
```

```bash theme={null}
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
```

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the server. Connect your bucket once before the first run: the steps for S3, R2, B2 and Spaces are in [Deliver to your bucket](/docs/s3-storage.md). Without a bucket, leave out `store` and the storage fields and copy each file from `mediaUrl` instead.

## How it works

The channel's feed is public and needs no YouTube API key. `https://www.youtube.com/feeds/videos.xml?channel_id=<id>` lists the channel's 15 most recent uploads, newest first, each with its video id, title and publish time. The script builds a plain watch URL from each id. Run it more often than the channel posts 15 videos and nothing is missed.

Shorts are in the same feed, with `/shorts/` links. The script skips them by default; set `SKIP_SHORTS=0` to import them too. Importly takes [Shorts links](/docs/features/supported-sites.md) like any other video.

Each video is sent once. The video id is the key in SQLite, so a re-run skips everything already started, finished or failed. Unfinished imports are picked up by the next run, so no run waits on a long download. The first run starts the 5 newest videos in the feed; the rest of the feed follows over the next two runs. To start from today instead, insert the current feed's ids as `completed` before the first run.

`maxCostDollars` caps each video. Downloads are $0.002 per MB, so a 10-minute 720p video is about $0.15, and the default of $1.00 covers about an hour of 720p. A longer video fails with `MAX_COST_EXCEEDED` before anything is downloaded, and costs only $0.003 for the price check. Raise the cap, or set `"includeVideo": false` for audio only, if the channel posts long streams.

`includeTranscript: true` adds the video's captions to the same job for $0.003. When a video has no captions, the import still succeeds and `transcript` is `{ "status": "skipped", "reason": "…" }`, so the script stores no text. To get speech-to-text for those, add `"transcriptProvider": "importly"` ($0.01 per minute). See [Transcripts inside an import](/docs/features/transcripts.md#transcripts-inside-an-import).

Live streams appear in the feed while they're live. They fail with `LIVE_NOT_SUPPORTED` and nothing is charged; the script sends them again an hour later, up to 3 tries.

## What gets stored

A finished job from `GET /import/status` has the file under `result`. The script stores the bucket key from `s3Storage`, the `mediaUrl`, the transcript `text` and `totalCostInDollars`:

```json theme={null}
{
  "mediaUrl": "https://…",
  "title": "My latest video",
  "duration": 612,
  "downloadedBytes": 79823104,
  "costInDollars": 0.154,
  "totalCostInDollars": 0.157,
  "transcript": { "text": "Hi everyone…", "source": "platform_captions", "language": "en" },
  "s3Storage": {
    "url": "https://my-app-media.s3.us-east-1.amazonaws.com/youtube/UC_x5XG1OV2P6uZZ5FSM9Ttw/WN5O4vWCa54.mp4",
    "bucket": "my-app-media",
    "key": "youtube/UC_x5XG1OV2P6uZZ5FSM9Ttw/WN5O4vWCa54.mp4"
  }
}
```

`mediaUrl` expires after 7 days; the copy in your bucket is yours to keep. If the copy to your bucket fails, the import still succeeds and `s3StorageError` says why. The script saves it in `error`.

## Errors to handle

| Where | What you see | What the script does |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Stops starting videos until the next run. Add credits; nothing was charged |
| Start request | HTTP `429` `RATE_LIMITED` | Stops until the next run. You hit 240 imports an hour or have 50 queued or running. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Start request | HTTP `400` | Records the video as failed so it isn't sent again |
| Status | `status: "failed"`, `code: "LIVE_NOT_SUPPORTED"` | Sends it again in an hour, up to 3 tries |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | Records it. Raise `MAX_COST_PER_VIDEO` and set the row back to `waiting` to retry |
| Status | `status: "failed"` with another `code` | Records it. Private, deleted, age-restricted or members-only videos can't be imported. Failed imports aren't charged |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

Use a webhook instead of polling. Pass a `webhookUrl` when you start each import and save the result when Importly calls you back. Keep the status check as a fallback: each job gets one delivery, with no retries. See [Webhooks](/docs/webhooks.md).

Many channels? Loop over their ids in the same run, with a `channel_id` column in the table. A `429` just moves the rest to the next run, and [Batch imports](/docs/integrations/batch-imports.md) shows a steady sender for larger volumes.

An app that imports around the clock shouldn't stop when credit runs out. Turn on [auto top-up](/docs/billing.md#auto-top-up), or watch for the [low-balance emails](/docs/billing.md#low-balance-emails).

> [!NOTE]
>
> A 10-minute 720p video with its captions costs about \$0.16, and status checks are free. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.