You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twitch直播录制代码异常:主播在线却提示离线求助

Twitch自动录制脚本无法检测直播问题排查

问题描述

尝试编写Python脚本实现Twitch主播pobr4tski开播时自动录制,代码如下:

import subprocess
import time
import os
import json

streamer_name = "pobr4tski"
quality = "best"
save_folder = "C:/Users/letha/twitch"

if not os.path.exists(save_folder):
    os.mkdir(save_folder)

while True:
    try:
        channels = subprocess.check_output(["streamlink", "--json", f"https://www.twitch.tv/{streamer_name}", quality])
        stream_data = json.loads(channels.decode("utf-8"))
        stream_url = stream_data["streams"][quality]["url"]
        file_name = f"{streamer_name} - {time.strftime('%Y-%m-%d %H-%M-%S')}.mp4" # Create a file name with the current date and time
        file_path = os.path.join(save_folder, file_name)
        print("Stream is live, starting recording...")
        subprocess.call(["streamlink", stream_url, quality, "-o", file_path])
    except:
        print("Stream is offline, checking again in 60 seconds...")
        time.sleep(60)

但主播直播时,脚本始终输出Stream is offline, checking again in 60 seconds...,已重装Python并安装所有依赖,问题仍未解决。

解决方案

1. 先通过命令行验证Streamlink可用性

直接在终端运行以下命令,测试Streamlink是否能正常获取主播的流:

streamlink https://www.twitch.tv/pobr4tski best
  • 如果命令执行失败,说明问题出在Streamlink本身,而非Python脚本;
  • 运行streamlink --version检查版本,确保是最新版,旧版本可能无法兼容Twitch的API更新。

2. 捕获具体异常,定位错误原因

原代码使用裸except:会掩盖所有错误类型,无法定位问题。修改为捕获具体异常,输出详细错误信息:

while True:
    try:
        channels = subprocess.check_output(["streamlink", "--json", f"https://www.twitch.tv/{streamer_name}", quality])
        stream_data = json.loads(channels.decode("utf-8"))
        stream_url = stream_data["streams"][quality]["url"]
        file_name = f"{streamer_name} - {time.strftime('%Y-%m-%d %H-%M-%S')}.mp4"
        file_path = os.path.join(save_folder, file_name)
        print("Stream is live, starting recording...")
        subprocess.call(["streamlink", stream_url, quality, "-o", file_path])
    except subprocess.CalledProcessError as e:
        print(f"Streamlink命令执行失败: {e}")
        time.sleep(60)
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
        time.sleep(60)
    except KeyError as e:
        print(f"找不到指定画质的流: {e}")
        time.sleep(60)
    except Exception as e:
        print(f"未知错误: {e}")
        time.sleep(60)

运行修改后的脚本,根据输出的错误信息针对性解决(比如命令执行失败可能是权限、网络问题,KeyError可能是best画质不存在)。

3. 简化脚本逻辑,避免冗余步骤

原脚本先获取JSON再提取URL,再调用Streamlink录制,步骤冗余。可以直接让Streamlink处理直播检测和录制,简化代码:

import subprocess
import time
import os

streamer_name = "pobr4tski"
quality = "best"
save_folder = "C:/Users/letha/twitch"

if not os.path.exists(save_folder):
    os.mkdir(save_folder)

while True:
    try:
        file_name = f"{streamer_name} - {time.strftime('%Y-%m-%d %H-%M-%S')}.mp4"
        file_path = os.path.join(save_folder, file_name)
        print("Checking stream status...")
        # 直接调用Streamlink录制,主播离线时会触发CalledProcessError
        subprocess.check_call(["streamlink", f"https://www.twitch.tv/{streamer_name}", quality, "-o", file_path])
    except subprocess.CalledProcessError:
        print("Stream is offline, checking again in 60 seconds...")
        time.sleep(60)

这种方式更可靠,减少中间环节出错的概率。

4. 排查网络与地区限制

  • 部分Twitch直播有地区限制,尝试切换到主播所在地区的网络(如VPN)后,再测试命令行的Streamlink;
  • 检查本地网络是否能正常访问Twitch官网,排除DNS污染或网络拦截的可能。

5. 确认主播用户名正确性

确保streamer_name与Twitch页面上的用户名完全一致(Streamlink对大小写不敏感,但需避免拼写错误)。

内容的提问来源于stack exchange,提问作者Bektur Asanbekov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:35:47