Skip to content

Commit c3766c4

Browse files
author
djs
committed
code cleanup, python2 probably doesn't work anymore
1 parent 930eea5 commit c3766c4

File tree

2 files changed

+40
-85
lines changed

2 files changed

+40
-85
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.DS_Store
2+
.whoislive2-token

whoislive.py

Lines changed: 38 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,28 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3-
from __future__ import print_function
43
import os.path
54
import json
6-
try:
7-
raw_input = raw_input
8-
except NameError:
9-
raw_input = input
10-
try:
11-
# python3 fixes
12-
import urllib.request as urllib2
13-
except ImportError:
14-
import urllib2
5+
import urllib.request as urllib2
156
import sys
16-
from colorama import Fore
17-
from colorama import init
18-
init()
19-
20-
try:
21-
reload
22-
except NameError:
23-
# python3 has unicode by default
24-
pass
25-
else:
26-
reload(sys).setdefaultencoding('utf-8')
27-
7+
from colorama import Fore, init
8+
init() # init() is needed, otherwise we get red prompt after execution
289

2910
token_file = os.path.join(os.path.expanduser("~"), '.whoislive2-token')
3011
clientid = "qr27075xc6n85gn944oj70qf0glly4" # please dont abuse
3112

13+
def TwitchRequest(url):
14+
req = urllib2.Request(url)
15+
req.add_header('Client-ID', clientid)
16+
response = urllib2.urlopen(req)
17+
data = json.loads(response.read())
18+
return data
3219

3320
# Get token and save it if there is none
3421
if not os.path.isfile(token_file):
35-
input_username = raw_input('Enter your Twtich.tv username (or someone elses if you wanna pretend to be them): ')
22+
input_username = input('Enter your Twtich.tv username (or someone elses if you wanna pretend to be them): ')
3623

3724
print("Grabbing User ID...")
38-
req = urllib2.Request('https://api.twitch.tv/helix/users?login=' + input_username)
39-
req.add_header('Client-ID', clientid)
40-
response = urllib2.urlopen(req)
41-
data = json.loads(response.read())
25+
data = TwitchRequest('https://api.twitch.tv/helix/users?login=' + input_username.rstrip())
4226
if len(data['data']) == 1:
4327
print("Username: " + data['data'][0]['login'])
4428
print("Saving user id to " + token_file + "...")
@@ -56,96 +40,65 @@
5640
print('Try again if you want to.')
5741
sys.exit(1)
5842

59-
# We have a token file, read userid
43+
# We have a token file, read userid from it
6044
if os.path.isfile(token_file):
61-
# Read token from file
6245
with open(token_file) as f:
6346
lines = f.readlines()
6447
for l in lines:
6548
if l.split(":")[0] == 'userid':
6649
userid = l.split(":")[1].rstrip()
67-
#print("DEBUG: user id: " + str(userid))
6850

6951
# We got the user id, now lets show who's live
7052
if userid:
71-
# grab followed streams
72-
req = urllib2.Request('https://api.twitch.tv/helix/users/follows?from_id=' + userid + '&first=100')
73-
req.add_header('Client-ID', clientid)
74-
response = urllib2.urlopen(req)
75-
data = json.loads(response.read())
53+
# Grab followed streams
54+
data = TwitchRequest('https://api.twitch.tv/helix/users/follows?from_id=' + userid + '&first=100')
7655

77-
# figure out total amount of channels
78-
followed_channels = []
56+
# Check total amount of channels
7957
total = int(data['total'])
80-
#print ('Followed channels:', total)
58+
#print ('Followed channels according to Twitch:', total)
8159

82-
# iterate follows
60+
# Iterate follows
61+
followed_channels = []
8362
for channel in data['data']:
84-
#print (channel['to_name']) # to_id to_name
8563
followed_channels.append(channel['to_id'])
8664

8765
if total > 100: # we need pagination
8866
while len(followed_channels) < total:
8967
pagination_cursor = data['pagination']['cursor']
90-
#print ('DEBUG pagination cursor:', pagination_cursor)
91-
req = urllib2.Request('https://api.twitch.tv/helix/users/follows?from_id=' + userid + '&first=100&after=' + pagination_cursor)
92-
req.add_header('Client-ID', clientid)
93-
response = urllib2.urlopen(req)
94-
data = json.loads(response.read())
68+
data = TwitchRequest('https://api.twitch.tv/helix/users/follows?from_id=' + userid + '&first=100&after=' + pagination_cursor)
9569
for channel in data['data']:
96-
#print (channel['to_name']) # to_id to_name
97-
followed_channels.append(channel['to_id'])
98-
99-
# validate follows to make sure there are no dupes because i dont trust my pagination skills
100-
if len(followed_channels) != total:
101-
print ("error! amount of parsed channels and followed channels reported from twitch do not match")
102-
sys.exit(1)
103-
104-
for c in followed_channels:
105-
if followed_channels.count(c) > 1:
106-
print ("error! duplicate in followed channels:",c)
107-
sys.exit(1)
108-
109-
110-
#print ('DEBUG: len fc list:', len(followed_channels))
70+
followed_channels.append(channel['to_id']) # Add channel id to followed_channels
11171

112-
# generate urls that we will call to see who is live
113-
# we need to do this because you can request max 100 channels per call
114-
# this is a damn mess btw
72+
# Generate urls that we will later call to see who is live
11573
urls_to_call = []
116-
x = 0
117-
while x < len(followed_channels):
118-
i = 0
119-
url = 'https://api.twitch.tv/helix/streams?'
120-
while i < 100: # 100 per call
121-
if i > 0:
122-
url += "&" # the first user_id= uses the ? in /streams?
123-
url += 'user_id=' + followed_channels[x]
74+
i = 1
75+
url = 'https://api.twitch.tv/helix/streams?'
76+
for channel in followed_channels:
77+
url += 'user_id=' + channel
78+
if i == 100: # max 100 per call
79+
urls_to_call.append(url)
80+
url = 'https://api.twitch.tv/helix/streams?'
81+
i = 1
82+
elif channel == followed_channels[-1]: # Last channel. This is so we won't end the url with an &
83+
urls_to_call.append(url)
84+
break
85+
else:
86+
url += '&'
12487
i += 1
125-
x += 1
126-
if x == len(followed_channels): # we've gone through all channels
127-
break
128-
urls_to_call.append(url)
129-
130-
#print ('debug x ', x) # should be the same as total and len(followed_channels)
13188

132-
# now call the urls and get who is actually live
89+
# Now call the urls and get who is actually live
13390
live_channels = []
13491
for url in urls_to_call:
135-
req = urllib2.Request(url)
136-
req.add_header('Client-ID', clientid)
137-
response = urllib2.urlopen(req)
138-
data = json.loads(response.read())
92+
data = TwitchRequest(url)
13993
for channel in data['data']:
140-
#print(channel['user_name'])
14194
live_channels.append({'user': channel['user_name'], 'title': channel['title'], 'viewers': channel['viewer_count']})
14295

14396
#print ('Live channels:', len(live_channels))
14497

145-
# sort by most viewers
98+
# Sort by most viewers
14699
live_channels_sorted_by_viewers = sorted(live_channels, key=lambda k: k['viewers'], reverse=True)
147100

148-
# print output if there are live channels
101+
# Output if there are live channels
149102
if len(live_channels) > 0:
150103
for channel in live_channels_sorted_by_viewers: # user, title, viewers
151104
print (Fore.GREEN + channel['user'], Fore.YELLOW + channel['title'], Fore.RED + str(channel['viewers']))

0 commit comments

Comments
 (0)