You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.0 KiB

import dateutil.parser
import requests
class Twitch(object):
def __init__(self, api_url, client_id, log=None):
self.api_url = api_url
self.client_id = client_id
self.log = log
def _get_videos(self, user_id):
def request(offset, limit):
url = '{0}/channels/{1}/videos'.format(self.api_url, user_id)
params = dict(client_id=self.client_id, offset=offset, limit=limit)
r = requests.get(url, params=params)
r.raise_for_status()
return r.json()
result = []
data = request(0, 1)
total = data.get('_total', 0)
limit = 100
for offset in range(0, total, limit):
data = request(offset, limit)
for vid in data.get('videos', []):
result.append(dict(
id=int(vid['_id'].lstrip('v')),
title=vid['title'],
date=dateutil.parser.parse(vid['recorded_at']).date()))
return result
def _get_comments(self, video_id):
def request(cursor):
url = '{0}/videos/{1}/comments'.format(self.api_url, video_id)
params = dict(client_id=self.client_id, cursor=cursor)
r = requests.get(url, params=params)
r.raise_for_status()
return r.json()
result = []
cursor = ''
while True:
data = request(cursor)
for comment in data.get('comments', []):
result.append(comment['message']['body'])
cursor = data.get('_next')
if not cursor:
break
return result
def get_messages(self, user_id, since):
videos = self._get_videos(user_id)
result = []
for video in [v for v in videos if v['date'] >= since]:
if self.log:
self.log.info('Processing VOD %d (%s)', video['id'], video['title'])
comments = self._get_comments(video['id'])
result.extend(comments)
return result