# Test if Twitch stream is live with Python and TwitchAPI

**URL:** <https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754>\
**Category:** API\
**Created:** [March 7, 2021, 1:54pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754 "2021-03-07T13:54:34Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![AimbotNooby](https://avatars.discourse-cdn.com/v4/letter/a/cdc98d/32.png) [@AimbotNooby](https://staging-discuss.dev.twitch.com/u/AimbotNooby)\
**Post date:** [March 7, 2021, 1:54pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/1 "2021-03-07T13:54:34Z")

</div>

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”.

```auto

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"))
```

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [March 7, 2021, 2:02pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/2 "2021-03-07T14:02:22Z")

</div>

This is from an old boken and outdated example.

You need to port this call to the New API

> **[Reference](https://dev.twitch.tv/docs/api/reference/)**
>
> Twitch Developer tools and services to integrate Twitch into your development or create interactive experience on twitch.tv.

---

<div class="post-metadata">

**Author:** ![AimbotNooby](https://avatars.discourse-cdn.com/v4/letter/a/cdc98d/32.png) [@AimbotNooby](https://staging-discuss.dev.twitch.com/u/AimbotNooby)\
**Post date:** [March 7, 2021, 2:16pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/3 "2021-03-07T14:16:31Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [March 7, 2021, 2:23pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/4 "2021-03-07T14:23:00Z")

</div>

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](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](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

```auto
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

---

<div class="post-metadata">

**Author:** ![AimbotNooby](https://avatars.discourse-cdn.com/v4/letter/a/cdc98d/32.png) [@AimbotNooby](https://staging-discuss.dev.twitch.com/u/AimbotNooby)\
**Post date:** [March 7, 2021, 2:39pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/5 "2021-03-07T14:39:31Z")

</div>

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?

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

```

Your example works btw.

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [March 7, 2021, 2:41pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/6 "2021-03-07T14:41:31Z")

</div>

> [@AimbotNooby](#):
>
> I’m not quite sure if I understood you right. Is it right to put the client secret as the token?

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](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

---

<div class="post-metadata">

**Author:** ![AimbotNooby](https://avatars.discourse-cdn.com/v4/letter/a/cdc98d/32.png) [@AimbotNooby](https://staging-discuss.dev.twitch.com/u/AimbotNooby)\
**Post date:** [March 7, 2021, 2:47pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/8 "2021-03-07T14:47:25Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [March 7, 2021, 3:01pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/9 "2021-03-07T15:01:29Z")

</div>

> [@AimbotNooby](#):
>
> 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](https://dev.twitch.tv/docs/authentication/#validating-requests) to check a tokens validity and current time left

> [@AimbotNooby](#):
>
> As a string? If so it doesn’t work, still getting back False.

I modifed my github example

```python
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

---

<div class="post-metadata">

**Author:** ![AimbotNooby](https://avatars.discourse-cdn.com/v4/letter/a/cdc98d/32.png) [@AimbotNooby](https://staging-discuss.dev.twitch.com/u/AimbotNooby)\
**Post date:** [March 7, 2021, 3:07pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/10 "2021-03-07T15:07:32Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [March 7, 2021, 3:10pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/11 "2021-03-07T15:10:08Z")

</div>

Glad to have helped!

---

<div class="post-metadata">

**Author:** ![system](https://d2spem0quai2ol.cloudfront.net/original/2X/0/05909729875cce3b53e59d5561c4d23bb14948fc.png) [@system](https://staging-discuss.dev.twitch.com/u/system)\
**Post date:** [April 6, 2021, 3:10pm UTC](https://staging-discuss.dev.twitch.com/t/test-if-twitch-stream-is-live-with-python-and-twitchapi/30754/12 "2021-04-06T15:10:09Z")

</div>

Closed on April 6, 2021, 3:10pm UTC

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