这是一个示例,您需要提供自己的 ClientID 和 Secret 以及要查找的 stream_name。您可以在https://dev.twitch.tv/console/apps注册 CID
此示例每次都会生成一个客户端凭据令牌,这是不好的做法。您应该(通常)生成并存储然后重用令牌直到它过期。
它生成一个令牌,然后调用流 API 来查找实时状态
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');