0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

YouTube DataAPI のドキュメント読んでレスポンスを想像しながらスクリプト書いてみた

Posted at

概要

なにやらYouTubeにもAPIが存在するようなので気になって試そうという記事です

利用方法

Google Cloudの登録が必要なようです
プライベートで登録するのはまだ気が引けるので、リファレンスからレスポンスを読み取ってこういことできるかなというのをみていければと思います

試したいもの

コメントで時間つきのコメントが見られると思います
お気に入りのタイミングが来たら、この場面面白かったといった形で残されていたりするやつですね

そこで、タイムスタンプが含まれるコメントだけ探し出して自分だけの切り抜きを探せるようにならないかなと思いました

早速ですが、レスポンスは以下の形式だそうです(引用)

{
  "kind": "youtube#commentListResponse",
  "etag": etag,
  "nextPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    comment Resource
  ]
}
kind string
API リソースのタイプを識別します。値は youtube#commentListResponse です。
etag etag このリソースの Etag。
nextPageToken string 結果セットで次のページを取得するために、pageToken パラメータの値として使用できるトークン。
pageInfo object pageInfo オブジェクトは、結果セットのページング情報をカプセル化します。
pageInfo.totalResults integer 結果セット内の結果の合計数。
pageInfo.resultsPerPage integer API レスポンスに含まれる結果の数。
items[] list API リクエスト条件に一致するコメントのリスト。

よくよく調べると、こちらはある特定のコメントIDに対するリプライを取得するAPIのようでした

途方に暮れているとcommentThreads.listというものがあるということを知りました

{
  "kind": "youtube#commentThreadListResponse",
  "etag": etag,
  "nextPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    commentThread Resource
  ]
}

なんかほとんど構造は同じですね
中身とかが違うのでしょう

itemsの中身が気になったのでダメ元でchatGPTに聞いてみたところ意外にも返ってきました

"items": [
    {
      "kind": "youtube#commentThread",
      "etag": "etag123",
      "id": "UgxabcXYZ123",
      "snippet": {
        "videoId": "dQw4w9WgXcQ",
        "topLevelComment": {
          "kind": "youtube#comment",
          "etag": "etag456",
          "id": "UgzabcCommentID",
          "snippet": {
            "authorDisplayName": "ChatGPT Fan",
            "authorProfileImageUrl": "https://yt3.ggpht.com/...",
            "authorChannelUrl": "http://www.youtube.com/channel/UC...",
            "textDisplay": "この動画めっちゃ面白い!",
            "textOriginal": "この動画めっちゃ面白い!",
            "likeCount": 25,
            "publishedAt": "2024-03-01T12:34:56Z",
            "updatedAt": "2024-03-01T12:34:56Z"
          }
        },
        "canReply": true,
        "totalReplyCount": 2,
        "isPublic": true
      },
      "replies": {
        "comments": [
          {
            "id": "Ugyreply123",
            "snippet": {
              "authorDisplayName": "Another Viewer",
              "textDisplay": "ほんとそれ!",
              "likeCount": 3,
              "publishedAt": "2024-03-01T13:00:00Z"
            }
          }
        ]
      }

commentThreadsという名の通りあるコメントに対して他の返信があればrepliesというものに追加されていくようですね

一旦、今回必要なものとしてはスレッド内のコメントは無視したいと思います(できなくはないと思いますが、大抵の場合トップコメントにタイムスタンプが書かれているコメントが多いのかなと)

ということで、レスポンスの形が見えた気がするのでこれを仮定にコードを書いてみます

仮定のコード

まずはYouTube APIにアクセスするためにはgoogle-api-python-clientが必要になるそうです
pipでインストールしておきましょう

コードとしては大体こんな感じになりそうかと

commentThreads APIを叩くためのクライアントや対象のVIDEO IDを定義して、APIを実行
そして上限である100件を取り、各コメントを取得してさらにそのコメント内にタイムスタンプ形式のものが存在するかを判別しています

また100件以上コメントがある場合も考慮してnextPageTokenがある限りはループするようにしています

from googleapiclient.discovery import build

# YouTube APIキーをここに記入
API_KEY = 'YOUR_API_KEY'
VIDEO_ID = 'TARGET_VIDEO'

youtube = build('youtube', 'v3', developerKey=API_KEY)

comments = []
next_page_token = None

while True:
    response = youtube.commentThreads().list(
        part='snippet',
        videoId=VIDEO_ID,
        maxResults=100,
        textFormat='plainText',
        pageToken=next_page_token
    ).execute()

    for item in response['items']:
        comment = item['snippet']['topLevelComment']['snippet']['textOriginal']
        if re.search(r'\b(?:\d{1,2}:)?[0-5]?\d:[0-5]\d\b', comment_text):
            comments.append(comment_text)  # タイムスタンプがついているものだけ保存

    # 次のページがなければ終了
    next_page_token = response.get('nextPageToken')
    if not next_page_token:
        break

コード実行によって取得されたコメントの一覧が得られた後は、それぞれに1:35みたいなタイムスタンプがあるのでそちらを秒数に直します(1:35=95s)

そして、以下のURLの形式でページを開くと該当の部分から再生ができるようになります

https://www.youtube.com/watch?v=xxxxxxxx&t=95s

youtubeのタイムタンプを押してその時間に動画が飛ぶというのは実はリンクで制御していたのですね

おわりに

ということで以上がyoutubeの動画でタイムスタンプを含んだコメントだけを取得できるのかという記事になります

実際に試せていないのでそこだけが残念ですが、いずれGoogle Cloudの登録を行なって試してみたいと思います

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?