Time stream went offline

For my basic PHP Uptime API, using Nightbot, I was wanting to incorporate a feature for when the stream is offline to tell the person how long the stream has been offline. I know there are APIs out there such as:

https://api.twitch.tv/kraken/users/CHANNEL_NAME
and
https://api.twitch.tv/kraken/channels/CHANNEL_NAME

That will give me the last modified date and time, but that’s not necessarily when the stream was registered as being offline on the twitch servers. Is there a API that will output JSON REST for the stream offline date and time?

There’s no way to check offline time unless VODs are enabled and the last one hasn’t been deleted, in which case you can use the channel videos API.

1 Like

Okay, thank you. And in case anyone else is wondering about the API @3ventic mentioned, here it is.

This will bring up the last broadcast.
https://api.twitch.tv/kraken/channels/CHANNEL_NAME/videos?broadcasts=true&limit=1
and just remove the broadcasts=true from the URL and it’ll bring up the highlight(s) just modify the value after the limit= to any value you wish.
https://api.twitch.tv/kraken/channels/CHANNEL_NAME/videos?limit=1

I have a programm written in Java, that caches data from the twitch api. it updates the values periodicly (e.g. 5 minutes). I let it run on a Server.

That is how i handle things like your question by my own.
If you have some more things like this question, things the api can not serve u directly, it could be useful caching data by your own (but dont spam the API).

In php it would be like:

<?php

$_channel = "rocketbeanstv";
$data_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams/$_channel/"), true);

if ($data_array["stream"] != null){
    //call function
    UpdateSQL();
} else { //donothing }

and the Function “UpdateSQL” updates the column(DATETIME) in the row where channel = $_channel.

I’ve seen some people querying the kraken and caching the values. While this would work for just myself, I also allow other people to use my API for their own streams on my hosting. Wouldn’t this cause issues if I’m caching multiple streams?

Personally, i have no issues, just some lag cuz i pull all the data every 5 minutes.
i dont know how your api works and how it has to be use (returning data, input …), but if u know how to use and return data corectly, i think u wont see any issuse.

My extent of anything programming related is next to nothing. I basically only know VERY basic PHP, which I kind of picked up in order to make my own custom APIs for use with NightBot. This is the entire source of my UpTime command.

<?php
// No name was entered for the broadcaster.
if (empty($_GET["Broadcaster"]))
{
        echo 'Channel broadcaster field is empty!';
        die();
}
// Set names to lowercase for URL injection.
$BroadcasterLower = strtolower($_GET["Broadcaster"]);
// Set timezone to match Twitch servers for JSON date/ time.
date_default_timezone_set("Greenwich");
// Inject lowercase name.
$ch = curl_init("https://api.twitch.tv/kraken/streams/" . $BroadcasterLower);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
// Decode the above JSON data.
$StreamingData = json_decode($result, true);
// Get a workable date and time out of the provided JSON.
$UpTimeDateTime = date('Y-m-d H:i:s', strtotime($StreamingData['stream']['created_at']));
// Stream offline
if($StreamingData['stream'] == null)
{    
    // Try to get the last broadcast via VOD. AKA past broadcasts.
    // Totally copy and pasted this from a few lines above... But it works.
    $ch = curl_init("https://api.twitch.tv/kraken/channels/" . $BroadcasterLower . "/videos?broadcasts=true&limit=1");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    // Decode the above JSON data.
    $StreamVideos = json_decode($result, true);
    if($StreamVideos['videos'])
    {
        // Get the start time of the last broadcast, add the length of broadcast (in seconds) to get time broadcast ended.
        $StreamEndPoint = date('Y-m-d H:i:s', strtotime($StreamVideos['videos'][0]['recorded_at']) + $StreamVideos['videos'][0]['length']);
    }
    // User doesn't have VOD enabled. We can only guess at this point now.
    else
    {
        // Totally copy and pasted this from a few lines above... But it works.
        $ch = curl_init("https://api.twitch.tv/kraken/channels/" . $BroadcasterLower . "/");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        // Decode the above JSON data.
        $StreamData = json_decode($result, true);
        if($StreamData['display_name'] == null)
        {
            echo 'Sorry, the broadcaster name is invalid!';
            die();
        }
        $OfflineGuess = date('Y-m-d H:i:s', strtotime($StreamData['updated_at']));
    }
    // Print out the offline message.
    echo 'Sorry, ' . htmlspecialchars($_GET["Broadcaster"]) . ' has not been streaming for the past ';
    // Print out the precise time stream has been offline.
    if($StreamVideos['videos'])
    {
        echo GetDateDifference($StreamEndPoint);
    }
    // No precise time available. Guessing game it is.
    else
    {
        echo GetDateDifference($OfflineGuess);
    }
    echo '. Check back later or follow and enable notifications to know when ' . htmlspecialchars($_GET["Broadcaster"]) . ' streams next!';
    die();
}
// Stream online.
else
{
    // User is streaming. Print out info.
    echo $StreamingData['stream']['channel']['display_name'] . ' has been streaming ' . $StreamingData['stream']['channel']['game'] . ' for the past ';
    echo GetDateDifference($UpTimeDateTime);
    echo '.';
}
// Function to get the date difference.
function GetDateDifference($datetime)
{
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    $string = array
    (
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        }
        else
        {
            unset($string[$k]);
        }
    }
    return $string ? implode(', ', $string) . '' : '';
}
?>

Or I also have it on pastebin since I share all of my APIs on the NightBot community forums. Pastebin source for UpTime.php

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.