Twitch recorder

232 Views Asked by At

I'm trying to write code in PyCharm to record stream when my favorite twitch streamer is broadcasting, using this code:

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)

but I have only output Stream is offline, checking again in 60 seconds..., even if he is online and broadcasting a broadcast, thank you in advance

I have uninstall python and download it again with all needed pip's, but it's didn't change my situation

1

There are 1 best solutions below

2
Raphael On

I think you can omit some of the code, since streamlink automatically pulls the correct stream url. https://streamlink.github.io/cli.html

while True:
    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)
    subprocess.call(["streamlink", f"https://www.twitch.tv/{streamer_name}", quality, "-o", file_path])
    print("Stream is live, starting recording...")
except Exception as e:
    print("Stream is offline, checking again in 60 seconds...")
    time.sleep(60)

I tested this on my machine and it seems to work if the streamer is online. Didn't test it if they are offline.