9

我只是想知道是否有任何方法可以编写 python 脚本来检查 twitch.tv 流是否直播?

我不确定为什么我的应用引擎标签被删除,但这将使用应用引擎。

4

11 回答 11

8

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
于 2020-02-05T12:14:51.740 回答
6

RocketDonkey 的好答案现在似乎已经过时了,所以我为像我这样偶然发现谷歌这个 SO-question 的人发布了一个更新的答案。您可以通过解析检查用户EXAMPLEUSER的状态

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

条目 "stream":null 将告诉您该用户是否离线,如果该用户存在。这是一个可以在命令行上使用的小型 Python 脚本,它将为在线用户打印 0,为离线用户打印 1,为未找到用户打印 2。

#!/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
于 2014-05-13T01:42:41.537 回答
5

看起来 Twitch 提供了一个 API(此处的文档),它提供了一种获取该信息的方法。获取提要的一个非常简单的示例是:

import urllib2

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

print contents.read()

这将转储所有信息,然后您可以使用JSON 库对其进行解析(XML 看起来也可用)。如果流不存在,看起来值返回空(根本没有测试这么多,我也没有读过任何东西:))。希望这可以帮助!

于 2012-08-21T22:57:09.053 回答
2

使用带有您的 client_id 作为参数的 twitch api,然后解析 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
于 2016-11-24T23:36:33.447 回答
2

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'))
于 2020-10-20T10:12:05.047 回答
2

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');
于 2021-03-08T20:02:09.947 回答
2

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')
于 2021-06-14T11:39:52.177 回答
1

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']['stream'] is not None else False


if __name__ == '__main__':
    USERS = ['forsen', 'offineandy', 'dyrus']
    for user in USERS:
        IS_LIVE = isLive(user)
        print(f'User {user} live: {IS_LIVE}')
于 2020-11-23T19:52:03.830 回答
0

是的。您可以使用 Twitch API 调用https://api.twitch.tv/kraken/streams/YOUR_CHANNEL_NAME和解析结果来检查它是否处于活动状态。

如果频道是实时的,则下面的函数返回一个streamID,否则返回-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)
于 2016-05-14T11:35:12.900 回答
0

https://dev.twitch.tv/docs/api/reference#get-streams

import requests
# ================================================================
# your twitch client id
client_id = '' 
# your twitch secret       
client_secret = ''
# twitch username you want to check if it is streaming online
twitch_user = ''                           
# ================================================================
#getting auth token
url = 'https://id.twitch.tv/oauth2/token'
params = {
    'client_id':client_id,
    'client_secret':client_secret,
    'grant_type':'client_credentials'}
req = requests.post(url=url,params=params)
token = req.json()['access_token']
print(f'{token=}')
# ================================================================
#getting user data (user id for example)
url = f'https://api.twitch.tv/helix/users?login={twitch_user}'
headers = {
    'Authorization':f'Bearer {token}',
    'Client-Id':f'{client_id}'}
req = requests.get(url=url,headers=headers)
userdata = req.json()
userid = userdata['data'][0]['id']
print(f'{userid=}')
# ================================================================
#getting stream info (by user id for example)
url = f'https://api.twitch.tv/helix/streams?user_id={userid}'
headers = {
    'Authorization':f'Bearer {token}',
    'Client-Id':f'{client_id}'}
req = requests.get(url=url,headers=headers)
streaminfo = req.json()
print(f'{streaminfo=}')
# ================================================================
于 2021-10-17T14:05:57.550 回答
0

Explanation

Now, the Twitch API v5 is deperecated. The helix API is in place, where a OAuth Authorization Bearer AND client-id is needed. All of the previous answers now don't function, so I created my own method. This is pretty annoying, so I went on a search for a viable workaround, and found one.

GraphQL

Once inspecting Twitch's network requests, I realized it used GraphQL. GraphQL is essentially a query language for APIs.

query($login: String) {
  user(login: $login) {
    stream {
      id
    }
  }
}

In the graphql query above, we are querying a user by their login name. If they are streaming, the stream's id will be given. If not, None will be returned.

The Final Code

The finished python code, in a function, is below. The client-id is taken from Twitch's website. Twitch uses the client-id, in the code below, to fetch information for anonymous users (people who aren't logged in). It will always work, without the need of getting your own client-id.

import requests
# ...
def checkIfUserIsStreaming(username):
  url = "https://gql.twitch.tv/gql"
  query = """query($login: String) {
  user(login: $login) {
    stream {
      id
    }
  }
}"""
  return True if requests.post(url, json={"query": query, "variables": {"login": username}}, headers={"client-id": "kimne78kx3ncx6brgo4mv6wki5h1ko"}).json()['data']['user']['stream'] else False
I've created a website where you can play with Twitch's GraphQL API. Refer to the GraphQL Docs for help on creating queries and mutations!
于 2022-02-27T23:44:17.600 回答