M
M
Michael2014-01-31 17:38:39
YouTube
Michael, 2014-01-31 17:38:39

How to write a script to notify you with a sms message about a new video on YouTube?

Hello.
I describe the situation:
There is a YouTube channel of one user, he uploads a new video about once every couple of weeks.
Constantly go to Yotube and check laziness.
You can turn on notifications of new messages via e-mail, but these messages arrive, in most cases, after an hour or even more.
I decided to write a script that will check if a new video has appeared on the user's channel.
If so, please send me a text message.
Through trial and error, it turned out that the link of the form

https://gdata.youtube.com/feeds/users/Пользователь/uploads
returns a page with information about the user's latest updates. Each video has a tag <published>with a unique post date, such as <published>2014-01-28T14:57:53.000Z</published>.
It was decided to check the content of the first occurrence <published>, if the value differs from the previously known - a new video has appeared.
So, the script was born (written below). After that, it remains to figure out how to run it for execution. I have my own small site, it was decided to upload the script there and run it via Cron, in the hosting control panel. Works.
And now the nuance: as soon as a new video appears, the script will constantly send sms until it is stopped, because. the first occurrence <published>will already be different when you run the script again.
Now the question is: how to stop the script after the first successful execution (i.e. a new video is found).
I will be glad for any help.
<?php

function send_sms($to, $msg, $login, $password){
 $u = 'http://www.websms.ru/http_in5.asp';
 $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, 'Http_username='.urlencode($login). '&Http_password='.urlencode($password).  '&Phone_list='.$to.'&Message='.urlencode($msg));
 curl_setopt($ch, CURLOPT_URL, $u);
 $u = trim(curl_exec($ch));
 curl_close($ch);
 preg_match("/message_id\s*=\s*[0-9]+/i", $u, $arr_id );
 $id = preg_replace("/message_id\s*=\s*/i", "", @strval($arr_id[0]) );
 return $id;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11');

$url = 'https://gdata.youtube.com/feeds/users/USER/uploads'; //ссылка на канал
$find = '<published>2014-01-26T04:00:00.000Z</published>'; //время публикации последнего видео на канале пользователя
$mob = ''; //твой мобильный в формате +380123456789
$login = ''; //твой логин на сервисе отправки смс
$pass = '';//твой пароль на сервисе отправки смс

curl_setopt($ch, CURLOPT_URL, $url);
$page = curl_exec($ch);
$page = iconv('utf-8', 'windows-1251', $page);

if ($page != false){
  $page = trim(substr($page, 0, 20000));
  $pos = strpos($page, $find);
  
  if ($pos == true) {
    $msg = 'You have a new video!!!';
  //send_sms($mob, $msg, $login, $pass);
  } 

} 

else die;
curl_close($ch);
?>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Danny Chernyavsky, 2014-01-31
@SnowLion

Something like this

<?php

function send_sms($to, $msg, $login, $password){
  $u = 'http://www.websms.ru/http_in5.asp';
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'Http_username='.urlencode($login). '&Http_password='.urlencode($password).  '&Phone_list='.$to.'&Message='.urlencode($msg));
  curl_setopt($ch, CURLOPT_URL, $u);

 	$u = trim(curl_exec($ch));
 	curl_close($ch);

 	preg_match("/message_id\s*=\s*[0-9]+/i", $u, $arr_id );
 	$id = preg_replace("/message_id\s*=\s*/i", "", @strval($arr_id[0]) );

 	return $id;
}

// some defaults
$url = 'https://gdata.youtube.com/feeds/users/USER/uploads'; //ссылка на канал

$filename = './lastvideo.txt';
$find = file_get_contents($filename);
$find = !empty($find) ? $find : '<published>2014-01-26T04:00:00.000Z</published>'; //время публикации последнего видео на канале пользователя

$mob = ''; //твой мобильный в формате +380123456789
$login = ''; //твой логин на сервисе отправки смс
$pass = '';//твой пароль на сервисе отправки смс

// запрос к youtube
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11');
curl_setopt($ch, CURLOPT_URL, $url);
$page = curl_exec($ch);
curl_close($ch);

// parse
if ($page == false) {
  exit('Empty curl response.');
}

preg_match_all('/(<published>.*?<\/published>)/ui', $page, $matches);
if (empty($matches[1])) {
  exit('Empty parse results.');
}

if ($matches[1][0] != $find) {	// если новое видео вверху, то оно должно быть нулевым матчем, иначе - появилось что-то новое
  file_put_contents($filename, $matches[1][0]); // пишем дату публикации нового видео, чтоб не было смс постоянно

  $msg = 'You have a new video!!!';
  //send_sms($mob, $msg, $login, $pass);
}

Sorry if it's wrong, but the idea is the same as @Medic84's . Also, I slightly tweaked the code for my taste.
The code has not been tested, problems may be in the regular expression.

D
Dmitry Kozhanov, 2014-01-31
@Medic84

Found video -> Write to file -> Next script call -> Check if the last video matches the time from the file, if it does, then do nothing.

else die;
curl_close($ch);

And who taught you to kill the script before the resources are released?

A
avalak, 2014-01-31
@avalak

There is an easier option:
- Google Apps Script or Google App Engine for logic.
- sms.ru to send sms (60 free sms to your number per day).
It turns out very reliable, flexible and, which is nice, for free.

F
frees2, 2014-01-31
@frees2

I strongly advise you to parse JSON V3. You just need to get your key on google api.
Loads instantly, by the eye "several times faster" V2 RSS.
Apploads or search, selection, feeds are the same in speed,
(applause
$fff2 =' https://www.googleapis.com/youtube/v3/playlistItem... '.$v.'&key=AIzaSyA...... ........3gEo'; )

Варианты по поиску
$v21 ='&type=channel&order=viewCount';
$v21 ='&type=video&order=viewCount';
..................


$fff ='https://www.googleapis.com/youtube/v3/search?key=AIz....................DAo3gEo'.$v21.'&part=snippet&safeSearch=none&maxResults=25';
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $fff);
 curl_setopt($ch, CURLOPT_USERAGENT, 'PHP Bot');
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_exec($ch); 
  $json = curl_exec($ch);
  curl_close($ch);
  if ($json !== false) { 
$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
setlocale(LC_ALL, 'ru_RU.utf8');
 Header("Content-Type: text/html;charset=UTF-8");
$json = json_decode($json, true) ; 
// print_r($json);


if (isset($json['items']))
 {
 foreach($json['items'] as $items) {
$thumbnails =$items['snippet']['thumbnails']['default']['url'];
$title =$items['snippet']['title'];
// $description =$items['snippet']['description'];
$channelId =$items['snippet']['channelId'];
.................................

The api allows you to customize the feed, for example, to receive only the latest date, or a new title, or both, that is, the server will return only the date or otherwise, only the necessary one and not the entire feed (RSS type) for parsing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question