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

后端 未结 7 476
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 18:44

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

相关标签:
7条回答
  • 2021-02-04 19:26

    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
    
    0 讨论(0)
  • 2021-02-04 19:27

    This solution doesn't require registering an application

    import requests
    
    HEADERS = { 'client-id' : 'kimne78kx3ncx6brgo4mv6wki5h1ko' }
    GQL_QUERY = """
    query($login: String) {
        user(login: $login) {
            stream {
                id
            }
        }
    }
    """
    
    def isLive(username):
        QUERY = {
            'query': GQL_QUERY,
            'variables': {
                'login': username
            }
        }
    
        response = requests.post('https://gql.twitch.tv/gql',
                                 json=QUERY, headers=HEADERS)
        dict_response = response.json()
        return True if dict_response['data']['user'] else False
    
    
    if __name__ == '__main__':
        USERS = ['forsen', 'offineandy', 'dyrus']
        for user in USERS:
            IS_LIVE = isLive(user)
            print(f'User {user} live: {IS_LIVE}')
    
    0 讨论(0)
  • 2021-02-04 19:38

    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!

    0 讨论(0)
  • 2021-02-04 19:38

    Yes. You can use Twitch API call https://api.twitch.tv/kraken/streams/YOUR_CHANNEL_NAME and parse result to check if it's live.

    The below function returns a streamID if the channel is live, else returns -1.

    import urllib2, json, sys
    TwitchChannel = 'A_Channel_Name'
    def IsTwitchLive(): # return the stream Id is streaming else returns -1
        url = str('https://api.twitch.tv/kraken/streams/'+TwitchChannel)
        streamID = -1
        respose = urllib2.urlopen(url)
        html = respose.read()
        data = json.loads(html)
        try:
           streamID = data['stream']['_id']
        except:
           streamID = -1
        return int(streamID)
    
    0 讨论(0)
  • 2021-02-04 19:40

    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
    
    0 讨论(0)
  • 2021-02-04 19:41

    I'll try to shoot my shot, just in case someone still needs an answer to this, so here it goes

    import requests
    import time
    from twitchAPI.twitch import Twitch
    
    client_id = ""
    client_secret = ""
    
    twitch = Twitch(client_id, client_secret)
    twitch.authenticate_app([])
    
    TWITCH_STREAM_API_ENDPOINT_V5 = "https://api.twitch.tv/kraken/streams/{}"
    
    API_HEADERS = {
        'Client-ID' : client_id,
        'Accept' : 'application/vnd.twitchtv.v5+json',
    }
    
    def checkUser(user): #returns true if online, false if not
        userid = twitch.get_users(logins=[user])['data'][0]['id']
        url = TWITCH_STREAM_API_ENDPOINT_V5.format(userid)
        try:
            req = requests.Session().get(url, headers=API_HEADERS)
            jsondata = req.json()
            if 'stream' in jsondata:
                if jsondata['stream'] is not None: 
                    return True
                else:
                    return False
        except Exception as e:
            print("Error checking user: ", e)
            return False
    
    print(checkUser('michaelreeves'))
    
    0 讨论(0)
提交回复
热议问题