Added function for getting stream info and threadlock in queries

This commit is contained in:
Aleksej Vanin 2017-10-11 12:05:50 +03:00
parent 9b992cce9d
commit 6a2e86dc2b

View file

@ -1,30 +1,35 @@
import requests import requests
import time import time
import threading
class TwitchClient: class TwitchClient:
def __init__(self, token, freq=2): def __init__(self, token, freq=2):
self.token = token self.token = token
self.lock = threading.Lock()
self.header_v5 = {'Client-ID': self.token, 'Accept': 'application/vnd.twitchtv.v5+json'} self.header_v5 = {'Client-ID': self.token, 'Accept': 'application/vnd.twitchtv.v5+json'}
self.header_v6 = {'Client-ID': self.token} self.header_v6 = {'Client-ID': self.token}
self.urlbase_v5 = 'https://api.twitch.tv/kraken/' self.urlbase_v5 = 'https://api.twitch.tv/kraken/'
self.urlbase_v6 = 'https://api.twitch.tv/helix/' self.urlbase_v6 = 'https://api.twitch.tv/helix/'
self.last_q = time.time() self.last_q = time.time()
self.delay = 1/freq self.delay = 1/freq
def do_q(self, base, header): def do_q(self, base, header):
if time.time() - self.last_q < self.delay: self.lock.acquire()
time.sleep(self.delay) delta = time.time() - self.last_q
if delta < self.delay:
time.sleep(delta)
r = requests.get(base, headers=header).json() r = requests.get(base, headers=header).json()
self.last_q = time.time() self.last_q = time.time()
self.lock.release()
return r return r
def get_base(self, ver): def get_base(self, ver):
if ver == 'v5': return (self.header_v5, self.urlbase_v5) if ver == 'v5': return (self.header_v5, self.urlbase_v5)
elif ver == 'v6': return (self.header_v6, self.urlbase_v6) elif ver == 'v6': return (self.header_v6, self.urlbase_v6)
else: return (None, None) else: return None
# - # - # # - # - #
@ -43,3 +48,8 @@ class TwitchClient:
if r.get('games', None): return (r['games'][0]['_id'], r['games'][0]['name']) if r.get('games', None): return (r['games'][0]['_id'], r['games'][0]['name'])
return None return None
def get_game_list(self, name, lang, lim):
header, base = self.get_base('v5')
r = self.do_q('%s/streams/?game=%s&language=%s&limit=%s' % (base, name, lang, str(lim)), header)
return r