Creating a Embed that only shows when stream is online

So the following code is no longer working. Can anyone tell me what changed? I rarely work with PHP “disclaimer”

The code is meant to load the embed only when the stream is live.

<?php
$streamChannel = "overwatchleague";  

$json_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams.json?channel=$streamChannel"), true);  

if(isset($json_array['streams'][0]['channel'])) {  
echo "<div id='streamonline'><iframe
src="http://player.twitch.tv/?channel= overwatchleague&muted=true"
name="report"
height="100%"
width="100%"
frameborder="0"
scrolling="no"
allowfullscreen="true">
</iframe></div>";  
} else {  
echo "<div id='streamoffline'>Display 0</div>";  
}  

?>

You need to include your client id in API requests, otherwise calling that endpoint will just return {"error":"Bad Request","status":400,"message":"No client id specified"}

Like so?

<?php
$streamChannel = "overwatchleague";  

$json_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams.json?channel=overwatchleague"), true);  

if(isset($json_array['streams'][0]['channel'])) {  
echo "<div id='streamonline'><iframe
src="http://player.twitch.tv/?channel= overwatchleague&muted=true"
name="report"
height="100%"
width="100%"
frameborder="0"
scrolling="no"
allowfullscreen="true">
</iframe></div>";  
} else {  
echo "<div id='streamoffline'>Display 0</div>";  
}  

?>

No, you need to actually register an app with Twitch (as explained in this documentation https://dev.twitch.tv/docs/authentication#registration)

Once you register an app it will provide you with a client id which you can add to the querystring of that API request you’re making, this will allow it to return the stream data you’re after.

I just read that as your message alert came through lol. Lets see if it works

So now that I have an ID where does it go in this… again this is the first i’ve worked with this.

You can add &client_id= followed by your client id to the end of the request URL and it should now work (at least the API request anyway, I’m not a PHP guy so can’t vouch for the rest of the code :sweat_smile:)

Yes that seems to be the problem… as the embed still shows up when the stream is not online

New PHP code still doesn’t work

<?php
function twitch_stream_live() {

$channel = 'overwatchleague';
$client_id = 'load your code';

$url = 'https://api.twitch.tv/kraken/streams/' . $channel . '?client_id=' . $client_id;
$response = wp_remote_get( $url );
	
if ( !is_wp_error( $response ) && $response['response']['code'] === 200 ) {

    $body = json_decode( wp_remote_retrieve_body( $response ) );

if( twitch_stream_live() ){
<iframe
src="http://player.twitch.tv/?channel=dallas&muted=true"
height="720"
width="1280"
frameborder="0"
scrolling="no"
allowfullscreen="true">
</iframe>
} else {

do not load
}

}

return false;

}

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