multistream/scripts/update_streams.py
File Type: text/x-script.python
#update_streams
from django.conf import settings
from twitchAPI.twitch import Twitch
from frontend import models
from datetime import datetime
import pprint
pp = pprint.PrettyPrinter(indent=4)
def run():
t_client = Twitch(settings.TWITCH_CLIENT_ID, settings.TWITCH_CLIENT_SECRET)
channels = models.Channel.objects.filter(active=True)
try:
t_streams = t_client.get_streams(
user_id=[channel.tid for channel in channels],
first=min(len(channels),100))
except:
t_streams = None
pp.pprint("Error communicating with Twitch API")
updated_channels = []
if t_streams:
for s in t_streams['data']:
c = channels.get(name__iexact=s['user_login'].lower())
pp.pprint("Updating: " + c.name + " is Live")
updated_channels.append(c.name)
c.live = True
c.preview = s['thumbnail_url'] \
.replace("{width}",str(settings.THUMBNAIL_WIDTH)) \
.replace("{height}",str(settings.THUMBNAIL_HEIGHT))
c.viewer_count = s['viewer_count']
c.game = s['game_name']
c.last_saved = datetime.now()
c.save()
#set stale channels to not-live
for c in channels:
if c.live == True and c.name not in updated_channels and c.age_in_seconds() > settings.CHANNEL_STALE_TIME:
pp.pprint("Marking Stale: " + c.name + " (age: " + str(c.age_in_seconds()) + ")")
c.live = False
c.save()