Search code examples
htmlruby-on-railsrubygemstwitch

Twitch-API ruby gem updates view counts slowly, how can I get real-time stream data?


I'm trying to make an app that tracks viewer counts for a particular Twitch stream over time, eventually to display them real-time on a web page. However, the ruby gem I am using, twitch-api, only seems to update its view count approximately every 5 minutes. Twitch's main website updates this information consistently every 10-20 seconds.

Why is the API / gem refreshing so slowly, and alternatively, is there a way I can access the updating data directly from the website?

Here is my test Ruby code using the gem:

previous_view_count = 0

while true do
    @twitch_client = Twitch::Client.new(
        client_id: @client_id,
        client_secret: @client_secret)
        username = "ludwig"

        twitch_id = @twitch_client.get_users({login: username}).data.first.id
        stream_info = @twitch_client.get_streams({user_id: twitch_id}).data.first
        if stream_info.viewer_count != previous_view_count then
            puts("Data for Twitch streamer: " + username)
            puts("Title: " + stream_info.title)
            puts("View count: " + stream_info.viewer_count.to_s)
            previous_view_count = stream_info.viewer_count
        end
    sleep(60)
    puts("-----")
end

Solution

  • Seems like the Twitch API's viewer count only updates at a very slow interval. Your best bet would be to look into establishing a WebSocket connection with their pubsub endpoint. Although the viewer count is not explicitly on their documentation, tracing the websocket connection while watching a stream using your browser's developer tools, it seems like you can subscribe to the video-playback-by-id topic and receive the viewcount every 30 seconds.

    Here's a sample LISTEN payload:

    {"type":"LISTEN","nonce":"zeMjhYYhJdwfVEjLGvO84eBSAHsIYk","data":{"topics":["video-playback-by-id.121059319"],"auth_token":"some_auth_token"}}
    

    Here's a sample MESSAGE response payload:

    {"type":"MESSAGE","data":{"topic":"video-playback-by-id.121059319","message":"{\"type\":\"viewcount\",\"server_time\":1618283400.433843,\"viewers\":28735}"}}