Laravel 和 Twitch API

Laravel and Twitch API

我在更新我的 laravel 项目上的流时遇到了一个小问题,我正在尝试定义流媒体是否处于活动状态,如果它们不在我的应用程序中则隐藏,但是当存在时一个不直播的流光它给了我..

Trying to get property of non-object

我的 cronjob 回发看起来像这样:

$twitch_api = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.$stream->channel));
if($twitch_api->stream == null) $live = 0;
else $live = 1;

$update = Streams::where('id', $stream->id)->firstOrFail();
$update->thumb = $twitch_api->stream->preview->large;
$update->game = $twitch_api->stream->channel->game;
$update->status = $live;
$update->save();

Twitch API 离线时显示此...

{"stream":null,"_links":{"self":"https://api.twitch.tv/kraken/streams/chan","channel":"https://api.twitch.tv/kraken/channels/chan"}}

知道为什么它给我非对象吗?

谢谢!

当流处于离线状态并且 "stream":null 您的以下代码行将不起作用:

$update->thumb = $twitch_api->stream->preview->large;
$update->game = $twitch_api->stream->channel->game;

您需要将其封装在 ifcase 语句中,这样当流处于离线状态时它就不会 运行。如果它是实时的,您已经将 $live 设置为 1,您只需要稍后在控制语句中使用它。

像这样:

$twitch_api = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.$stream->channel));
if($twitch_api->stream == null) $live = 0;
else $live = 1;
$update = Streams::where('id', $stream->id)->firstOrFail();
switch($live){
   case 0:
     // do stuff when the stream is offline
     break;
   case 1: 
     // do stuff when the stream is online
     $update->thumb = $twitch_api->stream->preview->large;
     $update->game = $twitch_api->stream->channel->game;
     break;
}
$update->status = $live;
$update->save();