【问题标题】:New Twitch API getting json data Python 3新的 Twitch API 获取 json 数据 Python 3
【发布时间】:2020-06-09 07:32:32
【问题描述】:

我正在尝试获取一个 python 脚本来说明一个 twitch 频道是否是实时的,但无法做到这一点,任何和所有的帮助将不胜感激。

这是我能找到的文档 https://dev.twitch.tv/docs/api/guide

这就是我的 atm,但我不断收到“'set' object has no attribute 'items'”。这是来自“Is There Any Way To Check if a Twitch Stream Is Live Using Python?”的修改代码,但是由于新的 API,它现在已经过时了。

import requests
def checkUser(): 
    API_HEADERS = {
        'Client-ID : [client id here from dev portal]',
        'Accept : application/vnd.twitchtv.v5+json',
    }

    url = "https://api.twitch.tv/helix/streams/[streamer here]"

    req = requests.Session().get(url, headers=API_HEADERS)
    jsondata = req.json()
    print(jsondata)

checkUser()

【问题讨论】:

  • api_headers 不是字典,它是一个包含 2 个字符串的集合

标签: python twitch-api


【解决方案1】:

“'set'对象没有属性'items'”问题的答案只是一个简单的错字。应该是

API_HEADERS = {
'Client-ID' : '[client id here from dev portal]',
'Accept' : 'application/vnd.twitchtv.v5+json'
}

注意冒号现在不是文本的一部分

要回答您关于如何判断频道是否在线的首要问题,您可以查看我制作的示例代码。

import requests

URL = 'https://api.twitch.tv/helix/streams?user_login=[Channel_Name_Here]'
authURL = 'https://id.twitch.tv/oauth2/token'
Client_ID = [Your_client_ID]
Secret  = [Your Client_Secret]

AutParams = {'client_id': Client_ID,
             'client_secret': Secret,
             'grant_type': 'client_credentials'
             }


def Check():
    AutCall = requests.post(url=authURL, params=AutParams) 
    access_token = AutCall.json()['access_token']

    head = {
    'Client-ID' : Client_ID,
    'Authorization' :  "Bearer " + access_token
    }

    r = requests.get(URL, headers = head).json()['data']

    if r:
        r = r[0]
        if r['type'] == 'live':
            return True
        else:
            return False
    else:
        return False

print(Check())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2016-05-09
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多