LoginSignup
1
0

More than 1 year has passed since last update.

Youtube Data Api v3+GASを使ってLive配信のコメントを取得した

Last updated at Posted at 2022-06-15

YoutubeDataApiV3を使うとLive配信のコメント及びスーパーチャットを取得することができます。しかし、あくまで生配信中でかつ実行した直近のものしか取得できないので、あまり実用的ではないです。

メリット

  • スプレッドシートに出力するのが楽

デメリット

  • 直近のものしか取得できない
  • アーカイブ化されたものは不可

方針

  1. 動画のURLからvideoIdを取得
  2. videoIdからliveChatIdを取得
  3. liveChatIdからコメント取得

コード

function getComments() {
    const videoUrl = "https://www.youtube.com/watch?v=[videoId]";
    const videoId = videoUrl.match(/watch\?v=.*$/g)[0].replace('watch?v=/','');
    var api = YouTube.Videos.list("snippet,liveStreamingDetails,contentDetails,status", {id: videoId})
    var chatId = api["items"][0]["liveStreamingDetails"]["activeLiveChatId"]
    const results = []
    if (chatId != null){
        var comments = YouTube.LiveChatMessages.list(chatId, "snippet,authorDetails", {hl: "ja"});
        for (let comment of comments["items"]){
            var isSuperChat = (comment["snippet"]["superChatDetails"] != null)
            var message;
            var published;
            var name;
            var nameId;
            var amount = "";
            if (isSuperChat){
              var superChat = comment["snippet"]["superChatDetails"]
              amount = superChat["amountDisplayString"];
              message = superChat["userComment"];
            }else{
              amount = "";
              message = comment["snippet"]["textMessageDetails"]["messageText"];
            }
            published = comment["snippet"]["publishedAt"]
            name = comment["authorDetails"]["displayName"]
            nameId = comment["authorDetails"]["channelId"]
            // コメント、投稿時刻, ユーザー名, ユーザーID, スーパーチャット時の金額を取得
            results.push([message, published, name, nameId, amount])
          }
    }
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = spreadsheet.getSheetByName('test');
    const lastRow = sheet.getLastRow();
    // 1行目に見出しを入れるので、削除しない
    if (lastRow >= 2){
        sheet.deleteRows(2, lastRow-1)
    }
    // 2行目からあとに挿入
    sheet.getRange(2, 1, outputComments.length, outputComments[0].length).setValues(results)
}

ハマった点など

  • pageTokenを使うと最新のコメントを常に取得し続ける(過去には遡らない)
  • スーパーチャットになるとcomment["snippet"]["textMessageDetails"]["messageText"]が消える
1
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
1
0