DEV Community

1322 Monitors
1322 Monitors

Posted on Originally published at 1322.io

YouTube upload alerts without API quota

Disclosure: I work on 1322 Monitors (1322.io), the service used in this post.

The usual way to watch a YouTube channel for new videos is to call the YouTube Data API on a timer. That works for a few channels. It gets harder as the list grows: the Data API gives a project 10,000 quota units a day by default, and a search costs 100 of them.

YouTube's push option, WebSub (also called PubSubHubbub), avoids the timer. In exchange, you host a public callback server and renew a lease for every subscription, and each ping is a minimal feed entry: IDs, title and link.

This post takes a third route. A WebSocket pushes each new upload from the channels on your list. There is no Data API key, no quota and nothing public to host. Uploads and Shorts arrive sub-second from the moment they go public on YouTube.

Step 1: track the channels

Add a channel with one REST call. Your API key is on the API access page of your dashboard.

curl -X POST "https://youtube.1322.io/v1/track" \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $YT_API_KEY" \
  -d '{"channel": "@examplestudio"}'
Enter fullscreen mode Exit fullscreen mode

channel takes a UC… channel ID, an @handle or a channel URL. All three resolve to the same channel. GET /v1/list returns your tracked channels, POST /v1/untrack removes one, and GET /v1/limits shows your slots and request rate.

Step 2: get your stream URL

On YouTube plans the WebSocket is an add-on. With it on, GET /v1/dashboard returns a complete ws_url and a separate ws_key:

curl "https://youtube.1322.io/v1/dashboard" -H "X-Api-Key: $YT_API_KEY"
Enter fullscreen mode Exit fullscreen mode

Save them as YT_WS_URL and YT_WS_KEY. You can also click Copy URL on the Workspace page in your dashboard, which gives the same URL with the key already in it. If you use that value, connect to it as it is and do not add ?key= again.

Step 3: the consumer

# pip install "websockets>=13"   (Python 3.9+)
import asyncio, json, os
from websockets.asyncio.client import connect

# ws_url and ws_key from GET /v1/dashboard
WS_URL = os.environ["YT_WS_URL"] + "?key=" + os.environ["YT_WS_KEY"]
latest = {}  # channel id -> newest upload message

def handle(msg):
    kind = msg.get("type")
    if kind == "upload":
        channel = msg.get("channel") or {}
        video = msg.get("video") or {}
        latest[channel.get("id")] = msg
        label = "Short" if msg.get("subtype") == "short" else "video"
        print(f"new {label}: {channel.get('name')} | {video.get('title')} | {video.get('url')}")
    elif kind == "upgrade":
        upgrade = msg.get("upgrade") or {}
        print("better thumbnail for", upgrade.get("video_id"), upgrade.get("url"))
    elif kind == "deletion":
        print("no longer available:", (msg.get("video") or {}).get("id"))

async def main():
    backoff = 1
    while True:
        try:
            async with connect(WS_URL) as ws:
                backoff = 1
                async for raw in ws:
                    try:
                        msg = json.loads(raw)
                    except ValueError:
                        continue
                    if isinstance(msg, dict):
                        handle(msg)
        except Exception as exc:
            print("disconnected:", exc)
        await asyncio.sleep(backoff)
        backoff = min(backoff * 2, 30)

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

You can send the key in an X-WS-KEY header instead of ?key=. Use one or the other, not both. The server pings every 30 seconds, and the library answers for you.

The three message types

One stream carries three types. They are not a fixed sequence.

  • upload is the one to build on. It is sent for every new video. subtype is video or short. The message carries the channel (id, name, url, avatar) and the video (id, url, title, published_at). images.chosen is the best image available when the upload is sent. Any channel or images field can be null.
  • upgrade is sent only when a better thumbnail becomes available. It carries upgrade.video_id and the new image URL, so you can update a card you already posted.
  • deletion is sent when a tracked video is confirmed unavailable. That can happen much later, or never.

Most videos never get an upgrade or a deletion, so treat every message as standalone and never wait for a follow-up. The latest dict above keeps the newest upload per channel, which answers the common question "what did this channel post last?" without a single quota unit.

What to expect

  • No backfill. A channel's stream starts when you add it. Videos published before then are not sent.
  • Nothing is replayed while your client is offline, so the loop reconnects with a capped backoff.
  • Lives and premieres. There is no separate live-stream start or end event. A stream or premiere can still arrive as an ordinary upload, sometimes when it is scheduled rather than when it starts.
  • Not included: comments, community posts and subscriber counts.

Prefer a webhook, or no code at all?

A signed webhook can stand in for the WebSocket. It POSTs each event to your own https:// endpoint with an X-1322-Signature HMAC header and an X-1322-Event-Id. Answer with a 2xx within 8 seconds. A failed attempt is retried, up to 6 attempts in all, so dedupe on the event ID. Act on upload and ignore upload_ws_only, which is a webhook-only repeat notice. Signed webhooks depend on account configuration and enabled features.

If the alerts only need to reach a Discord channel, the bot is included on every YouTube plan:

  • /yt_add post_channel:#youtube-uploads youtube:@examplestudio tracks a channel and picks where it posts.
  • /yt_untrack stops tracking a channel. /yt_list shows tracked channels.
  • /yt_set_default_channel sets the channel for anything without its own.

By default these need Administrator or Manage Server. A regular upload posts as "New Video" and a Short as "New Short".

Cost

$150/month for 5 channels, $300 for 15 or $400 for 50, each with the Discord bot included. The WebSocket is a $100/month add-on.

The full quick start, with a Node consumer and every REST call, is at 1322.io/docs/youtube. A one-day evaluation is available on request, reviewed by the team, no card.

Top comments (0)