Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There Any Way To Check if a Twitch Stream Is Live Using Python?

Tags:

python

twitch

I'm just wondering if there is any way to write a python script to check to see if a twitch.tv stream is live?

I'm not sure why my app engine tag was removed, but this would be using app engine.

like image 949
suitegamer Avatar asked Aug 21 '12 22:08

suitegamer


6 Answers

I hated having to go through the process of making an api key and all those things just to check if a channel was live, so i tried to find a workaround:

As of june 2021 if you send a http get request to a url like https://www.twitch.tv/CHANNEL_NAME, in the response there will be a "isLiveBroadcast": true if the stream is live, and if the stream is not live, there will be nothing like that.

So i wrote this code as an example in nodejs:

const fetch = require('node-fetch');
const channelName = '39daph';

async function main(){
    let a = await fetch(`https://www.twitch.tv/${channelName}`);
    if( (await a.text()).includes('isLiveBroadcast') )
        console.log(`${channelName} is live`);
    else
        console.log(`${channelName} is not live`);
}

main();

here is also an example in python:

import requests
channelName = '39daph'

contents = requests.get('https://www.twitch.tv/' +channelName).content.decode('utf-8')

if 'isLiveBroadcast' in contents: 
    print(channelName + ' is live')
else:
    print(channelName + ' is not live')
like image 171
GreenGoes 27 Avatar answered Oct 12 '22 10:10

GreenGoes 27


Here is a more up to date answer using the latest version of the Twitch API (helix). (kraken is deprecated and you shouldn't use GQL since it's not documented for third party use).

It works but you should store the token and reuse the token rather than generate a new token every time you run the script.


import requests

client_id = ''
client_secret = ''
streamer_name = ''

body = {
    'client_id': client_id,
    'client_secret': client_secret,
    "grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token', body)

#data output
keys = r.json();

print(keys)

headers = {
    'Client-ID': client_id,
    'Authorization': 'Bearer ' + keys['access_token']
}

print(headers)

stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers)

stream_data = stream.json();

print(stream_data);

if len(stream_data['data']) == 1:
    print(streamer_name + ' is live: ' + stream_data['data'][0]['title'] + ' playing ' + stream_data['data'][0]['game_name']);
else:
    print(streamer_name + ' is not live');
like image 36
Barry Carlyon Avatar answered Sep 19 '22 19:09

Barry Carlyon


Since all answers are actually outdated as of 2020-05-02, i'll give it a shot. You now are required to register a developer application (I believe), and now you must use an endpoint that requires a user-id instead of a username (as they can change).

See https://dev.twitch.tv/docs/v5/reference/users

and https://dev.twitch.tv/docs/v5/reference/streams

First you'll need to Register an application

From that you'll need to get your Client-ID.

The one in this example is not a real

TWITCH_STREAM_API_ENDPOINT_V5 = "https://api.twitch.tv/kraken/streams/{}"

API_HEADERS = {
    'Client-ID' : 'tqanfnani3tygk9a9esl8conhnaz6wj',
    'Accept' : 'application/vnd.twitchtv.v5+json',
}

reqSession = requests.Session()

def checkUser(userID): #returns true if online, false if not
    url = TWITCH_STREAM_API_ENDPOINT_V5.format(userID)

    try:
        req = reqSession.get(url, headers=API_HEADERS)
        jsondata = req.json()
        if 'stream' in jsondata:
            if jsondata['stream'] is not None: #stream is online
                return True
            else:
                return False
    except Exception as e:
        print("Error checking user: ", e)
        return False
like image 31
Cherona Avatar answered Oct 12 '22 09:10

Cherona


RocketDonkey's fine answer seems to be outdated by now, so I'm posting an updated answer for people like me who stumble across this SO-question with google. You can check the status of the user EXAMPLEUSER by parsing

https://api.twitch.tv/kraken/streams/EXAMPLEUSER

The entry "stream":null will tell you that the user if offline, if that user exists. Here is a small Python script which you can use on the commandline that will print 0 for user online, 1 for user offline and 2 for user not found.

#!/usr/bin/env python3

# checks whether a twitch.tv userstream is live

import argparse
from urllib.request import urlopen
from urllib.error import URLError
import json

def parse_args():
    """ parses commandline, returns args namespace object """
    desc = ('Check online status of twitch.tv user.\n'
            'Exit prints are 0: online, 1: offline, 2: not found, 3: error.')
    parser = argparse.ArgumentParser(description = desc,
             formatter_class = argparse.RawTextHelpFormatter)
    parser.add_argument('USER', nargs = 1, help = 'twitch.tv username')
    args = parser.parse_args()
    return args

def check_user(user):
    """ returns 0: online, 1: offline, 2: not found, 3: error """
    url = 'https://api.twitch.tv/kraken/streams/' + user
    try:
        info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
        if info['stream'] == None:
            status = 1
        else:
            status = 0
    except URLError as e:
        if e.reason == 'Not Found' or e.reason == 'Unprocessable Entity':
            status = 2
        else:
            status = 3
    return status

# main
try:
    user = parse_args().USER[0]
    print(check_user(user))
except KeyboardInterrupt:
    pass
like image 6
timgeb Avatar answered Oct 12 '22 09:10

timgeb


It looks like Twitch provides an API (documentation here) that provides a way to get that info. A very simple example of getting the feed would be:

import urllib2

url = 'http://api.justin.tv/api/stream/list.json?channel=FollowGrubby'
contents = urllib2.urlopen(url)

print contents.read()

This will dump all of the info, which you can then parse with a JSON library (XML looks to be available too). Looks like the value returns empty if the stream isn't live (haven't tested this much at all, nor have I read anything :) ). Hope this helps!

like image 5
RocketDonkey Avatar answered Oct 12 '22 08:10

RocketDonkey


Use the twitch api with your client_id as a parameter, then parse the json:

https://api.twitch.tv/kraken/streams/massansc?client_id=XXXXXXX

Twitch Client Id is explained here: https://dev.twitch.tv/docs#client-id, you need to register a developer application: https://www.twitch.tv/kraken/oauth2/clients/new

Example:

import requests
import json

def is_live_stream(streamer_name, client_id):

    twitch_api_stream_url = "https://api.twitch.tv/kraken/streams/" \
                    + streamer_name + "?client_id=" + client_id

    streamer_html = requests.get(twitch_api_stream_url)
    streamer = json.loads(streamer_html.content)

    return streamer["stream"] is not None
like image 2
Hhhhhhh Avatar answered Oct 12 '22 09:10

Hhhhhhh