From 06aaed3d0fb470f22f11d26fbb88b4c54e240d41 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 00:06:08 +0000 Subject: [PATCH 01/32] =?UTF-8?q?=D0=A0=D0=B0=D0=B1=D0=BE=D1=87=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=BF=D1=80=D0=BE=D1=82=D0=BE=D1=82=D0=B8=D0=BF.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 daemon.py diff --git a/daemon.py b/daemon.py new file mode 100644 index 0000000..b9f5e19 --- /dev/null +++ b/daemon.py @@ -0,0 +1,52 @@ +#!/usr/bin/python3 + +# база со стримерами в json файле + +from threading import Thread +import json +import config_python + + +def startRecord(i): + ''' + Функция, которая запускает в отдельном потоке запись стрима - recorder(i) + ''' + th = Thread(target=recorder, args=(i, )) + th.start() + +def recorder(i): + ''' + Функция, которая запускает youtube-dl, фактически записывает стрим + ''' + print("Записываем стрим %s\n" % i) + # FIXME: пофиксить абсолютный путь + cmdline = ["/home/losted/.local/bin/youtube-dl","twitch.tv/"+i] + import subprocess + s = subprocess.call(cmdline) + print("Запись стрима %s закончена\n" % i) + +def checkAlive(streamers, client_id): + ''' + 1. Проверка на наличие стрима + 1.1 Если нет - удалить lock файл, если он есть + 1.2 Если есть - создать lock файл, запустить записывалку + ''' + + from twitch import TwitchClient + client = TwitchClient(client_id=client_id) + + for i in streamers: + # Если есть такой стример - проверяем, идет ли стрим + user_id=client.users.translate_usernames_to_ids(i)[0]['id'] #Получить ID по нику + # Это зачем проверка? + if client.streams.get_stream_by_user(user_id): + # Если стрим идет то записываем + if client.streams.get_stream_by_user(user_id).stream_type == 'live': + startRecord(i) + else: + print(i+" Не стримит") + + + +if __name__ == "__main__": + checkAlive(config_python.streamers, config_python.twitchid) From c8c902163b7a3fc010ce66f63af6ddb114e8e9ad Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 00:31:39 +0000 Subject: [PATCH 02/32] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D1=8F=D0=B5?= =?UTF-8?q?=D0=BC=20=D1=81=D1=82=D0=B0=D1=80=D0=BE=D0=B5=20=D0=B3=D0=BE?= =?UTF-8?q?=D0=B2=D0=BD=D0=BE=D0=BC=D0=B5=D1=81=D0=B8=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- check.sh | 27 --------------------------- cron.sh | 29 ----------------------------- lifeChk.py | 21 --------------------- 3 files changed, 77 deletions(-) delete mode 100755 check.sh delete mode 100755 cron.sh delete mode 100755 lifeChk.py diff --git a/check.sh b/check.sh deleted file mode 100755 index b81a624..0000000 --- a/check.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -########## -# check if stream is live and start recording using youtube-dl -########## - -full_path=$(dirname "$(realpath $0)") - -source $full_path/config_list.sh - - - -#check if not running, kill if running and stream is finished (broken record) -# [ -f $storage_path/$1/pid ] && $full_path/lifeChk.py $1 && exit 0 || kill -9 $(cat $storage_path/$1/pid) - -#if pid exists and stream is live, than exit and do not start recording -[ -f $storage_path/$1/pid ] && $full_path/lifeChk.py $1 $twitchid && exit 0 - -#exit if no stream and remove lock -$full_path/lifeChk.py $1 $twitchid || rm $storage_path/$1/pid ; exit 0 - -echo $$ > $storage_path/$1/pid - -#set pid and start recording -/home/losted/.local/bin/youtube-dl -v -o $storage_path/$1/"%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s" twitch.tv/$1 >> $storage_path/$1/youtube-dl.log 2>&1 - -# remove pid -rm $storage_path/$1/pid diff --git a/cron.sh b/cron.sh deleted file mode 100755 index b333ac5..0000000 --- a/cron.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -########## -# (actually main) script which cron (systemd.timer) starts by time -########## -full_path=$(dirname "$(realpath $0)") -source $full_path/config_list.sh - -for i in $list; do - echo "$i is live?..." - - #check folder - [ ! -d $storage_path/$i ] && mkdir -p $storage_path/$i && echo "Created dir $storage_path/$i" - - #detached check & start - nohup bash $full_path/check.sh $i &>> $storage_path/$1/youtube-dl.log & - sleep 2 - -done - -#Show status -echo -for i in $list; do - [[ -f $storage_path/$i/pid ]] && echo $i "is recording!" || echo $i "is not recording" -done -echo -echo "Removing old files (older than $ctime_remove days):" -find $storage_path/ -ctime +$ctime_remove -name "*mp4*" -find $storage_path/ -ctime +$ctime_remove -name "*mp4*" -exec rm {} \; -echo "Done" \ No newline at end of file diff --git a/lifeChk.py b/lifeChk.py deleted file mode 100755 index aaf7e16..0000000 --- a/lifeChk.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/python3 -################# -# return 0 if streamer is live (continue execution while in bash), 1 if not -################# -import sys -if (not sys.argv[1]) or (not sys.argv[2]): - sys.exit(2) - -from twitch import TwitchClient - -client = TwitchClient(client_id=sys.argv[2]) #client init -user_id=client.users.translate_usernames_to_ids(sys.argv[1])[0].id #get id -#get live by id (if var not empty) - -if client.streams.get_stream_by_user(user_id): - print(user_id) - print(client.streams.get_stream_by_user(user_id).stream_type) - if client.streams.get_stream_by_user(user_id).stream_type == 'live': - sys.exit(0) - -sys.exit(1) From 2b5b0a182ebd8c7c0386bfd8046f3e1467977259 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 00:32:01 +0000 Subject: [PATCH 03/32] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D1=82=D0=BE=D1=82?= =?UTF-8?q?=D0=B8=D0=BF=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8=20?= =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D1=8B=D1=85=20=D1=81=D1=82=D1=80=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index b9f5e19..ee8353c 100644 --- a/daemon.py +++ b/daemon.py @@ -46,7 +46,8 @@ def checkAlive(streamers, client_id): else: print(i+" Не стримит") - +def removeOldStreams(): + pass if __name__ == "__main__": checkAlive(config_python.streamers, config_python.twitchid) From 115fcefab2da33a8305578ba05bc7f53d2fd30b2 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 01:40:48 +0000 Subject: [PATCH 04/32] remove output --- daemon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index ee8353c..0118aff 100644 --- a/daemon.py +++ b/daemon.py @@ -22,7 +22,7 @@ def recorder(i): # FIXME: пофиксить абсолютный путь cmdline = ["/home/losted/.local/bin/youtube-dl","twitch.tv/"+i] import subprocess - s = subprocess.call(cmdline) + s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) def checkAlive(streamers, client_id): From c248845101e7f439f467d3e04469d8db4eada076 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 02:39:06 +0000 Subject: [PATCH 05/32] =?UTF-8?q?Lock=20=D1=84=D0=B0=D0=B9=D0=BB=20=D0=B4?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD.=20=D0=A2=D0=B5?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D1=8C=20=D1=8D=D1=82=D0=BE=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B6=D0=BD=D0=BE=20=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA=D0=B0?= =?UTF-8?q?=D1=82=D1=8C.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- daemon.py | 30 ++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index 67b05d3..3d0c26f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ list.sh config_python.py config_list.sh -__pycache__ \ No newline at end of file +__pycache__ +.vscode \ No newline at end of file diff --git a/daemon.py b/daemon.py index 0118aff..4be5d8c 100644 --- a/daemon.py +++ b/daemon.py @@ -2,10 +2,12 @@ # база со стримерами в json файле +import os from threading import Thread import json import config_python +locked_streams = list() def startRecord(i): ''' @@ -20,10 +22,12 @@ def recorder(i): ''' print("Записываем стрим %s\n" % i) # FIXME: пофиксить абсолютный путь - cmdline = ["/home/losted/.local/bin/youtube-dl","twitch.tv/"+i] + cmdline = ["/home/losted/.local/bin/youtube-dl","https://twitch.tv/"+i] import subprocess s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) + os.system("rm "+config_python.path + "/"+i+"/pid") + print("lock файл удален") def checkAlive(streamers, client_id): ''' @@ -31,20 +35,30 @@ def checkAlive(streamers, client_id): 1.1 Если нет - удалить lock файл, если он есть 1.2 Если есть - создать lock файл, запустить записывалку ''' - from twitch import TwitchClient client = TwitchClient(client_id=client_id) - for i in streamers: - # Если есть такой стример - проверяем, идет ли стрим - user_id=client.users.translate_usernames_to_ids(i)[0]['id'] #Получить ID по нику - # Это зачем проверка? + # Путь до диры со стримами + path = config_python.path + "/"+ i + # Создаем путь, если его нет + if not (os.path.exists(config_python.path+"/"+i)): + os.makedirs(path) + # TODO: Сделать проверку на наличие стримера + user_id=client.users.translate_usernames_to_ids(i)[0]['id'] # Получить ID по нику + # Если стрим идет, то идем дальше if client.streams.get_stream_by_user(user_id): - # Если стрим идет то записываем - if client.streams.get_stream_by_user(user_id).stream_type == 'live': + # Если стрим идет и лок файла нет, то записываем и ставим лок + if (client.streams.get_stream_by_user(user_id).stream_type == 'live') and not (os.path.exists(config_python.path+"/"+i+"/pid")): + print(i+" стримит") startRecord(i) + os.system("touch "+path+"/pid") + else: + print(i+" Уже стримит") else: + # Если стрим не идет, то пишем об этом и убираем его из залоченных print(i+" Не стримит") + os.system("rm "+path+"/pid") + def removeOldStreams(): pass From fa9fa3f137d0a15c58902ddce105e61607c287b1 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 02:45:22 +0000 Subject: [PATCH 06/32] readme --- README.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ee79f51..40410c5 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,22 @@ # Что это? -Скрипт который проверяет и начинает запись live стримов +Скрипт который проверяет и начинает запись стримов с твича (WIP) # Как юзать? -* Поставить youtube-dl, python-twitch-client (TODO: создать requirements.txt для автоматической установки) +* Поставить youtube-dl, python-twitch-client `pip3 install python-twitch-client youtube-dl` -* Переименовать файл conf_python.py.template в conf_python.py и добавить свой ключ (Можно получить на https://dev.twitch.tv/console) +* Создать файл conf_python.py и добавить свой ключ (Можно получить на https://dev.twitch.tv/console), а также переменные: -* Переименовать файл list.sh.template в list.sh, добавить стримеров в параметре list (через пробел), изменить путь для сохранения стримов в path +``` +twitchid="ID" # ID ключа +streamers = ("jesusavgn", "252mart", "vi0xxx") # список стримеров в таком формате +path="/путь/до/диры/со/стримами" # путь до директории, куда писать стримы +``` -* Добавить cron.sh в crontab, ну и офк убедиться что cron.service запущен (systemd timer не подойдет ибо он убивает child процессы после завершения работы родителя) +* Добавить daemon.py в crontab, ну и офк убедиться что cron.service запущен (systemd timer не подойдет ибо он убивает child процессы после завершения работы родителя) `*/5 * * * * /opt/twitch-downloader/cron.sh` From bff624917348a35300b9faad437b73bdb2c82bb3 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sun, 18 Jul 2021 19:16:03 +0000 Subject: [PATCH 07/32] fix paths --- daemon.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/daemon.py b/daemon.py index 4be5d8c..633679c 100644 --- a/daemon.py +++ b/daemon.py @@ -20,14 +20,16 @@ def recorder(i): ''' Функция, которая запускает youtube-dl, фактически записывает стрим ''' + path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) # FIXME: пофиксить абсолютный путь cmdline = ["/home/losted/.local/bin/youtube-dl","https://twitch.tv/"+i] import subprocess s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) - os.system("rm "+config_python.path + "/"+i+"/pid") - print("lock файл удален") + if (os.path.exists(path+"/pid")): + os.system("rm "+path+"/pid") + print("lock файл удален") def checkAlive(streamers, client_id): ''' @@ -40,7 +42,7 @@ def checkAlive(streamers, client_id): for i in streamers: # Путь до диры со стримами path = config_python.path + "/"+ i - # Создаем путь, если его нет + # Создаем путь до диры со стримером, если его нет if not (os.path.exists(config_python.path+"/"+i)): os.makedirs(path) # TODO: Сделать проверку на наличие стримера @@ -57,7 +59,9 @@ def checkAlive(streamers, client_id): else: # Если стрим не идет, то пишем об этом и убираем его из залоченных print(i+" Не стримит") - os.system("rm "+path+"/pid") + # Если есть лок, то удаляем + if (os.path.exists(path+"/pid")): + os.system("rm "+path+"/pid") def removeOldStreams(): From 82efe0ce8c52ac35e16d47b456e61c923beac2c5 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 05:30:37 +0000 Subject: [PATCH 08/32] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20=D0=B7?= =?UTF-8?q?=D0=B0=D1=85=D0=B0=D1=80=D0=B4=D0=BA=D0=BE=D0=B6=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D0=BF=D1=83=D1=82=D1=8C,=20=D0=B4=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=20=D1=85=D0=BE=D1=82=D0=B5=D0=BB=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/daemon.py b/daemon.py index 633679c..682e400 100644 --- a/daemon.py +++ b/daemon.py @@ -1,6 +1,8 @@ #!/usr/bin/python3 -# база со стримерами в json файле +# FIXME: не создавать папки для несуществующих стримеров +# TODO: Сделать нормальную конфигурацию +# TODO: Автоматически удалять старые стримы import os from threading import Thread @@ -23,8 +25,9 @@ def recorder(i): path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) # FIXME: пофиксить абсолютный путь - cmdline = ["/home/losted/.local/bin/youtube-dl","https://twitch.tv/"+i] + cmdline = ["youtube-dl","https://twitch.tv/"+i] import subprocess + # Не хочу делать тут проверку на существование "youtube-dl" в $PATH s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): @@ -65,6 +68,7 @@ def checkAlive(streamers, client_id): def removeOldStreams(): + # https://clck.ru/WHh32 pass if __name__ == "__main__": From 1f19f24dd5c0a17e018a2449ccea9a3da07cb4d1 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 06:13:13 +0000 Subject: [PATCH 09/32] =?UTF-8?q?=D0=9C=D0=BE=D1=8F=20=D1=84=D1=83=D0=BD?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D1=8F=20which?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/daemon.py b/daemon.py index 682e400..05d2fbf 100644 --- a/daemon.py +++ b/daemon.py @@ -11,6 +11,16 @@ import config_python locked_streams = list() +def which(command): + # Пиздец, почему нет нормального аналога which из bash??? + # Мой аналог отдает true или false если есть или нет утилиты command + for dirs in os.get_exec_path(): + if command in os.listdir(dirs): + # Если что-нибудь нашли, то True + return True + # Если ничего не нашли во всех дирах, то завершает функцию с False + return False + def startRecord(i): ''' Функция, которая запускает в отдельном потоке запись стрима - recorder(i) From 30afd5ca4834a127a3beb2564fb4437ee8058876 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 06:22:21 +0000 Subject: [PATCH 10/32] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D1=83=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B5=20=D1=83=D1=82=D0=B8=D0=BB=D0=B8?= =?UTF-8?q?=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/daemon.py b/daemon.py index 05d2fbf..9c580b4 100644 --- a/daemon.py +++ b/daemon.py @@ -21,6 +21,17 @@ def which(command): # Если ничего не нашли во всех дирах, то завершает функцию с False return False +def checkTools(): + ''' + Проверяет, установлены ли необходимые утилиты + ''' + tools = ('youtube-dl', 'ffmpeg') + for i in tools: + if not which(i): + print(i + " не установлен") + return False + return True + def startRecord(i): ''' Функция, которая запускает в отдельном потоке запись стрима - recorder(i) @@ -82,4 +93,5 @@ def removeOldStreams(): pass if __name__ == "__main__": + if not checkTools(): exit() checkAlive(config_python.streamers, config_python.twitchid) From ba3b7ad2f3cc5e645a62167b8c247fbb98d57fa8 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 23:04:09 +0000 Subject: [PATCH 11/32] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20?= =?UTF-8?q?=D1=81=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20=D0=B4=D0=B5=D0=BC=D0=BE?= =?UTF-8?q?=D0=BD=D0=BE=D0=BC=20=D0=B8=20=D1=87=D1=83=D1=82=D1=8C=20=D0=BE?= =?UTF-8?q?=D0=BF=D1=82=D0=B8=D0=BC=D0=B8=D0=B7=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 18 +++++++++++++----- requirements.txt | 3 ++- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/daemon.py b/daemon.py index 9c580b4..884d4ad 100644 --- a/daemon.py +++ b/daemon.py @@ -8,6 +8,11 @@ import os from threading import Thread import json import config_python +import schedule +from twitch import TwitchClient +import subprocess +import time + locked_streams = list() @@ -47,7 +52,6 @@ def recorder(i): print("Записываем стрим %s\n" % i) # FIXME: пофиксить абсолютный путь cmdline = ["youtube-dl","https://twitch.tv/"+i] - import subprocess # Не хочу делать тут проверку на существование "youtube-dl" в $PATH s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) @@ -55,13 +59,14 @@ def recorder(i): os.system("rm "+path+"/pid") print("lock файл удален") -def checkAlive(streamers, client_id): +def checkAlive(): + streamers = config_python.streamers + client_id = config_python.twitchid ''' 1. Проверка на наличие стрима 1.1 Если нет - удалить lock файл, если он есть 1.2 Если есть - создать lock файл, запустить записывалку ''' - from twitch import TwitchClient client = TwitchClient(client_id=client_id) for i in streamers: # Путь до диры со стримами @@ -93,5 +98,8 @@ def removeOldStreams(): pass if __name__ == "__main__": - if not checkTools(): exit() - checkAlive(config_python.streamers, config_python.twitchid) + # if not checkTools(): exit() + schedule.every(config_python.period).minutes.do(checkAlive) + while True: + schedule.run_pending() + time.sleep(1) diff --git a/requirements.txt b/requirements.txt index a757172..7c433f4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ youtube-dl==2021.4.17 -python-twitch-client==0.7.1 \ No newline at end of file +python-twitch-client==0.7.1 +schedule \ No newline at end of file From 607f9f9b5f60ddba322ab89db1dfc927b8ad396c Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 23:20:32 +0000 Subject: [PATCH 12/32] =?UTF-8?q?=D0=9D=D0=B5=D0=BC=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D1=84=D0=B8=D0=BA=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/daemon.py b/daemon.py index 884d4ad..706b221 100644 --- a/daemon.py +++ b/daemon.py @@ -6,7 +6,6 @@ import os from threading import Thread -import json import config_python import schedule from twitch import TwitchClient @@ -14,16 +13,16 @@ import subprocess import time -locked_streams = list() - def which(command): # Пиздец, почему нет нормального аналога which из bash??? - # Мой аналог отдает true или false если есть или нет утилиты command + ''' + Мой аналог which из bash'а, который отдает true или false при наличии или отсутствии утилиты + ''' for dirs in os.get_exec_path(): if command in os.listdir(dirs): # Если что-нибудь нашли, то True return True - # Если ничего не нашли во всех дирах, то завершает функцию с False + # Если ничего не нашли во всех дирах, то выходим с False return False def checkTools(): @@ -50,9 +49,9 @@ def recorder(i): ''' path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) - # FIXME: пофиксить абсолютный путь + # cmdline для запуска youtube-dl + # TODO: сделать возможность добавлять свои параметры cmdline = ["youtube-dl","https://twitch.tv/"+i] - # Не хочу делать тут проверку на существование "youtube-dl" в $PATH s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): @@ -98,7 +97,7 @@ def removeOldStreams(): pass if __name__ == "__main__": - # if not checkTools(): exit() + if not checkTools(): exit() schedule.every(config_python.period).minutes.do(checkAlive) while True: schedule.run_pending() From bb4a29300b867ff5a2287d3a46bd4d517eea1c3b Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 23:23:03 +0000 Subject: [PATCH 13/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=88=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config_list.sh.template | 10 ---------- config_python.py.template | 4 ++++ 2 files changed, 4 insertions(+), 10 deletions(-) delete mode 100644 config_list.sh.template create mode 100644 config_python.py.template diff --git a/config_list.sh.template b/config_list.sh.template deleted file mode 100644 index 362e959..0000000 --- a/config_list.sh.template +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -########### -# just config file -########### - -list="jesusavgn" -twitchid="123456789qwertyuiops" -storage_path="/media/nfs/twitch/automatedRecording" -ytdl_path="/home/ubuntu/.local/bin" -ytdl_conf="-o %(uploader)s__%(upload_date)s_%(timestamp)s__%(title)s_%(id)s.%(ext)s" diff --git a/config_python.py.template b/config_python.py.template new file mode 100644 index 0000000..cac8a9f --- /dev/null +++ b/config_python.py.template @@ -0,0 +1,4 @@ +twitchid="....." +streamers = ("jesusavgn", "252mart", "vi0xxx") +path="/home/losted/test" +period = 5 \ No newline at end of file From e776f8d4e47e90947b2da264441f6b0d1e902552 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 23:28:08 +0000 Subject: [PATCH 14/32] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D1=81=20TODO=20=D0=B2=D0=B2=D0=B5=D1=80=D1=85,=20=D1=81=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=B3=D0=BB=D0=BE=D0=B1=D0=B0=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B5=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/daemon.py b/daemon.py index 706b221..7bd1994 100644 --- a/daemon.py +++ b/daemon.py @@ -1,8 +1,10 @@ #!/usr/bin/python3 +# TODO: Сделать проверку на наличие стримера # FIXME: не создавать папки для несуществующих стримеров # TODO: Сделать нормальную конфигурацию # TODO: Автоматически удалять старые стримы +# TODO: сделать возможность добавлять свои параметры в cmdline к команде записи import os from threading import Thread @@ -11,6 +13,8 @@ import schedule from twitch import TwitchClient import subprocess import time +streamers = config_python.streamers +client_id = config_python.twitchid def which(command): @@ -50,7 +54,6 @@ def recorder(i): path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) # cmdline для запуска youtube-dl - # TODO: сделать возможность добавлять свои параметры cmdline = ["youtube-dl","https://twitch.tv/"+i] s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) print("Запись стрима %s закончена\n" % i) @@ -59,8 +62,6 @@ def recorder(i): print("lock файл удален") def checkAlive(): - streamers = config_python.streamers - client_id = config_python.twitchid ''' 1. Проверка на наличие стрима 1.1 Если нет - удалить lock файл, если он есть @@ -71,9 +72,8 @@ def checkAlive(): # Путь до диры со стримами path = config_python.path + "/"+ i # Создаем путь до диры со стримером, если его нет - if not (os.path.exists(config_python.path+"/"+i)): + if not (os.path.exists(config_python.path + "/" + i)): os.makedirs(path) - # TODO: Сделать проверку на наличие стримера user_id=client.users.translate_usernames_to_ids(i)[0]['id'] # Получить ID по нику # Если стрим идет, то идем дальше if client.streams.get_stream_by_user(user_id): From 5fbdee20a5278d61b8ea28f6a118eeba370c9f72 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 22 Jul 2021 23:28:56 +0000 Subject: [PATCH 15/32] path fix --- daemon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index 7bd1994..651df42 100644 --- a/daemon.py +++ b/daemon.py @@ -72,7 +72,7 @@ def checkAlive(): # Путь до диры со стримами path = config_python.path + "/"+ i # Создаем путь до диры со стримером, если его нет - if not (os.path.exists(config_python.path + "/" + i)): + if not (os.path.exists(path)): os.makedirs(path) user_id=client.users.translate_usernames_to_ids(i)[0]['id'] # Получить ID по нику # Если стрим идет, то идем дальше From bc996a143082b6ed74fda2e7ba5cbb0c434faf0f Mon Sep 17 00:00:00 2001 From: Lulzette Date: Fri, 23 Jul 2021 01:07:53 +0000 Subject: [PATCH 16/32] =?UTF-8?q?DONE:=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BC?= =?UTF-8?q?=D0=B0=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=BE=D0=B5=20=D1=83?= =?UTF-8?q?=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D0=B0?= =?UTF-8?q?=D1=80=D1=8B=D1=85=20=D1=81=D1=82=D1=80=D0=B8=D0=BC=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/daemon.py b/daemon.py index 651df42..0c96b22 100644 --- a/daemon.py +++ b/daemon.py @@ -3,7 +3,6 @@ # TODO: Сделать проверку на наличие стримера # FIXME: не создавать папки для несуществующих стримеров # TODO: Сделать нормальную конфигурацию -# TODO: Автоматически удалять старые стримы # TODO: сделать возможность добавлять свои параметры в cmdline к команде записи import os @@ -94,11 +93,24 @@ def checkAlive(): def removeOldStreams(): # https://clck.ru/WHh32 - pass + records_path = config_python.path + # По каждой папке со стримерами + for i in streamers: + if len(os.listdir(records_path+i)) > config_python.max_files: + # Получаем список файлов + # и смотрим, превышает ли кол-во mp4 файлов заданное в конфиге + # Если превышает - удаляем старейший + oldest = min(os.listdir(records_path+i), key=os.path.getctime) + os.unlink(oldest) + print("Удален файл: " + oldest) if __name__ == "__main__": + # Проверить, установлены ли нужные утилиты if not checkTools(): exit() - schedule.every(config_python.period).minutes.do(checkAlive) + # Проверять стримы раз в check_period + schedule.every(config_python.check_period).minutes.do(checkAlive) + # Каждый час удалять старые стримы + schedule.every(1).hours.do(removeOldStreams) while True: schedule.run_pending() time.sleep(1) From ce76a97253c3c9e4ee60188d0dd9c0760758e10c Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 31 Jul 2021 11:41:35 +0000 Subject: [PATCH 17/32] =?UTF-8?q?=D0=9F=D1=83=D1=82=D1=8C,=20=D0=B8=D0=BC?= =?UTF-8?q?=D1=8F,=20=D1=87=D0=B0=D1=81=D1=82=D0=BE=D1=82=D0=B0=20=D0=BE?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=81=D0=B0.=20=D0=A3=D0=B2=D0=B5=D0=BB?= =?UTF-8?q?=D0=B8=D1=87=D0=B8=D0=BB=20=D1=87=D0=B0=D1=81=D1=82=D0=BE=D1=82?= =?UTF-8?q?=D1=83=20=D0=BE=D0=BF=D1=80=D0=BE=D1=81=D0=B0=20=D0=B4=D0=BE=20?= =?UTF-8?q?=D1=81=D0=B5=D0=BA=D1=83=D0=BD=D0=B4,=20=D0=BF=D0=BE=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BB=D0=BE=D0=B3,=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BF=D1=83=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B4=D0=BB=D1=8F=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=B8.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/daemon.py b/daemon.py index 0c96b22..82a2fe1 100644 --- a/daemon.py +++ b/daemon.py @@ -53,8 +53,10 @@ def recorder(i): path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) # cmdline для запуска youtube-dl - cmdline = ["youtube-dl","https://twitch.tv/"+i] - s = subprocess.call(cmdline, stdout=subprocess.DEVNULL) + cmdline = ["youtube-dl", "-q", + "-o", path + "/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", + "https://twitch.tv/"+i] + s = subprocess.call(cmdline) print("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): os.system("rm "+path+"/pid") @@ -82,7 +84,7 @@ def checkAlive(): startRecord(i) os.system("touch "+path+"/pid") else: - print(i+" Уже стримит") + print(i+" Идет запись") else: # Если стрим не идет, то пишем об этом и убираем его из залоченных print(i+" Не стримит") @@ -108,7 +110,7 @@ if __name__ == "__main__": # Проверить, установлены ли нужные утилиты if not checkTools(): exit() # Проверять стримы раз в check_period - schedule.every(config_python.check_period).minutes.do(checkAlive) + schedule.every(config_python.check_period).seconds.do(checkAlive) # Каждый час удалять старые стримы schedule.every(1).hours.do(removeOldStreams) while True: From 60a5341cdf7d2fe2cec2e8838d63c6bd09e5e530 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 5 Aug 2021 00:40:42 +0000 Subject: [PATCH 18/32] =?UTF-8?q?=D0=A1=D0=B2=D0=BE=D0=B8=20=D0=BF=D0=B0?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D1=8B=20=D0=BA=20ytdl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) mode change 100644 => 100755 daemon.py diff --git a/daemon.py b/daemon.py old mode 100644 new mode 100755 index 82a2fe1..00f01ff --- a/daemon.py +++ b/daemon.py @@ -3,7 +3,6 @@ # TODO: Сделать проверку на наличие стримера # FIXME: не создавать папки для несуществующих стримеров # TODO: Сделать нормальную конфигурацию -# TODO: сделать возможность добавлять свои параметры в cmdline к команде записи import os from threading import Thread @@ -14,7 +13,7 @@ import subprocess import time streamers = config_python.streamers client_id = config_python.twitchid - +ytdl_options = config_python.ytdl_options def which(command): # Пиздец, почему нет нормального аналога which из bash??? @@ -53,7 +52,7 @@ def recorder(i): path = config_python.path + "/"+ i print("Записываем стрим %s\n" % i) # cmdline для запуска youtube-dl - cmdline = ["youtube-dl", "-q", + cmdline = ["youtube-dl", "-q", ytdl_options, "-o", path + "/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", "https://twitch.tv/"+i] s = subprocess.call(cmdline) From 6e3cada45cd6ed159130a5a5ccebef98125ef31a Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 5 Aug 2021 00:45:31 +0000 Subject: [PATCH 19/32] =?UTF-8?q?=D0=9F=D0=BE=D1=84=D0=B8=D0=BA=D1=81?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B0=D0=B2=D1=82=D0=BE=D1=83=D0=B4=D0=B0=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D1=82=D1=80=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/daemon.py b/daemon.py index 00f01ff..e9a1145 100755 --- a/daemon.py +++ b/daemon.py @@ -97,11 +97,12 @@ def removeOldStreams(): records_path = config_python.path # По каждой папке со стримерами for i in streamers: - if len(os.listdir(records_path+i)) > config_python.max_files: + # Если файлов в папке со стримами больше чем указано в конфиге + if len(os.listdir(records_path+"/"+i)) > config_python.max_files: # Получаем список файлов # и смотрим, превышает ли кол-во mp4 файлов заданное в конфиге # Если превышает - удаляем старейший - oldest = min(os.listdir(records_path+i), key=os.path.getctime) + oldest = min(os.listdir(records_path+"/"+i), key=os.path.getctime) os.unlink(oldest) print("Удален файл: " + oldest) From b6f328b682741414576a11a0fce4fdef53f0007c Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 23 Sep 2021 03:59:05 +0300 Subject: [PATCH 20/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BA=D0=BE=D0=B4=20=D0=B2=20=D1=81=D0=BE=D0=BE?= =?UTF-8?q?=D1=82=D0=B2=D0=B5=D1=82=D1=81=D1=82=D0=B2=D0=B8=D0=B8=20=D1=81?= =?UTF-8?q?=20PEP8,=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BB=D0=BE=D0=B3=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 89 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 65 insertions(+), 24 deletions(-) diff --git a/daemon.py b/daemon.py index e9a1145..ade11b1 100755 --- a/daemon.py +++ b/daemon.py @@ -5,20 +5,27 @@ # TODO: Сделать нормальную конфигурацию import os +import sys from threading import Thread import config_python import schedule from twitch import TwitchClient import subprocess import time +import logging +from logging.handlers import TimedRotatingFileHandler streamers = config_python.streamers client_id = config_python.twitchid ytdl_options = config_python.ytdl_options +log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s') +log_file = 'output.log' + def which(command): # Пиздец, почему нет нормального аналога which из bash??? ''' - Мой аналог which из bash'а, который отдает true или false при наличии или отсутствии утилиты + Мой аналог which из bash'а, который отдает true или false + при наличии или отсутствии утилиты ''' for dirs in os.get_exec_path(): if command in os.listdir(dirs): @@ -27,6 +34,7 @@ def which(command): # Если ничего не нашли во всех дирах, то выходим с False return False + def checkTools(): ''' Проверяет, установлены ли необходимые утилиты @@ -34,10 +42,11 @@ def checkTools(): tools = ('youtube-dl', 'ffmpeg') for i in tools: if not which(i): - print(i + " не установлен") + log.critical(i + " не установлен") return False return True + def startRecord(i): ''' Функция, которая запускает в отдельном потоке запись стрима - recorder(i) @@ -45,21 +54,24 @@ def startRecord(i): th = Thread(target=recorder, args=(i, )) th.start() + def recorder(i): ''' Функция, которая запускает youtube-dl, фактически записывает стрим ''' - path = config_python.path + "/"+ i - print("Записываем стрим %s\n" % i) - # cmdline для запуска youtube-dl - cmdline = ["youtube-dl", "-q", ytdl_options, - "-o", path + "/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", - "https://twitch.tv/"+i] + path = config_python.path + "/" + i + log.info("Записываем стрим %s\n" % i) + # cmdline для запуска youtube-dl + cmdline = ["youtube-dl", "-q", ytdl_options, + "-o", + path+"/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", + "https://twitch.tv/" + i] s = subprocess.call(cmdline) - print("Запись стрима %s закончена\n" % i) + log.info("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): os.system("rm "+path+"/pid") - print("lock файл удален") + log.info("lock файл удален") + def checkAlive(): ''' @@ -70,23 +82,24 @@ def checkAlive(): client = TwitchClient(client_id=client_id) for i in streamers: # Путь до диры со стримами - path = config_python.path + "/"+ i + path = config_python.path + "/" + i # Создаем путь до диры со стримером, если его нет if not (os.path.exists(path)): os.makedirs(path) - user_id=client.users.translate_usernames_to_ids(i)[0]['id'] # Получить ID по нику + # Получить ID по нику + user_id = client.users.translate_usernames_to_ids(i)[0]['id'] # Если стрим идет, то идем дальше if client.streams.get_stream_by_user(user_id): # Если стрим идет и лок файла нет, то записываем и ставим лок if (client.streams.get_stream_by_user(user_id).stream_type == 'live') and not (os.path.exists(config_python.path+"/"+i+"/pid")): - print(i+" стримит") + log.info(i + " стримит") startRecord(i) os.system("touch "+path+"/pid") else: - print(i+" Идет запись") + log.info(i + " Идет запись") else: # Если стрим не идет, то пишем об этом и убираем его из залоченных - print(i+" Не стримит") + log.info(i + " Не стримит") # Если есть лок, то удаляем if (os.path.exists(path+"/pid")): os.system("rm "+path+"/pid") @@ -97,22 +110,50 @@ def removeOldStreams(): records_path = config_python.path # По каждой папке со стримерами for i in streamers: - # Если файлов в папке со стримами больше чем указано в конфиге - if len(os.listdir(records_path+"/"+i)) > config_python.max_files: - # Получаем список файлов - # и смотрим, превышает ли кол-во mp4 файлов заданное в конфиге - # Если превышает - удаляем старейший - oldest = min(os.listdir(records_path+"/"+i), key=os.path.getctime) - os.unlink(oldest) - print("Удален файл: " + oldest) + try: + # Если файлов в папке со стримами больше чем указано в конфиге + if len(os.listdir(records_path+"/"+i)) > config_python.max_files: + # Получаем список файлов + # и смотрим, превышает ли кол-во mp4 файлов заданное в конфиге + # Если превышает - удаляем старейший + oldest = min(os.listdir(records_path+"/"+i), key=os.path.getctime) + os.unlink(oldest) + log.warning("Удален файл: " + oldest) + except Exception as e: + log.error(e) + +def get_console_handler(): + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(log_format) + return console_handler + +def get_file_handler(): + file_handler = TimedRotatingFileHandler(log_file, when='midnight') + file_handler.setFormatter(log_format) + return file_handler + +def get_logger(logger_name): + logger = logging.getLogger(logger_name) + logger.setLevel(logging.DEBUG) + logger.addHandler(get_console_handler()) + logger.addHandler(get_file_handler()) + logger.propagate = False + return logger + if __name__ == "__main__": # Проверить, установлены ли нужные утилиты if not checkTools(): exit() + + # Log config + log = get_logger("main") + log.info("Запущен") + # Проверять стримы раз в check_period schedule.every(config_python.check_period).seconds.do(checkAlive) # Каждый час удалять старые стримы schedule.every(1).hours.do(removeOldStreams) + while True: schedule.run_pending() - time.sleep(1) + time.sleep(1) From 52335dd67628cf34d5ff9d87cdfe6131c5ccfb49 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 23 Sep 2021 04:00:59 +0300 Subject: [PATCH 21/32] =?UTF-8?q?=D0=94=D0=BE=D0=BF=20=D0=BE=D0=BF=D1=86?= =?UTF-8?q?=D0=B8=D0=B8=20ytdl=20=D0=BF=D0=BE=D0=BA=D0=B0=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6=D0=B8=D0=B2=D0=B0?= =?UTF-8?q?=D1=8E=D1=82=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/daemon.py b/daemon.py index ade11b1..af91320 100755 --- a/daemon.py +++ b/daemon.py @@ -62,8 +62,7 @@ def recorder(i): path = config_python.path + "/" + i log.info("Записываем стрим %s\n" % i) # cmdline для запуска youtube-dl - cmdline = ["youtube-dl", "-q", ytdl_options, - "-o", + cmdline = ["youtube-dl", "-q", "-o", path+"/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", "https://twitch.tv/" + i] s = subprocess.call(cmdline) From 36d6d1135b59548dee1aa23c70e148ab9fda0818 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 23 Sep 2021 04:11:36 +0300 Subject: [PATCH 22/32] =?UTF-8?q?=D0=91=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20PE?= =?UTF-8?q?P8+=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B5?= =?UTF-8?q?=D1=89=D0=B5=20=D1=87=D1=83=D1=87=D1=83=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/daemon.py b/daemon.py index af91320..45a693c 100755 --- a/daemon.py +++ b/daemon.py @@ -16,7 +16,6 @@ import logging from logging.handlers import TimedRotatingFileHandler streamers = config_python.streamers client_id = config_python.twitchid -ytdl_options = config_python.ytdl_options log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s') log_file = 'output.log' @@ -65,7 +64,7 @@ def recorder(i): cmdline = ["youtube-dl", "-q", "-o", path+"/%(upload_date)s_%(title)s__%(timestamp)s_%(id)s.%(ext)s", "https://twitch.tv/" + i] - s = subprocess.call(cmdline) + subprocess.call(cmdline) log.info("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): os.system("rm "+path+"/pid") @@ -115,22 +114,26 @@ def removeOldStreams(): # Получаем список файлов # и смотрим, превышает ли кол-во mp4 файлов заданное в конфиге # Если превышает - удаляем старейший - oldest = min(os.listdir(records_path+"/"+i), key=os.path.getctime) + oldest = min(os.listdir(records_path+"/"+i), + key=os.path.getctime) os.unlink(oldest) log.warning("Удален файл: " + oldest) except Exception as e: log.error(e) + def get_console_handler(): console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(log_format) return console_handler + def get_file_handler(): file_handler = TimedRotatingFileHandler(log_file, when='midnight') file_handler.setFormatter(log_format) return file_handler + def get_logger(logger_name): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) @@ -142,7 +145,8 @@ def get_logger(logger_name): if __name__ == "__main__": # Проверить, установлены ли нужные утилиты - if not checkTools(): exit() + if not checkTools(): + exit() # Log config log = get_logger("main") From 1ed28aea264b47446e03fb9f0500266acb0c5887 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 23 Sep 2021 06:06:17 +0300 Subject: [PATCH 23/32] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D1=81=D1=82=D0=B0=D1=80=D1=8B=D1=85=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 1 + 1 file changed, 1 insertion(+) diff --git a/daemon.py b/daemon.py index 45a693c..bf82480 100755 --- a/daemon.py +++ b/daemon.py @@ -109,6 +109,7 @@ def removeOldStreams(): # По каждой папке со стримерами for i in streamers: try: + os.chdir(records_path+"/"+i) # Если файлов в папке со стримами больше чем указано в конфиге if len(os.listdir(records_path+"/"+i)) > config_python.max_files: # Получаем список файлов From dd340b8caa6101a322a96f386210b2fb2bd502c6 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Thu, 23 Sep 2021 06:27:54 +0300 Subject: [PATCH 24/32] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=86=D0=B2=D0=B5=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 10 +++++++++- requirements.txt | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/daemon.py b/daemon.py index bf82480..404cc40 100755 --- a/daemon.py +++ b/daemon.py @@ -14,6 +14,8 @@ import subprocess import time import logging from logging.handlers import TimedRotatingFileHandler +from termcolor import colored + streamers = config_python.streamers client_id = config_python.twitchid log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s') @@ -94,7 +96,13 @@ def checkAlive(): startRecord(i) os.system("touch "+path+"/pid") else: - log.info(i + " Идет запись") + log.info( + colored( + "Идет запись " + i, + 'red', + attrs=['bold'] + ) + ) else: # Если стрим не идет, то пишем об этом и убираем его из залоченных log.info(i + " Не стримит") diff --git a/requirements.txt b/requirements.txt index 7c433f4..1e4de30 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ youtube-dl==2021.4.17 python-twitch-client==0.7.1 -schedule \ No newline at end of file +schedule +termcolor From c08670d2a2ff008700f8ddb6c5c5406e9a00d98e Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 14:25:34 +0300 Subject: [PATCH 25/32] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=83=D1=81=D1=82=D0=BE=D0=B9=D1=87=D0=B8=D0=B2=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D1=8C=20=D0=BA=20=D0=BD=D0=B5=D1=81=D1=83=D1=89?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B2=D1=83=D1=8E=D1=89=D0=B8=D0=BC/=D0=B7?= =?UTF-8?q?=D0=B0=D0=B1=D0=B0=D0=BD=D0=B5=D0=BD=D1=8B=D0=BC=20=D1=8E=D0=B7?= =?UTF-8?q?=D0=B5=D1=80=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index 404cc40..c32f8ea 100755 --- a/daemon.py +++ b/daemon.py @@ -7,6 +7,7 @@ import os import sys from threading import Thread +from types import resolve_bases import config_python import schedule from twitch import TwitchClient @@ -87,7 +88,16 @@ def checkAlive(): if not (os.path.exists(path)): os.makedirs(path) # Получить ID по нику - user_id = client.users.translate_usernames_to_ids(i)[0]['id'] + resolved_id = client.users.translate_usernames_to_ids(i) + if not resolved_id: + log.error( + colored( + "Аккаунт " + i + " не найден", + 'red', + ) + ) + break + user_id = resolved_id[0]['id'] # Если стрим идет, то идем дальше if client.streams.get_stream_by_user(user_id): # Если стрим идет и лок файла нет, то записываем и ставим лок From 10c36350e72aa230c96f646f42fc7f1e29632b1c Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 14:26:34 +0300 Subject: [PATCH 26/32] Done TODO --- daemon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index c32f8ea..257bc1a 100755 --- a/daemon.py +++ b/daemon.py @@ -1,6 +1,6 @@ #!/usr/bin/python3 -# TODO: Сделать проверку на наличие стримера +# TODO: Перезапускать скрипт при обнаружении новой версии # FIXME: не создавать папки для несуществующих стримеров # TODO: Сделать нормальную конфигурацию From fc1331e075faeac45b4b11b3eedbefc89116b98f Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 14:49:14 +0300 Subject: [PATCH 27/32] fix readme --- README.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 40410c5..f77547e 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,23 @@ # Что это? -Скрипт который проверяет и начинает запись стримов с твича (WIP) +Скрипт, который записывает стримы с твича, удаляет старые, ведет красивый лог с цветами (Alpha) # Как юзать? -* Поставить youtube-dl, python-twitch-client +* Поставить youtube-dl, ffmpeg и другие пакеты из requirements.txt -`pip3 install python-twitch-client youtube-dl` +`apt install youtube-dl ffmpeg -y` -* Создать файл conf_python.py и добавить свой ключ (Можно получить на https://dev.twitch.tv/console), а также переменные: +`pip install -r requirements.txt` + +* Создать файл conf_python.py и добавить свой ключ (Можно получить на https://dev.twitch.tv/console), а также переменные из config_python.py.template: ``` -twitchid="ID" # ID ключа +twitchid = "ID" # ID ключа streamers = ("jesusavgn", "252mart", "vi0xxx") # список стримеров в таком формате -path="/путь/до/диры/со/стримами" # путь до директории, куда писать стримы +path = "/путь/до/диры/со/стримами" # путь до директории, куда писать стримы +check_period = 5 # Частота проверки стримеров (в секундах) +max_files = 3 # Сколько хранить стримов ``` -* Добавить daemon.py в crontab, ну и офк убедиться что cron.service запущен (systemd timer не подойдет ибо он убивает child процессы после завершения работы родителя) - -`*/5 * * * * /opt/twitch-downloader/cron.sh` - +* Запустить скрипт в screen'е или создать для него systemd.service файл (или init.d, в зависимости от системы инициализации) \ No newline at end of file From 3a539f3ce8e71dedb5833c7ed91c2a5a76f9e8d3 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 14:54:26 +0300 Subject: [PATCH 28/32] =?UTF-8?q?=D0=9D=D0=B5=20=D1=81=D0=BE=D0=B7=D0=B4?= =?UTF-8?q?=D0=B0=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BF=D0=B0=D0=BF=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=BD=D0=B5=D1=81=D1=83=D1=89=D0=B5=D1=81=D1=82=D0=B2=D1=83?= =?UTF-8?q?=D1=8E=D1=89=D0=B8=D1=85=20=D1=81=D1=82=D1=80=D0=B8=D0=BC=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/daemon.py b/daemon.py index 257bc1a..889d66d 100755 --- a/daemon.py +++ b/daemon.py @@ -1,7 +1,6 @@ #!/usr/bin/python3 # TODO: Перезапускать скрипт при обнаружении новой версии -# FIXME: не создавать папки для несуществующих стримеров # TODO: Сделать нормальную конфигурацию import os @@ -84,10 +83,7 @@ def checkAlive(): for i in streamers: # Путь до диры со стримами path = config_python.path + "/" + i - # Создаем путь до диры со стримером, если его нет - if not (os.path.exists(path)): - os.makedirs(path) - # Получить ID по нику + # Получаем инфо о стримере, если не получается, выходим с ошибкой resolved_id = client.users.translate_usernames_to_ids(i) if not resolved_id: log.error( @@ -97,6 +93,11 @@ def checkAlive(): ) ) break + # Создаем путь до диры со стримером, если папка не существует + if not (os.path.exists(path)): + os.makedirs(path) + log.info("Создана директория " + i) + # Достаем ID стримера из инфо user_id = resolved_id[0]['id'] # Если стрим идет, то идем дальше if client.streams.get_stream_by_user(user_id): From c38cb73e3ebc27fef629ca44dd86a06349b113b8 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 23:18:08 +0300 Subject: [PATCH 29/32] =?UTF-8?q?=D0=9F=D0=BE=D1=82=D0=B5=D0=BD=D1=86?= =?UTF-8?q?=D0=B8=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=20=D0=BF=D1=80=D0=BE=D1=82=D0=B8=D0=B2=20=D0=BF=D0=B0?= =?UTF-8?q?=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BD=D0=B0=20104=20=D1=81?= =?UTF-8?q?=D1=82=D1=80=D0=BE=D0=BA=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/daemon.py b/daemon.py index 889d66d..bc20da8 100755 --- a/daemon.py +++ b/daemon.py @@ -74,12 +74,12 @@ def recorder(i): def checkAlive(): + # FIXME: Распилить ну более мелкие функции ''' 1. Проверка на наличие стрима 1.1 Если нет - удалить lock файл, если он есть 1.2 Если есть - создать lock файл, запустить записывалку ''' - client = TwitchClient(client_id=client_id) for i in streamers: # Путь до диры со стримами path = config_python.path + "/" + i @@ -177,6 +177,7 @@ if __name__ == "__main__": # Каждый час удалять старые стримы schedule.every(1).hours.do(removeOldStreams) + client = TwitchClient(client_id=client_id) while True: schedule.run_pending() time.sleep(1) From b0c0573d34383a61f1dc400e466e50f25708cd39 Mon Sep 17 00:00:00 2001 From: Lulzette Date: Sat, 25 Sep 2021 23:49:08 +0300 Subject: [PATCH 30/32] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=BB=20os.system=20=D0=BD=D0=B0=20=D0=BD=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D0=B2=D0=BD=D1=8B=D0=B5=20=D0=B0=D0=BD=D0=B0=D0=BB=D0=BE=D0=B3?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- daemon.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/daemon.py b/daemon.py index bc20da8..294e1dc 100755 --- a/daemon.py +++ b/daemon.py @@ -69,7 +69,7 @@ def recorder(i): subprocess.call(cmdline) log.info("Запись стрима %s закончена\n" % i) if (os.path.exists(path+"/pid")): - os.system("rm "+path+"/pid") + os.remove(path+"/pid") log.info("lock файл удален") @@ -105,7 +105,7 @@ def checkAlive(): if (client.streams.get_stream_by_user(user_id).stream_type == 'live') and not (os.path.exists(config_python.path+"/"+i+"/pid")): log.info(i + " стримит") startRecord(i) - os.system("touch "+path+"/pid") + open(path+"/pid", 'w').close else: log.info( colored( @@ -119,7 +119,7 @@ def checkAlive(): log.info(i + " Не стримит") # Если есть лок, то удаляем if (os.path.exists(path+"/pid")): - os.system("rm "+path+"/pid") + os.remove(path+"/pid") def removeOldStreams(): From 7cb3c3675933f80bdb4de1dfd081000846db751b Mon Sep 17 00:00:00 2001 From: lulzette Date: Sun, 13 Nov 2022 11:31:48 +0300 Subject: [PATCH 31/32] pep-8 --- .gitignore | 3 ++- daemon.py | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 13 deletions(-) mode change 100755 => 100644 daemon.py diff --git a/.gitignore b/.gitignore index 3d0c26f..0352d8d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ list.sh config_python.py config_list.sh __pycache__ -.vscode \ No newline at end of file +.vscode +.idea \ No newline at end of file diff --git a/daemon.py b/daemon.py old mode 100755 new mode 100644 index 294e1dc..b67b157 --- a/daemon.py +++ b/daemon.py @@ -24,10 +24,10 @@ log_file = 'output.log' def which(command): # Пиздец, почему нет нормального аналога which из bash??? - ''' + """ Мой аналог which из bash'а, который отдает true или false при наличии или отсутствии утилиты - ''' + """ for dirs in os.get_exec_path(): if command in os.listdir(dirs): # Если что-нибудь нашли, то True @@ -37,9 +37,9 @@ def which(command): def checkTools(): - ''' + """ Проверяет, установлены ли необходимые утилиты - ''' + """ tools = ('youtube-dl', 'ffmpeg') for i in tools: if not which(i): @@ -49,17 +49,17 @@ def checkTools(): def startRecord(i): - ''' + """ Функция, которая запускает в отдельном потоке запись стрима - recorder(i) - ''' + """ th = Thread(target=recorder, args=(i, )) th.start() def recorder(i): - ''' + """ Функция, которая запускает youtube-dl, фактически записывает стрим - ''' + """ path = config_python.path + "/" + i log.info("Записываем стрим %s\n" % i) # cmdline для запуска youtube-dl @@ -68,18 +68,18 @@ def recorder(i): "https://twitch.tv/" + i] subprocess.call(cmdline) log.info("Запись стрима %s закончена\n" % i) - if (os.path.exists(path+"/pid")): + if os.path.exists(path + "/pid"): os.remove(path+"/pid") log.info("lock файл удален") def checkAlive(): # FIXME: Распилить ну более мелкие функции - ''' + """ 1. Проверка на наличие стрима 1.1 Если нет - удалить lock файл, если он есть 1.2 Если есть - создать lock файл, запустить записывалку - ''' + """ for i in streamers: # Путь до диры со стримами path = config_python.path + "/" + i @@ -118,7 +118,7 @@ def checkAlive(): # Если стрим не идет, то пишем об этом и убираем его из залоченных log.info(i + " Не стримит") # Если есть лок, то удаляем - if (os.path.exists(path+"/pid")): + if os.path.exists(path + "/pid"): os.remove(path+"/pid") From 7961509acaf07bbed18ebd5d205aff5f27d8dc37 Mon Sep 17 00:00:00 2001 From: lulzette Date: Sun, 13 Nov 2022 12:43:03 +0300 Subject: [PATCH 32/32] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=88=D0=B5?= =?UTF-8?q?=D0=BB=20=D0=BD=D0=B0=20=D0=B4=D1=80=D1=83=D0=B3=D1=83=D1=8E,?= =?UTF-8?q?=20=D0=B0=D0=BA=D1=82=D1=83=D0=B0=D0=BB=D1=8C=D0=BD=D1=83=D1=8E?= =?UTF-8?q?=20=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=D1=83?= =?UTF-8?q?=20=D1=82=D0=B2=D0=B8=D1=87=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- README.md | 9 ++++++++- config_python.py.template | 3 ++- daemon.py | 21 +++++++++++++-------- requirements.txt | 2 +- 5 files changed, 26 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 0352d8d..c25b3a3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ config_python.py config_list.sh __pycache__ .vscode -.idea \ No newline at end of file +.idea +output.log \ No newline at end of file diff --git a/README.md b/README.md index f77547e..aae4b98 100644 --- a/README.md +++ b/README.md @@ -20,4 +20,11 @@ check_period = 5 # Частота проверки стримеров (в сек max_files = 3 # Сколько хранить стримов ``` -* Запустить скрипт в screen'е или создать для него systemd.service файл (или init.d, в зависимости от системы инициализации) \ No newline at end of file +* Запустить скрипт в screen'е или создать для него systemd.service файл (или init.d, в зависимости от системы инициализации) + +# Updates + +## 2022-11-13 + +В связи с переходом на новую библиотеку необходимо указывать 2 переменные авторизации - appid и appsecret. +twitchid это appid, а секретный ключ можно получить или перегенерировать в https://dev.twitch.tv/console \ No newline at end of file diff --git a/config_python.py.template b/config_python.py.template index cac8a9f..dfa3865 100644 --- a/config_python.py.template +++ b/config_python.py.template @@ -1,4 +1,5 @@ -twitchid="....." +appid="" +appsecret="" streamers = ("jesusavgn", "252mart", "vi0xxx") path="/home/losted/test" period = 5 \ No newline at end of file diff --git a/daemon.py b/daemon.py index b67b157..f405ec0 100644 --- a/daemon.py +++ b/daemon.py @@ -9,7 +9,7 @@ from threading import Thread from types import resolve_bases import config_python import schedule -from twitch import TwitchClient +from twitchAPI.twitch import Twitch import subprocess import time import logging @@ -17,7 +17,9 @@ from logging.handlers import TimedRotatingFileHandler from termcolor import colored streamers = config_python.streamers -client_id = config_python.twitchid +app_id = config_python.appid +app_secret = config_python.appsecret + log_format = logging.Formatter('%(asctime)s %(levelname)s:%(message)s') log_file = 'output.log' @@ -84,8 +86,10 @@ def checkAlive(): # Путь до диры со стримами path = config_python.path + "/" + i # Получаем инфо о стримере, если не получается, выходим с ошибкой - resolved_id = client.users.translate_usernames_to_ids(i) - if not resolved_id: + + # resolved_id = client.users.translate_usernames_to_ids(i) + resolved_id = twitch_client.get_users(logins=[i]) + if not resolved_id['data']: log.error( colored( "Аккаунт " + i + " не найден", @@ -98,11 +102,12 @@ def checkAlive(): os.makedirs(path) log.info("Создана директория " + i) # Достаем ID стримера из инфо - user_id = resolved_id[0]['id'] + user_id = resolved_id['data'][0]['id'] + user_stream = twitch_client.get_streams(user_id=user_id) # Если стрим идет, то идем дальше - if client.streams.get_stream_by_user(user_id): + if user_stream['data']: # Если стрим идет и лок файла нет, то записываем и ставим лок - if (client.streams.get_stream_by_user(user_id).stream_type == 'live') and not (os.path.exists(config_python.path+"/"+i+"/pid")): + if (user_stream['data'][0]['type'] == 'live') and not (os.path.exists(config_python.path+"/"+i+"/pid")): log.info(i + " стримит") startRecord(i) open(path+"/pid", 'w').close @@ -177,7 +182,7 @@ if __name__ == "__main__": # Каждый час удалять старые стримы schedule.every(1).hours.do(removeOldStreams) - client = TwitchClient(client_id=client_id) + twitch_client = Twitch(app_id, app_secret) while True: schedule.run_pending() time.sleep(1) diff --git a/requirements.txt b/requirements.txt index 1e4de30..4fece1b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ youtube-dl==2021.4.17 -python-twitch-client==0.7.1 +twitchAPI==2.5.7.1 schedule termcolor