Files
wehub-resource-sync 9b395f5cc3
E2E Headed Chrome / e2e-headed (macos-15) (push) Has been cancelled
E2E Headed Chrome / e2e-headed (ubuntu-latest) (push) Has been cancelled
E2E Headed Chrome / e2e-headed (windows-latest) (push) Has been cancelled
CI / build (macos-latest) (push) Has been cancelled
CI / build (ubuntu-latest) (push) Has been cancelled
CI / build (windows-latest) (push) Has been cancelled
CI / unit-test (push) Has been cancelled
CI / bun-test (push) Has been cancelled
CI / adapter-test (push) Has been cancelled
CI / smoke-test (macos-latest) (push) Has been cancelled
CI / smoke-test (ubuntu-latest) (push) Has been cancelled
Security Audit / audit (push) Has been cancelled
Build Chrome Extension / build (push) Has been cancelled
Trigger Website Rebuild (Docs Updated) / dispatch (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:39:48 +08:00

97 lines
4.3 KiB
JavaScript

/**
* YouTube comments — get video comments via InnerTube API.
*/
import { cli, Strategy } from '@jackwener/opencli/registry';
import { CommandExecutionError } from '@jackwener/opencli/errors';
import { parseVideoId } from './utils.js';
cli({
site: 'youtube',
name: 'comments',
access: 'read',
description: 'Get YouTube video comments',
domain: 'www.youtube.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'url', required: true, positional: true, help: 'YouTube video URL or video ID' },
{ name: 'limit', type: 'int', default: 20, help: 'Max comments (max 100)' },
],
columns: ['rank', 'author', 'text', 'likes', 'replies', 'time'],
func: async (page, kwargs) => {
const videoId = parseVideoId(kwargs.url);
const limit = Math.min(kwargs.limit || 20, 100);
await page.goto(`https://www.youtube.com/watch?v=${videoId}`);
await page.wait(3);
const data = await page.evaluate(`
(async () => {
const videoId = ${JSON.stringify(videoId)};
const limit = ${limit};
const cfg = window.ytcfg?.data_ || {};
const apiKey = cfg.INNERTUBE_API_KEY;
const context = cfg.INNERTUBE_CONTEXT;
if (!apiKey || !context) return {error: 'YouTube config not found'};
// Step 1: Get comment continuation token
let continuationToken = null;
// Try from current page ytInitialData
if (window.ytInitialData) {
const results = window.ytInitialData.contents?.twoColumnWatchNextResults?.results?.results?.contents || [];
const commentSection = results.find(i => i.itemSectionRenderer?.targetId === 'comments-section');
continuationToken = commentSection?.itemSectionRenderer?.contents?.[0]?.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token;
}
// Fallback: fetch via next API
if (!continuationToken) {
const nextResp = await fetch('/youtubei/v1/next?key=' + apiKey + '&prettyPrint=false', {
method: 'POST', credentials: 'include',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({context, videoId})
});
if (!nextResp.ok) return {error: 'Failed to get video data: HTTP ' + nextResp.status};
const nextData = await nextResp.json();
const results = nextData.contents?.twoColumnWatchNextResults?.results?.results?.contents || [];
const commentSection = results.find(i => i.itemSectionRenderer?.targetId === 'comments-section');
continuationToken = commentSection?.itemSectionRenderer?.contents?.[0]?.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token;
}
if (!continuationToken) return {error: 'No comment section found — comments may be disabled'};
// Step 2: Fetch comments
const commentResp = await fetch('/youtubei/v1/next?key=' + apiKey + '&prettyPrint=false', {
method: 'POST', credentials: 'include',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({context, continuation: continuationToken})
});
if (!commentResp.ok) return {error: 'Failed to fetch comments: HTTP ' + commentResp.status};
const commentData = await commentResp.json();
// Parse from frameworkUpdates (new ViewModel format)
const mutations = commentData.frameworkUpdates?.entityBatchUpdate?.mutations || [];
const commentEntities = mutations.filter(m => m.payload?.commentEntityPayload);
return commentEntities.slice(0, limit).map((m, i) => {
const p = m.payload.commentEntityPayload;
const props = p.properties || {};
const author = p.author || {};
const toolbar = p.toolbar || {};
return {
rank: i + 1,
author: author.displayName || '',
text: (props.content?.content || '').substring(0, 300),
likes: toolbar.likeCountNotliked || '0',
replies: toolbar.replyCount || '0',
time: props.publishedTime || '',
};
});
})()
`);
if (!Array.isArray(data)) {
const errMsg = data && typeof data === 'object' ? String(data.error || '') : '';
if (errMsg)
throw new CommandExecutionError(errMsg);
return [];
}
return data;
},
});