Skip to content

Instantly share code, notes, and snippets.

@squaresmile
Last active October 3, 2021 15:34
Show Gist options
  • Save squaresmile/7395dec4cbcaec55b939464f9e2d8df2 to your computer and use it in GitHub Desktop.
Save squaresmile/7395dec4cbcaec55b939464f9e2d8df2 to your computer and use it in GitHub Desktop.
Script and systemd service to record twitch stream automatically
[Unit]
Description=Save Twitch stream
After=network.target
[Service]
WorkingDirectory=/home/squaresmile/twitch_streams
ExecStart=/bin/bash /home/squaresmile/twitch_streams/save_stream.sh
User=cereal
[Install]
WantedBy=multi-user.target
#!/usr/bin/env bash
set -e
if [[ $(find . -name "*_.mp4" -printf '.' | wc -m) -ne "0" ]]; then
exit 1
fi
STREAM=$(date +"%Y_%m_%d_%H_%M_%S")
echo "Saving stream $STREAM"
streamlink https://www.twitch.tv/<twitch_username> -o "$STREAM"_.mp4 --twitch-disable-hosting \
--twitch-disable-ads --twitch-disable-reruns --retry-streams 60 --retry-max 5 || true
if [ -f "$STREAM"_.mp4 ]; then
# Some players (Chrome) can't play the original mp4 file from streamlink (probably because when the stream ends, strealink doesn't finish writing cleanly)
# so we remux the file
ffmpeg -i "$STREAM"_.mp4 -c: copy "$STREAM".mp4
rm "$STREAM"_.mp4
# Uncomment if you want to send a pushbullet notification on finish
# curl -u <pushbullet_api_token>: https://api.pushbullet.com/v2/pushes -d type=note --data-urlencode title="$STREAM stream finished"
fi
[Unit]
Description=Check and save stream
[Timer]
OnCalendar=*-*-* *:00/15:00
RandomizedDelaySec=60
AccuracySec=1us
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment