Last active
March 5, 2023 21:43
-
-
Save baderj/8340312 to your computer and use it in GitHub Desktop.
script to download past broadcasts from twitch.tv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import sys | |
import json | |
import re | |
import os | |
import string | |
import argparse | |
BASE_URL = 'https://api.twitch.tv' | |
def download_file(url, local_filename): | |
print("downloading {0}".format(local_filename)) | |
CS = 1024 | |
done = 0 | |
r = requests.get(url, stream=True) | |
with open(local_filename, 'wb') as f: | |
for chunk in r.iter_content(chunk_size=CS): | |
if not chunk: # filter out keep-alive new chunks | |
continue | |
f.write(chunk) | |
f.flush() | |
done += CS | |
sys.stdout.write("\r{0:>7.2f} MB".format(done/float(pow(1024,2)))) | |
print("done\n") | |
def download_broadcast(id_): | |
""" download all video parts for broadcast 'id_' """ | |
pattern = '{base}/api/videos/a{id_}' | |
url = pattern.format(base=BASE_URL, id_=id_) | |
r = requests.get(url) | |
if r.status_code != 200: | |
raise Exception("API returned {0}".format(r.status_code)) | |
try: | |
j = r.json() | |
except ValueError as e: | |
print("API did not return valid JSON: {}".format(e)) | |
print("{}".format(r.text)) | |
quit() | |
qualities = j['chunks'] | |
res = [int(q[:-1]) for q in qualities if re.match("^\d+p", q)] | |
best_resolution = "{}p".format(max(res)) | |
for nr, chunk in enumerate(j['chunks'][best_resolution]): | |
video_url = chunk['url'] | |
ext = os.path.splitext(video_url)[1] | |
filename = "{0}_{1:0>2}{2}".format(id_, nr, ext) | |
download_file(video_url, filename) | |
if __name__=="__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument('video_id', help='twitch video id') | |
args = parser.parse_args() | |
download_broadcast(args.video_id) |
Thanks for the script, baderj
Updated the script to resolve errors with quality resolution. "live" seems to be the only 'quality' returned anymore. Also: added support for download directory creation, cleaned up a few sections, improved output of current download status, added content-type check to avoid downloading non-flash files.
Nice script,
I've also written a small script based on yours. I have connection issues with my Provider somtimes, so my script is able to resume downloads. I convert the Videos to mp4 after downloading. (requires ffmpeg)
where to put stream id in the code?
As the first command line argument. But the script probably wont work anymore.
Use youtube-dl instead, works perfectly
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome script, thanks so much.