YoutubeDataApiV3を使うとLive配信のコメント及びスーパーチャットを取得することができます。しかし、あくまで生配信中でかつ実行した直近のものしか取得できないので、あまり実用的ではないです。
メリット
- スプレッドシートに出力するのが楽
デメリット
- 直近のものしか取得できない
- アーカイブ化されたものは不可
方針
- 動画のURLからvideoIdを取得
- videoIdからliveChatIdを取得
- 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"]が消える