Home > Uncategorized > How to download “past broadcasts” from twitch.tv

How to download “past broadcasts” from twitch.tv

Unfortunately justin api no longer support twitch.tv channels and new twitch api doesn’t show direct links for flv videos. But fortunately we can still use listing by archive id using this url:
http://api.justin.tv/api/broadcast/by_archive/yyyyyyyyy.json

So, lets adopt our previous source to get fully working code in php witch download all videos from our favorite twitch channel:

<?php
$url = "https://api.twitch.tv/kraken/channels/xxxxxxx/videos?limit=100&broadcasts=true";

$c = curl_init($url);
$options = array(
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_HTTPHEADER => array('Content-type: application/json'),
	CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
);
curl_setopt_array( $c, $options );
$json = curl_exec($c);
$json_a = json_decode($json,true);

foreach($json_a['videos'] as $v) {
	$id = $v['_id'];
	$id = preg_replace('/[^0-9.]+/', '', $id);
	if(!history_check($id)){
		$vid = "http://api.justin.tv/api/broadcast/by_archive/$id.json";
		$d = curl_init($vid);
		$options2 = array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => array('Content-type: application/json')
		);
		curl_setopt_array( $d, $options2 );
		$json2 = curl_exec($d);
		$json2_a = json_decode($json2,true);
		exec('wget --progress=dot:mega -c '.$json2_a[0]['video_file_url'].' -O "downloads/'.$json2_a[0]['start_timestamp'].' - '.format_title($json2_a[0]['title']).'.flv"', $array,$exit_code);
		echo 'Exit code: '.$exit_code."\n";
		echo $array;
		echo "\n";
		history_add($id);
		echo implode('"\n"', $array);
	}
}

function format_title($title){ //format title and limit to 50 chars
	$out = preg_replace('/[^a-zA-Z \.]/','', $title);
	$out = substr($out, 0, 50); 
	return $out;
}
function history_check($date){
	$data = file_get_contents('history');

	if(strpos($data, $date) !== FALSE)
	{
		$out = TRUE;
	}
	else
	{
		$out = FALSE;
	}
return $out;
}

function history_add($date){
	file_put_contents('history', $date."\n", FILE_APPEND);
}
?>
Categories: Uncategorized
  1. Steve
    01/09/2013 at 12:02

    Hello,
    Can you tell me how can I use this script to download videos from twitch, I’m not a programmer so my knowlede is limited.
    Would it work If I edit the line nr 2 with a streamer’s name and past broadcast number, save’it as .php and use a software like xamp to make a server?

    Thanks.

  1. 08/08/2013 at 23:23

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: