(warning) Бота мы начали писать тут: http://nujensait.ru/10776/

Сейчас он умеет отвечать на простейшие запросы…

Хочется научить его читать мой ютуб канал и выводить последние/случайные видео оттуда.

/**/

Документашка

Ищем по теме ….

Получаем API токен Google тут

https://code.google.com/apis/console

Разрешаем доступ YouTube Data API v3

Смотрим ID плейлиста

https://www.youtube.com/playlist?list={id_канала}

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={id_list}&maxResults=50&key={api_key} — получаем 50 видео с канала в формате JSON

Пишем код

Генерируем ключ API

Получаем API токен Google : https://code.google.com/apis/console

Youtube search:

Активируем:

Далее кнопка “Create credentials“

Здесь нам нужен “ключ API“

Запоминаем/сохраняем ключ:


Ставим API библиотеку

composer require google/apiclient:^2.12.1

  - Installing google/auth (v1.21.0): Extracting archive
  - Installing google/apiclient-services (v0.243.0): Extracting archive
  - Installing google/apiclient (v2.12.1): Extracting archive
17 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
13 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

Скрипт индексации youtube канала

Пишем скриптик, который найдет нужное кол-во видео роликов с указанным ключевым словом.

Пример №1: поиск видео по ключевому слову (глобальный)

<?php

/**
 * Sample PHP code for youtube.search.list
 * See instructions for running these code samples locally:
 * https://developers.google.com/explorer-help/guides/code_samples#php
 * @source https://www.freakyjolly.com/google-api-php-how-to-use-google-api-like-youtube-data-v3-api-in-php/
 */

if (!file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/../../../vendor/autoload.php';

Class YoutubeApi {
    /**
     * @return GoogleServiceYouTubeSearchListResponse
     */
    public function getVideosList(): GoogleServiceYouTubeSearchListResponse {
        $client = new Google_Client();
        $client->setApplicationName('API code samples');
        $client->setDeveloperKey('ХХХХХХХХХХХХХХХХХХХХХХХХ');

        // Define service object for making API requests.
        $service = new Google_Service_YouTube($client);

        $queryParams = [
            'maxResults' => 5,
            'q' => 'mishaikon'
        ];

        $response = $service->search->listSearch('snippet', $queryParams);
        return $response;
    }
}

$ytApi = new YoutubeApi();
$list = $ytApi->getVideosList();

print_r($list['items']);
print "Videos found: " . count($list['items']);
print "n";

(плюс) Работает: находит 5 видео по запросу “mishaikon“

    [4] => GoogleServiceYouTubeSearchResult Object
        (
....
            [id] => GoogleServiceYouTubeResourceId Object
                (
                    [channelId] => 
                    [kind] => youtube#video
                    [playlistId] => 
                    [videoId] => 9Zjttqj3uk4
                    [internal_gapi_mappings:protected] => Array
                        (
                        )
                    [modelData:protected] => Array
                        (
                        )
                    [processed:protected] => Array
                        (
                        )
                )
....
        )
)
Videos found: 5

(звезда) нас тут интересует только ИД видео: [id][videoId](ниже сформируем URL-s с этими ИД)

Допишем наш класс т.о., чтобы могли получать случайное видео по указанной поисковой фразе (метод searchRandomVideo):

<?php

/**
 * Work with Youtube API
 */

class MyYoutubeApi
{
    private $client = null;
    private $service = null;
    private const MAX_VIDEOS_LIMIT = 50;
    private const CONFIG_NAME = "mishaikon_bot.ini";

    public function __construct()
    {
        // read API key from config
        $config = parse_ini_file(__DIR__ . '/' . self::CONFIG_NAME, true);
        $apiKey = $config['youtube']['api_key'];
        if (!$apiKey) {
            throw new DomainException("apiKey is undefined");
        }

        $this->client = new Google_Client();
        $this->client->setApplicationName('API code samples');
        $this->client->setDeveloperKey($apiKey);

        if (!$this->client) {
            throw new DomainException("Cannot init API client");
        }

        // Define service object for making API requests.
        $this->service = new Google_Service_YouTube($this->client);

        if (!$this->service) {
            throw new DomainException("Cannot init API connection");
        }
    }


    /**
     * @return GoogleServiceYouTubeSearchListResponse
     */
    public function searchVideosList(string $query, int $limit): GoogleServiceYouTubeSearchListResponse
    {

        $queryParams = [
            'maxResults' => $limit,
            'q' => $query
        ];

        $response = $this->service->search->listSearch('snippet', $queryParams);

        return $response;
    }

    /**
     * @return array<string>
     */
    public function searchVideosUrlsList(string $query, int $limit): array
    {
        $list = $this->searchVideosList($query, $limit);

        /** @var GoogleServiceYouTubeSearchResult $v */
        foreach ($list as $v) {
            $videoId = $v->getId()->getVideoId();
            if($videoId) {
                $urls[] = "https://www.youtube.com/watch?v=" . $videoId;
            }
        }

        return $urls;
    }

    /**
     * @param string $query
     * @return string
     */
    public function searchRandomVideo(string $query): string
    {
        $list = $this->searchVideosUrlsList($query, self::MAX_VIDEOS_LIMIT);
        $key = array_rand($list, 1);
        $url = $list[$key];

        return $url;
    }
}

(звезда) параллельно ставим нужную библиотеку для работы с АПИ ютуба:

composer require google/apiclient:~2.0"

(плюс) смотрим пример по работа с ней тут: https://www.freakyjolly.com/google-api-php-how-to-use-google-api-like-youtube-data-v3-api-in-php/

(warning) Используем эту библиотеку для получения/вывода ботом случайного видео из Ютуба:

Добавляем в mishaikon_bot.php :

    /**
     * @param string $reply
     * @return MessageObject
     * @throws TelegramBotExceptionsTelegramSDKException
     */
    public function sendHtmlMsg(string $reply): MessageObject
    {
        return $this->tgApi->sendMessage(['chat_id' => $this->msg->getChatId(), 'parse_mode' => 'HTML', 'disable_web_page_preview' => false, 'text' => $reply]);
    }

    /**
     * get random video from Youtube
     * @return bool
     * @throws TelegramBotExceptionsTelegramSDKException
     */
    private function actVideo(): bool
    {
        $ytApi = new MyYoutubeApi();
        $url = $ytApi->searchRandomVideo('mishaikon');

        $this->sendHtmlMsg($url);

        return true;
    }

Проверяем функционал

Пишем сообщение боту:

(плюс) получаем случайное видео, найденное по ключевому слову “mishaikon“, УРА


Пример №2: получаем список видео с нашего канала

Пишем скриптик, который создаст список всех видео с канала (нужны их URLS)

(warning) Будем парсить мой канал: https://www.youtube.com/c/mishaikon/videos

(звезда) см : https://stackoverflow.com/a/36387404/3928685

Here is a video from Google Developers showing how to list all videos in a channel in v3 of the YouTube API: https://youtu.be/RjUlmco7v2M

There are two steps:

Query Channels to get the «uploads» Id. eg https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails

Use this «uploads» Id to query PlaylistItems to get the list of videos. eg https://www.googleapis.com/youtube/v3/playlistItems?playlistId={«uploads» Id}&key={API key}&part=snippet&maxResults=50

(….) Продолжение следует : получение случайного видео непосредственно из указанного канала

Tags

Нет комментариев

Добавить комментарий

Ваш адрес email не будет опубликован.

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.