Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
script to download past broadcasts from
import requests
import sys
import json
import re
import os
import string
import argparse
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
done += CS
sys.stdout.write("\r{0:>7.2f} MB".format(done/float(pow(1024,2))))
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))
j = r.json()
except ValueError as e:
print("API did not return valid JSON: {}".format(e))
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()
Copy link

Kieldro commented Jun 24, 2014

Awesome script, thanks so much.

Copy link

norova commented Oct 29, 2014

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.

Copy link

LordH3lmchen commented Nov 8, 2014

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)

Copy link

Hilal-Ahmad commented May 31, 2021

where to put stream id in the code?

Copy link

baderj commented May 31, 2021

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