Advertisement
kyroskoh

Twitch CustomAPI - Uptime

May 7th, 2016
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.69 KB | None | 0 0
  1. <?php
  2. // Set names to lowercase for URL injection.
  3. $BroadcasterLower = strtolower($_GET["Broadcaster"]);
  4. // Set timezone to match Twitch servers for JSON date/ time.
  5. date_default_timezone_set("Greenwich");
  6. // Inject lowercase name.
  7. $ch = curl_init("https://api.twitch.tv/kraken/streams/" . $BroadcasterLower);
  8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  9. $result = curl_exec($ch);
  10. curl_close($ch);
  11. // Decode the above JSON data.
  12. $StreamData = json_decode($result, true);
  13. $UpTimeDateTime =date('Y-m-d H:i:s', strtotime($StreamData['stream']['created_at']));
  14.  
  15. // Stream offline
  16. if($StreamData['stream'] == null)
  17. {
  18.     echo 'Sorry, ' . htmlspecialchars($_GET["Broadcaster"]) . ' isn\'t currently streaming, check back later or follow and enable notifications to know when ' . htmlspecialchars($_GET["Broadcaster"]) . ' streams next!';
  19.     die();
  20. }
  21.  
  22. echo $StreamData['stream']['channel']['display_name'] . ' has been streaming ' . $StreamData['stream']['channel']['game'] . ' for the past ';
  23. echo GetDateDifference($UpTimeDateTime);
  24. echo '.';
  25.  
  26. // Function to get the date difference.
  27. function GetDateDifference($datetime)
  28. {
  29.     $now = new DateTime;
  30.     $ago = new DateTime($datetime);
  31.     $diff = $now->diff($ago);
  32.  
  33.     $diff->w = floor($diff->d / 7);
  34.     $diff->d -= $diff->w * 7;
  35.  
  36.     $string = array
  37.     (
  38.         'y' => 'year',
  39.         'm' => 'month',
  40.         'w' => 'week',
  41.         'd' => 'day',
  42.         'h' => 'hour',
  43.         'i' => 'minute',
  44.         's' => 'second',
  45.     );
  46.     foreach ($string as $k => &$v) {
  47.         if ($diff->$k) {
  48.             $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
  49.         }
  50.         else
  51.         {
  52.             unset($string[$k]);
  53.         }
  54.     }
  55.     return $string ? implode(', ', $string) . '' : '';
  56. }
  57. ?>
  58.  
  59. Example: Uptime.php?Broadcaster=TwitchBroadcaster
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement