0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python入門】YouTubeライブの“見逃し配信”を自動で集める簡単スクリプトを作ってみた

Last updated at Posted at 2025-10-09

🎬 はじめに

YouTubeって、気づいたら「昨日配信してたライブ、見逃してた…」ってことありますよね?
そんな時に役立つのが “ライブ配信アーカイブだけを自動で拾うスクリプト” です。

この記事では、
Python初心者でも動かせる形で RSSフィード+YouTube Data API を使った簡単なツールを作ります。
APIキーだけで動くので、OAuthなどのややこしい設定は不要です💡

🚀 できること

  • チャンネルの RSSフィード から最近の動画IDを取得

  • それを YouTube Data API で調べて、
    「ライブ配信だった動画(アーカイブ)」だけを抽出

  • 結果をターミナルに一覧表示

🧰 必要なもの

✅ 1. Python環境

Python 3.9 以上を想定しています。

✅ 2. ライブラリのインストール

以下のコマンドをターミナルで実行してください。

pip install feedparser google-api-python-client

✅ 3. YouTube Data API の APIキー

  1. Google Cloud Console
    にアクセス

  2. 新しいプロジェクトを作成

  3. 「YouTube Data API v3」を有効化

  4. 「認証情報」→「APIキーを作成」

  5. 発行されたキーをコピーしておきます

🗂️ 準備ファイル

channel_list.txt を同じフォルダに作成し、
チェックしたいチャンネルIDを カンマ区切りまたは改行 で記載します。

UCXXXXXXXXXXXXX,
UCYYYYYYYYYYYYY

※ チャンネルIDはURLの

https://www.youtube.com/channel/UCxxxxx

の部分です。

💻 スクリプト全文

import os
import datetime as dt
from zoneinfo import ZoneInfo

import feedparser
from googleapiclient.discovery import build

# タイムゾーン(日本時間)
JST = ZoneInfo("Asia/Tokyo")

# APIキー(環境変数から取得)
API_KEY = os.getenv("YOUTUBE_API_KEY", "KEY")
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"


def jst_window_yesterday_to_now():
    """昨日00:00〜今(日本時間)の期間をUTCに直して返す"""
    now_jst = dt.datetime.now(JST)
    start_jst = (now_jst - dt.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
    return start_jst.astimezone(dt.timezone.utc), now_jst.astimezone(dt.timezone.utc)


def parse_entry_dt(entry):
    """RSSエントリから日時をdatetimeに変換"""
    if hasattr(entry, "updated_parsed") and entry.updated_parsed:
        return dt.datetime(*entry.updated_parsed[:6], tzinfo=dt.timezone.utc)
    if hasattr(entry, "published_parsed") and entry.published_parsed:
        return dt.datetime(*entry.published_parsed[:6], tzinfo=dt.timezone.utc)
    return None


def rss_analysis(channel_id, start_utc, end_utc):
    """RSSから期間内の動画IDを取得"""
    url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
    feed = feedparser.parse(url)
    vids = []
    for entry in feed.entries:
        t = parse_entry_dt(entry)
        if not t:
            continue
        if start_utc <= t <= end_utc:
            vid = getattr(entry, "yt_videoid", None)
            if vid:
                vids.append(vid)
    return list(dict.fromkeys(vids))


def videos_lookup_bulk(video_ids):
    """YouTube Data APIで動画情報をまとめて取得"""
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY)
    items = []
    for i in range(0, len(video_ids), 50):
        chunk = video_ids[i:i+50]
        resp = youtube.videos().list(
            id=",".join(chunk),
            part="liveStreamingDetails,snippet"
        ).execute()
        items.extend(resp.get("items", []))
    return items


def is_live_archive(item):
    """ライブ配信アーカイブかどうかを判定"""
    lsd = item.get("liveStreamingDetails") or {}
    return bool(lsd.get("actualEndTime"))


if __name__ == "__main__":
    start_utc, end_utc = jst_window_yesterday_to_now()

    with open("channel_list.txt", "r", encoding="utf-8") as f:
        raw = f.read()
    ch_ids = [x.strip() for part in raw.replace("\n", ",").split(",") for x in [part] if x.strip()]

    all_video_ids = []
    for cid in ch_ids:
        all_video_ids.extend(rss_analysis(cid, start_utc, end_utc))
    all_video_ids = list(dict.fromkeys(all_video_ids))

    if not all_video_ids:
        print("期間内の新しい動画は見つかりませんでした。")
    else:
        items = videos_lookup_bulk(all_video_ids)
        archives = [it for it in items if is_live_archive(it)]
        print(f"候補: {len(all_video_ids)} 件 / ライブアーカイブ: {len(archives)} 件\n")
        for it in archives:
            vid = it["id"]
            title = it["snippet"]["title"]
            ch = it["snippet"]["channelTitle"]
            print(f"- {ch} | {title} | https://www.youtube.com/watch?v={vid}")

💡 コードの仕組み

処理内容 関数名 使っている技術
昨日〜今日の期間を設定 jst_window_yesterday_to_now() datetime, timezone
RSSから動画ID取得 rss_analysis() feedparser
APIで詳細を取得 videos_lookup_bulk() YouTube Data API
ライブアーカイブ判定 is_live_archive() liveStreamingDetails.actualEndTime

⚠️ 注意事項

  • APIキーは他人に共有しないでください。GitHubなどに上げると不正利用される可能性があります

  • RSSは各チャンネル最新15件までしか取れないため、古い配信は拾えません

  • APIのクォータ(1日10,000ユニット)に注意してください

🏁 まとめ

この記事では、YouTubeのライブ配信アーカイブを自動で一覧にするPythonスクリプトを作りました。
OAuth認証なしでAPIキーだけで動くので、初心者でもすぐ試せます。

「昨日の配信、もう終わってた!」を防ぐための
シンプルなローカル見逃しチェッカーとして、ぜひ活用してみてください 🎥✨

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?