<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>stream &#8211; Blog von Draven</title>
	<atom:link href="https://draven.dravennet.de/tag/stream/feed/" rel="self" type="application/rss+xml" />
	<link>https://draven.dravennet.de</link>
	<description>Ein Blog, wie Tausend andere auch.</description>
	<lastBuildDate>Sun, 07 Jun 2020 21:43:27 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Twitch Recoder with New Api</title>
		<link>https://draven.dravennet.de/2020/06/twitch-recoder-with-new-api/</link>
		
		<dc:creator><![CDATA[Draven]]></dc:creator>
		<pubDate>Sun, 07 Jun 2020 21:43:27 +0000</pubDate>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[helix]]></category>
		<category><![CDATA[record]]></category>
		<category><![CDATA[save]]></category>
		<category><![CDATA[stream]]></category>
		<category><![CDATA[twtich]]></category>
		<guid isPermaLink="false">https://draven.dravennet.de/?p=815</guid>

					<description><![CDATA[Da Twitch seine API aktualisiert bzw. jetzt die alte API abgeschaltet hat musste im selben Zug auch mein Twitch Recorder Script angepasst werden. Das Original Script stammt von  junian https://gist.github.com/junian/b41dd8e544bf0e3980c971b0d015f5f6 Nach meinen Anpassung funktioniert das Script wieder, aber es gibt &#8230; <a href="https://draven.dravennet.de/2020/06/twitch-recoder-with-new-api/">Weiterlesen <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Da Twitch seine API aktualisiert bzw. jetzt die alte API abgeschaltet hat musste im selben Zug auch mein Twitch Recorder Script angepasst werden.</p>



<p>Das Original Script stammt von  <a href="https://gist.github.com/junian">junian</a> <a href="https://gist.github.com/junian/b41dd8e544bf0e3980c971b0d015f5f6">https://gist.github.com/junian/b41dd8e544bf0e3980c971b0d015f5f6</a></p>



<p>Nach meinen Anpassung funktioniert das Script wieder, aber es gibt auch schon einen Fork vom Original was ebenfalls auf die neue API setzt.</p>



<pre class="wp-block-code"><code># This code is based on tutorial by slicktechies modified as needed to use oauth token from Twitch.
# You can read more details at: https://www.junian.net/2017/01/how-to-record-twitch-streams.html
# original code is from https://slicktechies.com/how-to-watchrecord-twitch-streams-using-livestreamer/

import requests
import os
import time
import json
import sys
import subprocess
import datetime
import getopt

class TwitchRecorder:
    def __init__(self):
        # global configuration
        self.client_id = "" # insert your own Client-ID
        # get oauth token value by typing `streamlink --twitch-oauth-authenticate` in terminal
        self.oauth_token = ""
        self.ffmpeg_path = 'ffmpeg'
        self.refresh = 15.0
        self.root_path = "" # folder for saving files
        
        # user configuration
        self.username = "" # insert streamer 
        self.quality = "best"

    def run(self):
        # path to recorded stream
        self.recorded_path = os.path.join(self.root_path, "recorded", self.username)

        # path to finished video, errors removed
        self.processed_path = os.path.join(self.root_path, "processed", self.username)

        # create directory for recordedPath and processedPath if not exist
        if(os.path.isdir(self.recorded_path) is False):
            os.makedirs(self.recorded_path)
        if(os.path.isdir(self.processed_path) is False):
            os.makedirs(self.processed_path)

        # make sure the interval to check user availability is not less than 15 seconds
        if(self.refresh &lt; 15):
            print("Check interval should not be lower than 15 seconds.")
            self.refresh = 15
            print("System set check interval to 15 seconds.")
        
        # fix videos from previous recording session
        try:
            video_list = &#91;f for f in os.listdir(self.recorded_path) if os.path.isfile(os.path.join(self.recorded_path, f))]
            if(len(video_list) > 0):
                print('Fixing previously recorded files.')
            for f in video_list:
                recorded_filename = os.path.join(self.recorded_path, f)
                print('Fixing ' + recorded_filename + '.')
                try:
                    subprocess.call(&#91;self.ffmpeg_path, '-err_detect', 'ignore_err', '-i', recorded_filename, '-c', 'copy', os.path.join(self.processed_path,f)])
                    os.remove(recorded_filename)
                except Exception as e:
                    print(e)
        except Exception as e:
            print(e)

        print("Checking for", self.username, "every", self.refresh, "seconds. Record with", self.quality, "quality.")
        self.loopcheck()

    def check_user(self):
        # 0: online, 
        # 1: offline, 
        # 2: not found, 
        # 3: error
        headers = {
              'Authorization' : 'Bearer ' + self.oauth_token,
              'Client-ID' : self.client_id
              }
        
        url = 'https://api.twitch.tv/helix/streams?user_login=' + self.username
        info = None
        status = 3
        try:
            r = requests.get(url, headers = headers, timeout = 15)
            r.raise_for_status()
            info = r.json()
            if 'type' in str(info):
             status = 0
            else:
             status = 1 
        except requests.exceptions.RequestException as e:
            if e.response:
                if e.response.reason == 'Not Found' or e.response.reason == 'Unprocessable Entity':
                    status = 2

        return status, info

    def loopcheck(self):
        while True:
            status, info = self.check_user()
            if status == 2:
                print("Username not found. Invalid username or typo.")
                time.sleep(self.refresh)
            elif status == 3:
                print(datetime.datetime.now().strftime("%Hh%Mm%Ss")," ","unexpected error. will try again in 5 minutes.")
                time.sleep(300)
            elif status == 1:
                print(self.username, "currently offline, checking again in", self.refresh, "seconds.")
                time.sleep(self.refresh)
            elif status == 0:
                print(self.username, "online. Stream recording in session.")
                filename = self.username + " - " + datetime.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss") + " - " + info&#91;'data']&#91;0]&#91;'title'] + ".mp4"
                
                # clean filename from unecessary characters
                filename = "".join(x for x in filename if x.isalnum() or x in &#91;" ", "-", "_", "."])
                
                recorded_filename = os.path.join(self.recorded_path, filename)
                
                # start streamlink process
                subprocess.call(&#91;"streamlink", "--twitch-oauth-token", self.oauth_token, "twitch.tv/" + self.username, self.quality, "-o", recorded_filename])

                print("Recording stream is done. Fixing video file.")
                if(os.path.exists(recorded_filename) is True):
                    try:
                        subprocess.call(&#91;self.ffmpeg_path, '-err_detect', 'ignore_err', '-i', recorded_filename, '-c', 'copy', os.path.join(self.processed_path, filename)])
                        os.remove(recorded_filename)
                    except Exception as e:
                        print(e)
                else:
                    print("Skip fixing. File not found.")
                    
                print("Fixing is done. Going back to checking..")
                time.sleep(self.refresh)

def main(argv):
    twitch_recorder = TwitchRecorder()
    usage_message = 'twitch-recorder.py -u &lt;username> -q &lt;quality>'

    try:
        opts, args = getopt.getopt(argv,"hu:q:",&#91;"username=","quality="])
    except getopt.GetoptError:
        print (usage_message)
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(usage_message)
            sys.exit()
        elif opt in ("-u", "--username"):
            twitch_recorder.username = arg
        elif opt in ("-q", "--quality"):
            twitch_recorder.quality = arg

    twitch_recorder.run()

if __name__ == "__main__":
    main(sys.argv&#91;1:])</code></pre>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
