Test if Twitch stream is live with Python and TwitchAPI

Hey Guys, I want a program to test if a streamer is live and if so switching an OBS scene. I’m not really into programming and especially not the twitch API. I found this code to check if a streamer is live but it’s not working for me. It’s just returning “None”.


import requests

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

API_HEADERS = {
    'Client-ID' : 'myClientID',
    '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
                #print('online')
                return True
            else:
                return False
                #print('offline')
    except Exception as e:
        print("Error checking user: ", e)
        return False

print(checkUser("bikestreaming"))

This is from an old boken and outdated example.

You need to port this call to the New API

Thanks for the answer. Can you help me with that? I actually have no clue.

First, the use case indicated, you will need to generate an app access token

That is documented here https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow
And I have a python example here https://github.com/BarryCarlyon/twitch_misc/tree/master/authentication/app_access_tokens/python

Then store that token.

You should use this token till it expires

That token is then used with the streams endpoint

So something like this should do the trick (not tested I don’t do python). this just fixes the call, and doesn’t glue to two parts together

import requests

API_HEADERS = {
    'Client-ID' : 'myClientID',
    'Authorization' : 'Bearer '+token,
}

def checkUser(userName): #returns true if online, false if not
    url = 'https://api.twitch.tv/helix/streams?user_login='+userName

    try:
        req = reqSession.get(url, headers=API_HEADERS)
        jsondata = req.json()
        if len(jsondata['data']) == 1
            return True
        else:
            return False
    except Exception as e:
        print("Error checking user: ", e)
        return False

print(checkUser("bikestreaming"))

Edit: python code fix

Ok now I’m getting back “False” (not from the Exception).
I’m not quite sure if I understood you right. Is it right to put the client secret as the token?

API_HEADERS = {
    'Client-ID' : 'myClientID',
    'Authorization' : 'Bearer '+"client_secret",
}

Your example works btw.

No you need to put your token there that is generated yourself. Example code for that:
https://github.com/BarryCarlyon/twitch_misc/tree/master/authentication/app_access_tokens/python

HUGE ALERTING MASSIVE FLASHING TEXT IN RED → Its iDEFINTELY NOT your client secret.

Steps:

  1. Use Client ID + Client Secret to generate an App Access Token
  2. Use that App Access Token as the authorisation header

I feel very stupid.
As a string? If so it doesn’t work, still getting back False.

Btw how long can I use the generatet token.

Line 17 of my example, will print out the “keys”, one of the items in the object will be expires_in that tells you how long the key is good for. Generally speaking App Access Tokens last around 60 days.

You can also use the Validation endpoint, Authentication | Twitch Developers to check a tokens validity and current time left

I modifed my github example

import requests

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

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('live')
else:
    print('not live');

And this works (well aside from the target streamer now being offline)

My len() line is wrong in what I modified earlier

This code example is not a production ready example, you shouldn’t generate a new token every time

1 Like

Alright thanks a lot. I couldn’t have done it on my own. Thanks for sacrifice your time and have a nice Day!

Glad to have helped!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.