Added different base-data for v5 and v6 API calls. Added function to parse game_name into game_id

This commit is contained in:
2017-10-09 00:22:32 +03:00
parent 529e5980e4
commit c7801b81f8
2 changed files with 28 additions and 7 deletions

View file

@ -2,13 +2,17 @@
# -*- coding: utf-8 -*-
from twitch import TwitchClient
import json
def main():
with open('.token', 'r') as reader:
twitch_token = reader.read().strip()
client = TwitchClient(twitch_token)
print(client.raw_query('streams?first=20'))
streams = client.raw_query_v6('streams?game_id=%s&first=100&language=ru&type=live' % client.get_game_id('IRL')[0])
for i in streams['data']:
print(i['title'])
if __name__ == '__main__':
main()

View file

@ -1,12 +1,29 @@
import json
import requests
class TwitchClient:
def __init__(self, token):
self.token = token
self.header = {'Client-ID': self.token}
self.urlbase = 'https://api.twitch.tv/helix/'
def raw_query(self, q):
r = requests.get(self.urlbase+q, headers=self.header)
return r.text
self.header_v5 = {'Client-ID': self.token, 'Accept': 'application/vnd.twitchtv.v5+json'}
self.header_v6 = {'Client-ID': self.token}
self.urlbase_v5 = 'https://api.twitch.tv/kraken/'
self.urlbase_v6 = 'https://api.twitch.tv/helix/'
def get_base(self, ver):
if ver == 'v5': return (self.header_v5, self.urlbase_v5)
elif ver == 'v6': return (self.header_v6, self.urlbase_v6)
else: return (None, None)
def raw_query_v6(self, q):
header, base = self.get_base('v6')
return requests.get(base+q, headers=header).json()
# Returns (ID, GAMENAME) or None
def get_game_id(self, name):
header, base = self.get_base('v5')
r = requests.get('%s/search/games?query=%s' % (base, name), headers=header).json()
if r.get('games', None): return (r['games'][0]['_id'], r['games'][0]['name'])
return None