0

我正在寻找一种解决方案,可以在直播/离线时自动切换 OBS 中的场景。我从较早的问题中找到了此代码,但它对我不起作用。它只返回“无”。坦克!

import requests

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

API_HEADERS = {
    'Client-ID' : 'myID',
    '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"))

4

1 回答 1

0

这是一种更容易和更简单的方法,更容易调试:

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

# Call with is_live_stream("bikestreaming", your-client-id)

和以前一样,如果流媒体直播,则为 true,如果流媒体未直播,则为 false。带有 try catch 语句的代码很难调试。此链接解释了 twitch 客户端 ID:https ://dev.twitch.tv/docs#client-id

于 2021-03-07T11:43:39.707 回答