본문 바로가기
IT창고/PHP

youtube 영상 실시간 채팅 내용 수집 php

by 창구창고 2023. 2. 15.
반응형

사진출처: unsplash

YouTube의 실시간 채팅 내용 수집을 위해서는 YouTube API를 사용해야 합니다. 

YouTube API를 사용하면 HTTP 요청을 보내고 JSON 응답을 받아 채팅 내용을 추출할 수 있습니다.

먼저, YouTube API를 사용하기 위해서는 Google Developers Console에서 프로젝트를 생성하고 API 키를 발급받아야 합니다. 

그리고 PHP에서 CURL을 사용해 YouTube API에 HTTP 요청을 보내고, JSON 응답을 처리하여 채팅 내용을 추출할 수 있습니다.

// YouTube API 키
$apiKey = 'your_api_key';

// 영상 ID
$videoId = 'your_video_id';

// YouTube API 요청 URL
$url = 'https://www.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id='.$videoId.'&key='.$apiKey;

// CURL을 사용해 HTTP 요청 보내기
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);

// JSON 응답 처리
$json = json_decode($response, true);

// 실시간 채팅 ID
$liveChatId = $json['items'][0]['liveStreamingDetails']['activeLiveChatId'];

// YouTube API 요청 URL
$url = 'https://www.googleapis.com/youtube/v3/liveChat/messages?liveChatId='.$liveChatId.'&part=snippet,authorDetails&maxResults=2000&key='.$apiKey;

// CURL을 사용해 HTTP 요청 보내기
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);

// JSON 응답 처리
$json = json_decode($response, true);

// 채팅 내용 추출
foreach ($json['items'] as $item) {
    $textMessageDetails = $item['snippet']['textMessageDetails'];
    $messageText = $textMessageDetails['messageText'];
    $authorName = $item['authorDetails']['displayName'];
    echo '['.$authorName.'] '.$messageText.'<br>';
}
반응형