From 34b0592cf30ba07fdcbd2967cc37211550ca427c Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Fri, 23 Aug 2019 09:03:30 +0200 Subject: [PATCH] Fix usage of deprecated v3 API related #8 --- twitchdl/commands.py | 7 ++++++- twitchdl/twitch.py | 37 +++++++++++++++++++++++++++++++------ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/twitchdl/commands.py b/twitchdl/commands.py index be7f8e5..91f5c97 100644 --- a/twitchdl/commands.py +++ b/twitchdl/commands.py @@ -73,8 +73,13 @@ def _print_video(video): def videos(channel_name, limit, offset, sort, **kwargs): - videos = twitch.get_channel_videos(channel_name, limit, offset, sort) + print_out("Looking up user...") + user = twitch.get_user(channel_name) + if not user: + raise ConsoleError("User {} not found.".format(channel_name)) + print_out("Loading videos...") + videos = twitch.get_channel_videos(user["id"], limit, offset, sort) count = len(videos['videos']) if not count: print_out("No videos found") diff --git a/twitchdl/twitch.py b/twitchdl/twitch.py index 67a940c..c786829 100644 --- a/twitchdl/twitch.py +++ b/twitchdl/twitch.py @@ -1,3 +1,7 @@ +""" +Twitch API access. +""" + import requests from twitchdl import CLIENT_ID @@ -5,8 +9,8 @@ from twitchdl.exceptions import ConsoleError from twitchdl.parse import parse_playlists, parse_playlist -def authenticated_get(url, params={}): - headers = {'Client-ID': CLIENT_ID} +def authenticated_get(url, params={}, headers={}): + headers['Client-ID'] = CLIENT_ID response = requests.get(url, params, headers=headers) if response.status_code == 400: @@ -18,22 +22,43 @@ def authenticated_get(url, params={}): return response +def kraken_get(url, params={}, headers={}): + """ + Add accept header required by kraken API v5. + see: https://discuss.dev.twitch.tv/t/change-in-access-to-deprecated-kraken-twitch-apis/22241 + """ + headers["Accept"] = "application/vnd.twitchtv.v5+json" + return authenticated_get(url, params, headers) + + +def get_user(login): + """ + https://dev.twitch.tv/docs/api/reference/#get-users + """ + response = authenticated_get("https://api.twitch.tv/helix/users", { + "login": login + }) + + users = response.json()["data"] + return users[0] if users else None + + def get_video(video_id): """ https://dev.twitch.tv/docs/v5/reference/videos#get-video """ url = "https://api.twitch.tv/kraken/videos/%d" % video_id - return authenticated_get(url).json() + return kraken_get(url).json() -def get_channel_videos(channel_name, limit, offset, sort): +def get_channel_videos(channel_id, limit, offset, sort): """ https://dev.twitch.tv/docs/v5/reference/channels#get-channel-videos """ - url = "https://api.twitch.tv/kraken/channels/%s/videos" % channel_name + url = "https://api.twitch.tv/kraken/channels/{}/videos".format(channel_id) - return authenticated_get(url, { + return kraken_get(url, { "broadcast_type": "archive", "limit": limit, "offset": offset,