I am currently writing a Discord Bot in C#. I have most the bot done but for this next update I am wanting to add on the capability of checking if the Streamer has Gone live. Currently I am polling the Twitch API and Pulling the JSON File that it has and checking whether or not the JSON Stream Object is Null or Not. But this takes 3-5 min after the streamer to go live before it finally sees that Stream is not Null even though I poll the JSON every 5 seconds. Is there anyway to do this more efficiently? My code is Below:
private const string Url = "https://api.twitch.tv/kraken/streams/streamer";
var request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/vnd.twitchtv.v5+json";
request.Headers.Add("Client-ID", "ID");
using (var s = request.GetResponse().GetResponseStream())
{
using (var sr = new System.IO.StreamReader(s))
{
var jsonObject = JObject.Parse(sr.ReadToEnd());
var jsonStream = jsonObject["stream"];
// twitch channel is online if stream is not null.
LastTwitchStatus = jsonStream.Type != JTokenType.Null;
}
}
All API endpoints are cached so the results will always be around 1 to 5 min behind (usually just 1 to 2 min). Also depending on what server deals with your API request the cache can be slightly different, so when you’re polling as frequently as every 5 seconds, you could hit one server that has a more recent result that says a server is live, then 5 seconds later hit a different server that returns a null stream because it just happens to be a bit behind, so polling that frequently wont help you and isn’t recommended.
Thank you for the information! What would you recommend as a delay between each poll. 30 seconds? Currently I have it set to poll every 5 seconds to check if the JSON stream object is NULL once I get a server that says its not NULL I display the message saying Online and then I delay for 60 seconds. I was running into that issue before and this is how I resolved that Problem
If you’re looking to detect stream up and stream down in real time, the only way to do that as far as I’m aware of is to utilize the undocumented (and unsupported) pubsub topic video-playback. This pull request here Twitch-API pull request, while declined, provides information on the pubsub topic. I just tested it using my library and it appears to be still working.
Again, because this is unsupported, Twitch can (and probably will) change it at any time without any sort of notification.