EASIEST Way to Download Twitch Clips Using Python

The Scraper Guy
4 min readAug 7, 2024

--

With the rise of short form content mainly TikTok and YT Shorts, how can we simplify the process of bulk downloading clips from multiple twitch channels?

Today I will show you an easy python script to automate this process!

To begin we will be relying heavily on the Twitch API for this project so, lets consult the API’s getting started guide linked below.

Create a twitch account if you dont have one already, then follow the guide to register an application and make sure to take note of your Client ID and Client Secret keys.

The next step is to check that you have successfully followed the guide and Get an OAuth token. Run the following command in your IDE (I am using Jupyter Notebooks). Simply replace {YOUR CLIENT ID} and {YOUR CLIENT SECRET} with the values gathered in the last step.

bearerUrl = "https://id.twitch.tv/oauth2/token"
data = 'client_id={YOUR CLIENT ID}&client_secret={YOUR CLIENT SECRET}&grant_type=client_credentials'
headers = {
"accept": "application/json"
}
requestBearerToken = requests.post(bearerUrl, data=data, headers=headers)
requestBearerToken = requestBearerToken.json()
bearerToken = requestBearerToken['access_token']

I am unsure after how long the OAuth token expires so each time I am interacting with the Twitch API i create a new token. Copy the value that is returned. You can also wrap this code into a function so that it can be called easily.

Following on from this we need to gather the unique Twitch ID’s for the channels we need to download the clips from. Gather all the twitch usernames of the channels you want to download clips from, for example -

nmplol,kaicenat,xqc

Run the following code for each username replacing {USERNAME} with the Username you have copied add your client id and client secret keys and pass the bearer Token from the previous step into {YOUR BEARER TOKEN} and then print the response. Copy the id field in the response, into notepad as well as the corresponding username.

url = "https://api.twitch.tv/helix/users?login={USERNAME}"
data = 'client_id={YOUR CLIENT ID}&client_secret={YOUR CLIENT SECRET}&grant_type=client_credentials'
headers = {
"accept": "application/json",
"Authorization": "Bearer {YOUR BEARER TOKEN}",#
"Client-Id": "{YOUR CLIENT ID}"
}
request = requests.get(url, data=data, headers=headers)
request = request.json()
request

Create a dictionary with all usernames as the keys and ids as the values

streamerIDs = {"silky":"451786566","lacy" : "494543675","stableronaldo":"246450563","plaqueboymax":"672238954",
"jasontheween":"107117952","kaysan":"516862428","thesketchreal":"917774995"}

Create a new function that returns Today's Date as shown below

from datetime import date
def getTodaysDate():
today = date.today()
d1 = today.strftime("%Y-%m-%d")
d1 = d1 + "T00:00:00Z"
return d1

We will then create a new function called getClipsFromStreamer which takes the streamerID, bearerToken and todaysDate as inputs and returns clips from today. Using f before a string allows you to pass in variables using {variable}

def getClipsFromStreamer(streamerID,bearerToken,todaysDate):
url = f"https://api.twitch.tv/helix/clips?broadcaster_id={streamerID}&started_at={todaysDate}"
data = 'client_id={YOUR CLIENT ID}&client_secret={YOUR CLIENT SECRET}&grant_type=client_credentials'
headers = {
"accept": "application/json",
"Authorization": f"Bearer {bearerToken}",
"Client-Id": "{YOUR CLIENT ID}"
}
request = requests.get(url, data=data, headers=headers)
request = request.json()
return request

The response should look like this

Next we will create a function that actually downloads the clips called downloadClip() which takes the clip url, streamer name and name of clip as inputs and creates a new folder called Todays Date if not already created and downloads a single clip to this folder. The method by which it does this is using the thumbnail_url field from the previous response.

If you replace from -preview to the end of the url with simply .mp4, this will download the clip in an mp4 format. Enter the path where you wish to download the clips, example “C:/User/Desktop/Clips….”

def downloadClip(clip,streamer,clip_name):
todaysDate = str(datetime.today().strftime('%Y%m%d'))
path = f"{PATH}/{streamer}/{todaysDate}/"
index = clip.find('-preview')
clip_url = clip[:index] + '.mp4'
print(clip_url)
r = requests.get(clip_url,stream=True)

if not os.path.exists(path): os.makedirs(path)
directory = path + clip_name
with open(directory, 'wb') as f:
f.write(r.content)

So here we simply replace from -preview with .mp4 and download the clip to the new directory created on your machine.

Given that we probably do not want to download just one clip we can download the top 5 clips created today using the below code.

def getTop5Clips(streamerID,bearerToken,todaysDate,streamerName):
clips = getClipsFromStreamer(streamerID,bearerToken,todaysDate)
first_5_items = list(clips['data'])[:5]
newList = list(first_5_items)
j = 1
for i in newList:
try:
clipName = str(j) + ".mp4"
downloadClip(i['thumbnail_url'],streamerName,clipName)
j = j + 1
print(f"Downloaded Clips for {streamer} on {todaysDate}")
except:
print(f"Issue with downloading clips for {streamer} on {todaysDate}")
continue

This function simply converts the response from getClipsFromStreamer into a list with just the first 5 clips for each streamer, which will be sorted by view_count today, otherwise you can sort whichever way you want or increase the number of clips you wish to download.

We also create a clip name with just a simple incremented value j and print if the clips is downloaded successfully.

Putting all of this together we can run

streamerIDs = {"silky":"451786566","lacy" : "494543675","stableronaldo":"246450563","plaqueboymax":"672238954",
"jasontheween":"107117952","kaysan":"516862428","thesketchreal":"917774995"}
bearerToken = getBearerToken()
todaysDate = getTodaysDate()
for key, value in streamerIDs.items():
getTop5Clips(value,bearerToken,todaysDate,key)

This code will iterate through the streamerIDs dictionary and download the top 5 clips for each streamer in the dictionary.

Tomorrow we will use the Twitch API and Supabase as a DB layer to check and store whether a streamer is live or not!

Thanks for reading, that is it for today's article, as always if you enjoyed consider leaving a clap and following for more.

Follow me on Twitter — https://x.com/PaulConish

--

--

The Scraper Guy
The Scraper Guy

Written by The Scraper Guy

Teaching You How to Scrape Using Python LinkTree - https://linktr.ee/scrapingguy

No responses yet