|
1 | 1 | #!/usr/bin/env python
|
2 | 2 | # -*- coding: utf-8 -*-
|
3 |
| -from __future__ import print_function |
4 | 3 | import os.path
|
5 | 4 | 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 |
15 | 6 | 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 |
28 | 9 |
|
29 | 10 | token_file = os.path.join(os.path.expanduser("~"), '.whoislive2-token')
|
30 | 11 | clientid = "qr27075xc6n85gn944oj70qf0glly4" # please dont abuse
|
31 | 12 |
|
| 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 |
32 | 19 |
|
33 | 20 | # Get token and save it if there is none
|
34 | 21 | 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): ') |
36 | 23 |
|
37 | 24 | 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()) |
42 | 26 | if len(data['data']) == 1:
|
43 | 27 | print("Username: " + data['data'][0]['login'])
|
44 | 28 | print("Saving user id to " + token_file + "...")
|
|
56 | 40 | print('Try again if you want to.')
|
57 | 41 | sys.exit(1)
|
58 | 42 |
|
59 |
| -# We have a token file, read userid |
| 43 | +# We have a token file, read userid from it |
60 | 44 | if os.path.isfile(token_file):
|
61 |
| - # Read token from file |
62 | 45 | with open(token_file) as f:
|
63 | 46 | lines = f.readlines()
|
64 | 47 | for l in lines:
|
65 | 48 | if l.split(":")[0] == 'userid':
|
66 | 49 | userid = l.split(":")[1].rstrip()
|
67 |
| - #print("DEBUG: user id: " + str(userid)) |
68 | 50 |
|
69 | 51 | # We got the user id, now lets show who's live
|
70 | 52 | 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') |
76 | 55 |
|
77 |
| - # figure out total amount of channels |
78 |
| - followed_channels = [] |
| 56 | + # Check total amount of channels |
79 | 57 | total = int(data['total'])
|
80 |
| - #print ('Followed channels:', total) |
| 58 | + #print ('Followed channels according to Twitch:', total) |
81 | 59 |
|
82 |
| - # iterate follows |
| 60 | + # Iterate follows |
| 61 | + followed_channels = [] |
83 | 62 | for channel in data['data']:
|
84 |
| - #print (channel['to_name']) # to_id to_name |
85 | 63 | followed_channels.append(channel['to_id'])
|
86 | 64 |
|
87 | 65 | if total > 100: # we need pagination
|
88 | 66 | while len(followed_channels) < total:
|
89 | 67 | 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) |
95 | 69 | 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 |
111 | 71 |
|
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 |
115 | 73 | 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 += '&' |
124 | 87 | 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) |
131 | 88 |
|
132 |
| - # now call the urls and get who is actually live |
| 89 | + # Now call the urls and get who is actually live |
133 | 90 | live_channels = []
|
134 | 91 | 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) |
139 | 93 | for channel in data['data']:
|
140 |
| - #print(channel['user_name']) |
141 | 94 | live_channels.append({'user': channel['user_name'], 'title': channel['title'], 'viewers': channel['viewer_count']})
|
142 | 95 |
|
143 | 96 | #print ('Live channels:', len(live_channels))
|
144 | 97 |
|
145 |
| - # sort by most viewers |
| 98 | + # Sort by most viewers |
146 | 99 | live_channels_sorted_by_viewers = sorted(live_channels, key=lambda k: k['viewers'], reverse=True)
|
147 | 100 |
|
148 |
| - # print output if there are live channels |
| 101 | + # Output if there are live channels |
149 | 102 | if len(live_channels) > 0:
|
150 | 103 | for channel in live_channels_sorted_by_viewers: # user, title, viewers
|
151 | 104 | print (Fore.GREEN + channel['user'], Fore.YELLOW + channel['title'], Fore.RED + str(channel['viewers']))
|
|
0 commit comments