youtube-data-mcp
Version:
Extract YouTube transcripts and comments for analysis
53 lines (52 loc) • 1.91 kB
JavaScript
import axios from 'axios';
const SERPAPI_KEY = process.env.SERPAPI_KEY;
const SERPAPI_BASE_URL = 'https://serpapi.com/search.json';
export async function fetchCommentsFromSerpApi(videoId, limit = 100, sort = 'relevance') {
if (!SERPAPI_KEY) {
throw new Error('SERPAPI_KEY is not set in environment variables');
}
try {
const response = await axios.get(SERPAPI_BASE_URL, {
params: {
api_key: SERPAPI_KEY,
engine: 'youtube',
video_id: videoId,
order_by: sort === 'time' ? 'date' : 'relevance'
}
});
// 비디오 제목 추출
const videoTitle = response.data.title || undefined;
// 페이지네이션 토큰
const nextPageToken = response.data.serpapi_pagination?.token || undefined;
// 댓글 목록이 없는 경우
if (!response.data.comments || !Array.isArray(response.data.comments)) {
return {
videoTitle,
comments: [],
nextPageToken
};
}
// 댓글 파싱
const comments = response.data.comments
.slice(0, limit)
.map((comment) => ({
author: comment.author || 'Anonymous',
text: comment.text || '',
time: comment.time || '',
likes: comment.likes || 0,
replies: comment.replies || 0
}));
return {
videoTitle,
comments,
nextPageToken
};
}
catch (error) {
console.error(`Error fetching comments from SerpAPI:`, error);
if (axios.isAxiosError(error) && error.response) {
throw new Error(`SerpAPI error: ${error.response.status} - ${error.response.data.error || 'Unknown error'}`);
}
throw new Error('Failed to fetch comments from SerpAPI');
}
}