From 1d7678c95422c0e872bc0d21861e0644bba6db74 Mon Sep 17 00:00:00 2001 From: taizan-hokuto <55448286+taizan-hokuto@users.noreply.github.com> Date: Sun, 26 Jan 2020 20:06:04 +0900 Subject: [PATCH] Implement module for getting video information --- pytchat/exceptions.py | 3 +++ pytchat/tool/__init__.py | 0 pytchat/tool/videoinfo.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 pytchat/tool/__init__.py create mode 100644 pytchat/tool/videoinfo.py diff --git a/pytchat/exceptions.py b/pytchat/exceptions.py index b8a0045..cffb955 100644 --- a/pytchat/exceptions.py +++ b/pytchat/exceptions.py @@ -41,3 +41,6 @@ class IllegalFunctionCall(Exception): get()を呼び出した場合の例外 ''' pass + +class InvalidVideoIdException(Exception): + pass diff --git a/pytchat/tool/__init__.py b/pytchat/tool/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pytchat/tool/videoinfo.py b/pytchat/tool/videoinfo.py new file mode 100644 index 0000000..b63c165 --- /dev/null +++ b/pytchat/tool/videoinfo.py @@ -0,0 +1,30 @@ +import json +import re +import requests +from .. import config +from .. import util +from ..exceptions import InvalidVideoIdException +headers = config.headers +pattern=re.compile(r"yt\.setConfig\({'PLAYER_CONFIG': ({.*})}\);") + +def _parse(html): + result = re.search(pattern, html) + res= json.loads(result.group(1)) + response = res["args"].get("embedded_player_response") + if response is None: + raise InvalidVideoIdException("Invalid video_id.") + renderer = (json.loads(response))["embedPreview"]["thumbnailPreviewRenderer"] + return { + "duration": int(renderer["videoDurationSeconds"]), + "title" : [''.join(run["text"]) for run in renderer["title"]["runs"]][0], + "channelId" : renderer["videoDetails"]["embeddedPlayerOverlayVideoDetailsRenderer"]["channelThumbnailEndpoint"]["channelThumbnailEndpoint"]["urlEndpoint"]["urlEndpoint"]["url"][9:] + } + +def get_info(video_id): + url = f"https://www.youtube.com/embed/{video_id}" + resp= requests.get(url, headers = headers) + resp.raise_for_status() + return _parse(resp.text) + + +