Twitch 观看人数接口返回 stream: null:离线、缺失还是 0 人?
整份响应里最容易写错的只有一行:"stream": null。
对频道 ninja 的探测里,三个直播状态接口都返回 HTTP 200、status 为 ok,data.user 的形状也完全一样。区别只在 message:
| 接口 | HTTP | status | message | data.user |
|---|---|---|---|---|
get-stream-details | 200 | ok | channel is currently offline | id、stream: null、__typename |
list-stream-tags | 200 | ok | null | 同上 |
get-stream-viewer-count | 200 | ok | null | 同上 |
三个调用字面上都成功了。只检查 HTTP 状态的代码会把这个 null 当成数据继续往下走:写进观看人数列变成 0,写进标签列变成“没有标签”。反过来,把 null 当错误的客户端,会为一个正常下播的频道半夜报警。下面只处理这个字段。
三个接口返回同一个 null,只有一个告诉你原因
接口说明对 stream: null 的解释有两层:频道没在播,或者请求那一刻没有可用的流数据。两种情形在 JSON 里长得一样,所以 null 本身不是“离线”的证据,只是“没拿到直播对象”。
message 也帮不上太多忙。只有 get-stream-details 会带上离线提示;另外两个接口离线时 message 是 null,你不能因为它是空的就推断“一切正常、正在直播”。三个接口共同可靠的只有一点:stream 是对象,才算有直播内容。
请求写法是 https://api.opendata-api.com/api/project/twitch-scraper/get-stream-viewer-count?key=YOUR_API_KEY&channel=ninja。密钥在控制台获取,只放在服务端,日志里不要留下带密钥的完整 URL。调用方不需要自己去 Twitch 开发者后台注册应用、申请 Client ID 或换取 token,所以 Helix 教程里常见的 401(token 过期)在这里不是同一个问题;如果你收到 401,先查密钥是否缺失、写错或被截断,并把这次读数记为“无法判断”,不要记成离线。
先确认频道存在,再去读 stream 字段
channel 参数要的是登录名,也就是 twitch.tv/ 后面那一段,不是显示名。显示名可以有大小写,甚至是中文,拿它去查,结果往往是拿不到用户,而这恰好会和“离线”混在一起。
确认身份用 get-channel-details:一次调用返回 id、login、displayName 和 followers.totalCount。把 id 和 login 存下来,就是这个频道存在的证明。每个频道只需要查一次,不必每轮轮询都查;每次请求都会消耗额度。
探测只试了存在的频道,没有取到“登录名不存在”时的响应,所以这里不替接口编造那种返回值。规则反过来定:读不到 data.user.id 一律算无法判断,绝不回退成离线。
把每次响应归入直播中、已离线、无法判断三类
| 条件 | 状态 | 观看人数列 |
|---|---|---|
HTTP 200,status 为 ok,data.user.id 存在,stream 是对象 | live | 读到整数就存整数,读不到存 NULL |
同上,但 stream 键存在且值为 null | offline | NULL |
其余全部:非 200、status 不是 ok、没有 data.user 或 id、根本没有 stream 键、类型出乎意料、超时 | unresolved | NULL |
这张表回答了“怎么判断主播是否正在直播”:stream 是对象,且前面的 HTTP、status、id 三关都过了,才是 live。
注意“键缺失”和“值为 null”是两件事。user 里有 stream: null 是接口明确说没有直播;user 里压根没有 stream 键,说明响应不是你预期的形状,属于 unresolved。
HTTP 200 加 status: ok 只说明请求被处理了,不说明有人在播;unresolved 既不进入均值,也不触发通知,等下一轮再读,不要在同一轮里连环重试。
因为 null 可能只是请求当时没有流数据,下播提醒不要靠一次 offline 触发。连续两次读到 offline、且之前是 live,再发通知,能挡掉大部分抖动。
探测时频道恰好离线,直播分支没有抓到,所以这里不写直播对象里人数那个键叫什么。第一次拿到直播中的响应时,自己看一眼再填进下面脚本的 VIEWER_PATH。
观看人数快照里写 NULL,不要写 0
假设一晚采样 8 次,3 次在播(1200、1500、900 人),5 次离线。离线写 0,平均值是 3600 / 8 = 450;离线写 NULL,平均值是 3600 / 3 = 1200。前者描述的是“这个时间窗口里平均有多少人在频道里”,后者才是“开播时的平均观众”,两个数字回答的是不同问题,而你的看板只会显示一个。
SQL 的 AVG 会跳过 NULL,所以把离线读数存成 NULL,聚合天然就是对的,不需要每个查询都记得加过滤。0 只留给一种情况:live 状态下接口明确报告了 0 人。
标签接口遵循同样的缺失规则
list-stream-tags 在离线时同样返回 stream: null。这表示当前没有可读的直播对象,不表示“这个主播没有标签”,所以不要写入空数组。标签字段的名称同样没有在离线探测里出现,第一次遇到直播中的频道时先存原始 JSON,再决定怎么拆。
标签会随直播变化,也不能证明几小时后频道仍在播。展示或统计时把读取时间和状态一起带上;离线那一行只记 offline,别拿上一场直播的标签补上去,否则看板会显示一个已经不存在的分类。
单次快照回答不了的问题
“Twitch 观看人数能查历史记录吗?”这几个接口给的都是请求那一刻的快照,没有历史时间序列。想要曲线,只能自己定时采样,并为每条记录保存读取时间;两次采样之间发生了什么,轮询间隔内无从知道。
也别把几个数字混用:当前观众数不等于频道的粉丝总数(followers.totalCount),更不等于往期视频的播放量。
要批量取剪辑和往期视频,用 list-channel-clips 和 list-channel-videos:它们按游标翻页,探测里每页 12 条,另有一个顶层的续页游标,下一次请求用 cursor 参数带上。它们是内容列表,不能拿来还原某场直播的观众数。
如需其他类似应用的 API,可通过联系页面提出需求,也可了解私有源代码部署。
把状态和数字一起记录的轮询脚本
下面的脚本把前面几条规则放在一起:启动时对每个频道确认一次 id,之后每轮每个频道只调一个接口,每一行都带状态列,观看人数在非直播时是 NULL。打开文章或复制代码不会请求数据接口,只有你手动运行脚本才会。
import json
import os
import sqlite3
import time
from datetime import datetime, timezone
import requests
BASE = "https://api.opendata-api.com/api/project/twitch-scraper"
API_KEY = os.environ["TWITCH_API_KEY"] # keep the key on the server side
CHANNELS = ["ninja"] # logins from the channel URL, not display names
POLL_SECONDS = 300
# Fill this after you inspect the first live response; the offline probe never showed it.
# Example shape: ("viewersKey",) or ("outer", "inner") under data.user.stream
VIEWER_PATH = ()
db = sqlite3.connect("twitch_snapshots.db")
db.execute(
"""CREATE TABLE IF NOT EXISTS snapshots (
ts TEXT NOT NULL, login TEXT NOT NULL, user_id TEXT, state TEXT NOT NULL,
viewers INTEGER, http_status INTEGER, message TEXT, raw_stream TEXT)"""
)
def call(op, channel):
try:
r = requests.get(f"{BASE}/{op}", params={"key": API_KEY, "channel": channel}, timeout=20)
except requests.RequestException as exc:
# Log the class only: the exception text can include the URL and the key.
return None, None, type(exc).__name__
try:
return r.status_code, r.json(), None
except ValueError:
return r.status_code, None, "invalid json"
def dig(obj, path):
for key in path:
if not isinstance(obj, dict) or key not in obj:
return None
obj = obj[key]
return obj if isinstance(obj, int) and not isinstance(obj, bool) else None
def classify(code, body):
"""Return (state, user_id, viewers, raw_stream) for one stream response."""
if code != 200 or not isinstance(body, dict) or body.get("status") != "ok":
return "unresolved", None, None, None
data = body.get("data")
user = data.get("user") if isinstance(data, dict) else None
if not isinstance(user, dict) or not user.get("id") or "stream" not in user:
return "unresolved", None, None, None
stream = user["stream"]
if stream is None:
return "offline", str(user["id"]), None, None
if isinstance(stream, dict):
raw = json.dumps(stream, ensure_ascii=False)
return "live", str(user["id"]), dig(stream, VIEWER_PATH), raw
return "unresolved", str(user["id"]), None, None
def resolve(login):
"""Existence proof: get-channel-details must return a matching login and an id."""
code, body, _ = call("get-channel-details", login)
data = body.get("data") if isinstance(body, dict) else None
user = data.get("user") if isinstance(data, dict) else None
ok = code == 200 and isinstance(body, dict) and body.get("status") == "ok"
if ok and isinstance(user, dict) and user.get("id") and str(user.get("login", "")).lower() == login.lower():
return str(user["id"])
return None
def went_offline(login):
# live -> offline -> offline, read newest first; one offline reading is not enough
states = [r[0] for r in db.execute(
"SELECT state FROM snapshots WHERE login=? ORDER BY ts DESC LIMIT 3", (login,))]
return states[:2] == ["offline", "offline"] and states[2:] == ["live"]
def record(login, user_id, state, viewers, code, message, raw):
ts = datetime.now(timezone.utc).isoformat(timespec="seconds")
db.execute("INSERT INTO snapshots VALUES (?,?,?,?,?,?,?,?)",
(ts, login, user_id, state, viewers, code, message, raw))
db.commit()
ids = {}
while True:
for login in CHANNELS:
if login not in ids:
found = resolve(login)
if found is None:
record(login, None, "unresolved", None, None, "channel not confirmed", None)
continue
ids[login] = found
code, body, err = call("get-stream-viewer-count", login)
state, uid, viewers, raw = classify(code, body)
message = err or (body.get("message") if isinstance(body, dict) else None)
record(login, uid or ids[login], state, viewers, code, message, raw)
if went_offline(login):
print(f"{login}: two offline readings after a live one")
time.sleep(POLL_SECONDS)
跑起来之后先看分布,再看数字:
SELECT state, COUNT(*), AVG(viewers) FROM snapshots WHERE login = 'ninja' GROUP BY state;
unresolved 比例偏高,说明问题在密钥、登录名或网络,不在主播;live 行的 viewers 为 NULL,说明 VIEWER_PATH 还没填对,raw_stream 列里的原始 JSON 就是你对照的地方。另外,拼错的登录名每轮都会重新确认一次,表里反复出现 channel not confirmed 时,应当去改配置,而不是继续等。