How to Record Twitch Streams Automatically in Python
Using the power of streamlink and ffmpeg, twitch stream can be recorded every time user goes online
Let’s say you like to watch people playing game. Or maybe you like to study a game strategy from someone else. Or maybe you just find a player funny while playing a game. Of course you’re going to search those videos on Internet. Some videos are streamable at any time, like YouTube videos, but some are just live stream with a certain schedule, like Twitch.
If it’s streamable anytime, it’s not a problem because we can watch it anytime we want. But what if it’s a live stream and you’re busy, or at work, or at other place that make you can’t watch video right at the time. By the time you’re home and plan to watch the video, it probably has ended.
Because you’re reading this post right now, I assume you like to watch Twitch streams. Luckily, if you’re busy and don’t have time to follow your favorite Twitch streamers, there is a way to record those live streams anytime you want even 24/7.
This method requires you to understand command line though. Because we’re going to use two awesome command line tools: streamlink
and ffmpeg
. Also, if possible, you need understand Python 3.x
programming too, even though it’s not important because you can just copy and paste the code here. But I’ll also give some explanations for every code I write here in case you’re trying understand how it works.
Update! Seems like
livestreamer
isn’t active project anymore. But luckily there is an active project forked from it calledstreamlink
. Just replace everylivestreamer
in the code withstreamlink
and it should work just fine. This tutorial code is updated withstreamlink
.
Installation
First thing first, let’s install our command line tools. I’m using macOS Sierra to do the job, but it can also works for Windows and some Linux Distro. Assuming you already have Python 3.x
installed on your system (if not then just go ahead to python website), we’re going to install streamlink
first using pip
by typing this command:
streamlink
will be used to record active live stream from Twitch. After the live streaming session ended, we’re going to need a post processing tool for produced videos, because some errors could be happened when on recording session. For that we’re going to use ffmpeg
. We can install ffmpeg
on macOS by using Homebrew by typing this command:
If you’re on windows, you can download zeranoe builds here and extract it wherever you want, but I suggest to place it in C:\
.
After all required tools installed, it’s time for python scripting.
Please note that the code below was modified from slicktechies. The original code doesn’t work anymore because livestreamer
(or in this case streamlink
) needs oauth token to work. That is why I make this tutorial and make the original code better. To see the original code, see references below.
Configuration
Write following code at the beginning of your script. This code will import every library we need to make the code works. Let’s for now name our file twitch-recorder.py
.
Before we start the core programming, we’re going to need some configuration variables. For that we’re going to create a new class called TwitchRecorder
. In this class constructor, some configuration variables are defined. Here I’ll explain one by one what we’re creating.
self.client_id
is a value for Client-ID
header needed to access Twitch API. So how can the value jzkbprff40iqj646a697cyrvl0zt2m6
? Well, it turns out people on livestreamer issues found the default Client-ID
for Twitch website itself. So we’re going to use that to make it simple.
self.oauth_token
is a value for streamlink needed to access Twitch video. You need to have a Twitch account to use this. This token is received by typing this command from command line:
After the command executed, you need to accept / allow Twitch for authentication. Then the browser will redirect you to something like this url:
Now see the url parameter with format access_token=thisisyourtokenvalue
. That’s your token value. Now you need to replace xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
with your token thisisyourtokenvalue
to make it works.
You can leave self.ffmpeg_path
as it is if you’re on macOS or Linux. But in case you installed ffmpeg
on different location, for example when you’re on Windows, you can change self.ffmpeg_path
to your ffmpeg
binary path like this:
Next thing to understand is self.refresh
. We use this variable for interval of checking user status, whether it’s currently live streaming or not. It is recommended to set this value not less than 15 seconds because it is not good to access Twitch API if the interval is too low.
Use self.root_path
to set saved videos. This can be anything as long as you have permission to access that directory. No need to create directory manually because the code will create it automatically.
The last two variables are used to set Twitch username you wish to record and the quality of recording. Both self.username
and self.quality
can be set via command line argument. So you don’t have to change it in the code.
Check for user availability status
Next step is to make a function that can check user status. This step requires us to consume Twitch kraken API. The API endpoint we’re going to use is this:
To access this API, we also going to use self.client_id
as request header. This API will send us back with a json-formatted value. Here is an example of json result after consuming that API when the user is not live streaming right now:
After receiving the json value, we’re going to set the status into 4 categories. If the user is online and streaming right at the time, we set status = 0
. If the user is offline, we set status = 1
. If the user doesn’t exist (in case of typo or something), we set status = 2
. For unknown error, we set status = 3
.
We’re going to return user status and json data if exists. This function is still under class TwitchRecorder
Here is the complete function to check Twitch user status:
Routine to record live stream video when user is online
Still under class TwitchRecorder
, we’re going to write a loop to check user status.
If user is online, we call streamlink
subprocess using subprocess.call()
function. After recording is finished, we cleanup the video from any possible errors (usually some error frames caused by bad connection) using subprocess.call()
of ffmpeg
. After that, repeat to check user status again.
If the user is offline or not found, we just write a message on screen, then sleep and check user status again.
This routine would be executed in infinite of time, unless something wrong with your machine or you press ctrl + c from your keyboard.
Here is the complete function for this loop:
Combine them all together
Still in class TwitchRecorder
, we now need to define a main function to run them all. But before we run loopcheck()
, we’re going to make sure some variables and directories are created.
We need to define and create 2 separates folder: self.recorded_path
and self.processed_path
. Recorded path is path where streamlink
will save its videos. After recording is complete, ffmpeg
will fix the video, put it to processed directory, and delete the old file.
Also, before starting loopcheck
, we’re going to need fix all previous recorded videos in case user terminate the process so those last videos won’t left behind.
Here is the complete function for this part:
Accepting command line arguments
Now that we already have all the functions needed, we just need to create an object from TwitchRecorder
class and call run()
. But before that, I believe it’s better to add one more feature.
So imagine if you’d like to record 2 or more users at the same time. It’s ineffective if you had to duplicate the script and change its username for every user. That is why we’re going to add to set username via command line parameter. So we’re going to make it so we can run it to something like this:
To do something like that, we’re going to user getopt
. This is used to easily read command line arguments. Once we create a TwitchRecorder
object (let’s name it twitch_recorder
), we can set its username and quality from command line argument. This way, you can record multiple users at the same time without duplicating this code.
Here is the complete code looks like:
Running the script
After step above finished, now you can run this script by typing something like this in terminal:
To record another user, you can type the similar command inside new terminal session or window (or you can use something like tmux
).
Summary
That’s the simple way to record live stream from Twitch. Please note that this script probably won’t work if your computer in sleep mode or your hard drive is full. Use this code at your own risk, I don’t understand the legality to record a live streaming in your country.
To download the complete code, you can get it from this gist.
If you find anything wrong, feel free to write in comments below.
References
- How to Automatically Record Twitch Streams with a Script
- How to Watch/Record Twitch Streams using Livestreamer
- Overview — Livestreamer 1.12.2 documentation
- h.264 - Fix bad files and streams with ffmpeg so VLC and other players would not crash - Video Production Stack Exchange
- CLI for extracting streams from various websites to a video player of your choosing | GitHub - streamlink/streamlink