Skip to content

Instantly share code, notes, and snippets.

@MineRobber9000
Last active July 16, 2017 06:11
Show Gist options
  • Save MineRobber9000/da7b0e28b64baddbf0e52caf57d60651 to your computer and use it in GitHub Desktop.
Save MineRobber9000/da7b0e28b64baddbf0e52caf57d60651 to your computer and use it in GitHub Desktop.
A small library for accessing channel info from the Twitch API.
import requests
class ChanInfoError(Exception):
pass;
class OfflineStreamOBJ: # fix for offline streams backported from APIv5 version
def __init__(self,id,name):
self.id = id
self.name = name # we know the name for sure so we can use it
self.message = "[OFFLINE]"
def __getitem__(self,k):
if k=="channel":
return OfflineStreamChannelDict(self.id,self.name)
return self.message
class OfflineStreamChannelDict: # fix for offline stream channels backported from APIv5 version
def __init__(self,id,name):
self.id = id
self.name = name # we know the name for sure so we can use it
self.message = "[OFFLINE]"
def __getitem__(self,k):
if k=="_id":
return self.id
elif k=="name":
return self.name
return self.message
class ChannelInfo:
"""A class for obtaining info for a Twitch Channel"""
def __init__(self,channel,client_id):
self.channel = channel;
self.client_id = client_id;
self.resp = requests.get("https://api.twitch.tv/kraken/streams/{!s}?client_id={!s}".format(channel,client_id));
if self.resp.json().get("error") != None:
raise ChanInfoError("{status} {error} - \"{message}\"".format(**self.resp.json()))
self.streamobj = self.resp.json().get("stream",OfflineStreamOBJ(0,self.channel))
"""If the channel is online, returns true. Else, returns false."""
def isOnline(self):
return self.resp.json().get('stream') != None;
"""Get the status of the stream."""
def getStatus(self):
return self.streamobj['channel']['status']
"""Get the game."""
def getGame(self):
return self.streamobj['game']
"""Get whether to display "playing" or "being"."""
def getDisplay(self):
return self.getGame() == "Creative"
"""Get viewer count."""
def getViewers(self):
return self.streamobj['viewers']
"""Get embed frame (for HTML)"""
def getEmbed(self, width=950, height=700, autoplay=False):
return "<iframe src='http://player.twitch.tv/?channel={}&autoplay={}' width='{!s}' height='{!s}' frameborder='0' scrolling='no' allowfullscreen='true'></iframe>".format(self.streamobj["channel"]["name"],str(autoplay).lower(),width,height)
"""Update data, just runs the init again."""
def update(self):
self.__init__(self.channel,self.client_id)
import requests
class ChanInfoError(Exception):
pass;
class OfflineStreamOBJ:
def __init__(self,id):
self.id = id
self.message = '[OFFLINE]'
def __getitem__(self,k):
if k=='channel':
return OfflineStreamChannelDict(self.id)
return self.message
class OfflineStreamChannelDict:
def __init__(self,id,name=''):
self.id = id
self.name = name
self.message = '[OFFLINE]'
def __getitem__(self,k):
if k=='_id':
return self.id
elif k=='name':
return self.name
return self.message
class ChannelInfo:
"""A class for obtaining info for a Twitch Channel"""
def __init__(self,client_id,channel='',channel_id=''):
self.client_id = client_id;
self.headers = {}
self.headers["Accept"] = 'application/vnd.twitchtv.v5+json'
self.headers["Client-ID"] = self.client_id
if channel and not channel_id:
# when presented with a channel and no channel ID, get channel ID!
resp = self._callAPIMethod("/kraken/users?logins={}".format(channel))
self.channel_id = resp["users"][0]["_id"] # use channel ID of first channel
elif channel_id:
# if given a channel id, prefer it over legacy username
self.channel_id = channel_id
self.resp = self._callAPIMethod("/kraken/streams/{!s}".format(self.channel_id));
if self.isOnline():
self.streamobj = self.resp["stream"]
else:
self.streamobj = OfflineStreamOBJ(self.channel_id)
"""Internal method. Calls Twitch API with correct headers."""
def _callAPIMethod(self,method):
resp = requests.get("https://api.twitch.tv{}".format(method),headers=self.headers)
if resp.json().get("error",0)>0:
raise ChanInfoError("{status} {error} - \"{message}\"".format(**self.resp.json()))
return resp.json()
"""If the channel is online, returns true. Else, returns false."""
def isOnline(self):
return self.resp.get('stream') != None;
"""Get the status of the stream."""
def getStatus(self):
return self.streamobj['channel']['status']
"""Get the game."""
def getGame(self):
return self.streamobj['game']
"""Get whether to display "playing" or "being"."""
def getDisplay(self):
return self.getGame() == "Creative"
"""Get viewer count."""
def getViewers(self):
return self.streamobj['viewers']
"""Get embed frame (for HTML)"""
def getEmbed(self, width=950, height=700, autoplay=False):
return "<iframe src='http://player.twitch.tv/?channel={}&autoplay={}' width='{!s}' height='{!s}' frameborder='0' scrolling='no' allowfullscreen='true'></iframe>".format(self.getName(),str(autoplay).lower(),width,height)
"""Get name of channel."""
def getName(self):
return self.streamobj['channel']['name']
"""Get display name of channel."""
def getDisplayName(self):
return self.streamobj['channel']['display_name']
"""Update data, just runs the init again."""
def update(self):
self.__init__(self.channel,self.client_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment