1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
|
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
from urllib.error import HTTPError
from urllib.error import URLError
from urllib.request import urlopen
import json
from Caching import Caching
##################################################
## Settings
##################################################
# Directory for a local cache & time to live for cache items in seconds
CACHE = True
##################################################
executor = ThreadPoolExecutor(max_workers=25)
class SteamAPI():
def __init__(self, token):
self.token = token
def getGames(self):
"""Get list of steam games by app id.
Returns:
dict() with str(appid) as keys, str gamename as value
"""
if CACHE:
cache = Caching.readCache('general', 'gamelist', 7*24*60*60)
if cache:
return json.loads(cache)
url = 'https://api.steampowered.com/ISteamApps/GetAppList/v2'
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
applist = jsondata['applist']['apps']
except KeyError:
return None
except HTTPError:
return None
gamelist = dict()
for app in applist:
# str keys for json conversion
gamelist[str(app['appid'])] = app['name']
if CACHE:
cache = Caching.writeCache('general', 'gamelist', json.dumps(gamelist))
return gamelist
def getProfiles(self, steamids):
"""Get steam profiles.
Args:
steamids: Steamids to fetch profiles for
Returns:
dict() with str(steamid) as keys
"""
profile = dict()
steamids_copy = [str(steamid) for steamid in steamids]
if CACHE:
cachedids = []
for steamid in steamids_copy:
cache = Caching.readCache('profile', steamid, 15)
if cache:
cachedids.append(steamid)
profile[steamid] = json.loads(cache)
for steamid in cachedids:
steamids_copy.remove(steamid)
responses = []
while steamids_copy:
steamidlist = ','.join([str(x) for x in steamids_copy[:50]])
steamids_copy = steamids_copy[50:]
url = 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?format=json&key=%s&steamids=%s' % (self.token, steamidlist)
responses.append(executor.submit(urlopen, url))
for responseF in responses:
response = responseF.result()
if response.status != 200:
continue
data = response.read().decode('utf-8')
jsondata = json.loads(data)
for player in jsondata['response']['players']:
currentid = player['steamid']
profile[currentid] = player
if CACHE:
# save newly loaded profiles
for steamid in steamids_copy:
if steamid not in profile:
continue
Caching.writeCache('profile', steamid, json.dumps(profile[steamid]))
return profile
def getMultipleFriends(self, steamids):
results = dict()
for steamid in steamids:
results[steamid] = executor.submit(self.getFriends, steamid)
profiles = executor.submit(self.getProfiles, steamids).result()
for steamid in steamids:
profiles[steamid]['friends'] = results[steamid].result()
return profiles
def getFriends(self, steamid):
"""Fetch steam friends for given steamid.
Args:
steamid: Steamid, whose friendslist to fetch
Returns:
List of steamids. TODO(andre): We lose additional information here.
"""
if CACHE:
cache = Caching.readCache('friends', steamid, 15*60)
if cache:
return json.loads(cache)
url = 'https://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=%s&steamid=%s&relationship=friend' % (self.token, str(steamid))
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
except HTTPError:
# f.e. profile is private
jsondata = None
friends = []
if jsondata and 'friendslist' in jsondata and 'friends' in jsondata['friendslist']:
friends = [friend['steamid'] for friend in jsondata['friendslist']['friends']]
if CACHE:
Caching.writeCache('friends', steamid, json.dumps(friends))
return friends
def getGameSchema(self, gameid):
"""Fetch info about a game.
Args:
gameid: Appid of the game
Returns:
gameName, gameVersion, availableGameStats (Achievements/Stats)
"""
if CACHE:
cache = Caching.readCache('gameschema', gameid, 7*24*60*60)
if cache:
jsondata = json.loads(cache)
return jsondata['game']
url = 'http://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/?key=%s&appid=%s&format=json' % (self.token, str(gameid))
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
except HTTPError as e:
# f.e. profile is private
jsondata = None
if 'game' in jsondata:
if CACHE:
Caching.writeCache('gameschema', gameid, json.dumps(jsondata))
return jsondata['game']
return None
def getPlayerGames(self, steamid):
"""Fetch a list of games a person possesses.
Args:
steamid: Steamid, whose gamelist to fetch
Returns:
Tuple with (number of games, gameinfo [appid, name, playtime_2weeks, playtime_forever, icons])
"""
if CACHE:
cache = Caching.readCache('games', steamid, 60*60)
if cache:
jsondata = json.loads(cache)
return ( jsondata['response']['game_count'], jsondata['response']['games'] )
url = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=%s&steamid=%s&include_appinfo=1&format=json' % (self.token, str(steamid))
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
except HTTPError:
# f.e. profile is private
jsondata = None
if 'response' in jsondata and 'games' in jsondata['response']:
if CACHE:
Caching.writeCache('games', steamid, json.dumps(jsondata))
return ( jsondata['response']['game_count'], jsondata['response']['games'] )
return None
def getUserstatsForGame(self, steamid, gameid):
"""Fetch the available game stats for a player in the specified game.
Args:
steamid: Steamid of the particular user
gameid: Appid of the game we want to check
Returns:
dict() with statname and value
"""
if CACHE:
cache = Caching.readCache('usergamestats', '%s-%s' % (str(steamid), str(gameid)), 24*60*60)
if cache:
cachedata = json.loads(cache)
return cachedata
url = 'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0001/?key=%s&steamid=%s&appid=%s' % (self.token, str(steamid), str(gameid))
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
statslist = jsondata['playerstats']['stats']
userstats = dict()
for stat in statslist:
userstats[stat] = statslist[stat]['value']
except HTTPError:
# f.e. profile is private
userstats = None
if userstats:
if CACHE:
cache = Caching.writeCache('usergamestats', '%s-%s' % (str(steamid), str(gameid)), json.dumps(userstats))
return userstats
return None
def getMultipleUserUserstatsForGame(self, steamids, gameid):
futures = dict()
for steamid in steamids:
futures[steamid] = executor.submit(self.getUserstatsForGame, steamid, gameid)
result = dict()
for steamid in steamids:
result[steamid] = futures[steamid].result()
return result
def getOwnedGames(self, steamid):
"""Fetch games owned by a player.
Args:
steamid: Steamid of the particular user
Returns:
dict() with game_count and games, which contains appid + playtime_forever
"""
if CACHE:
cache = Caching.readCache('userownedgames', '%s' % (str(steamid)), 7*24*60*60)
if cache:
cachedata = json.loads(cache)
return cachedata
url = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=%s&steamid=%s' % (self.token, str(steamid))
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
if 'response' in jsondata:
jsondata = jsondata['response']
except HTTPError:
jsondata = None
if jsondata:
if CACHE:
cache = Caching.writeCache('userownedgames', '%s' % (str(steamid)), json.dumps(jsondata))
return jsondata
return None
def getGameUpdateState(self, gameid, gameversion):
"""Fetch the current game update state.
Args:
gameid: Steam game id
gameversion: Current version of the game
Returns:
dict() with the following keys:
- success Boolean Was able to check version
- up_to_date Boolean If the game is up to date
- version_is_listable Boolean If the game version is listed
- required_version (int) ? New version ?
- message (String) Message to display
"""
if CACHE:
cache = Caching.readCache('serverupdate', '%s-%s' % (str(gameid), str(gameversion)), 60*60)
if cache:
cachedata = json.loads(cache)
return cachedata
url = 'http://api.steampowered.com/ISteamApps/UpToDateCheck/v1?appId={0}&version={1}'.format(gameid, gameversion)
try:
response = urlopen(url)
data = response.read().decode('utf-8')
jsondata = json.loads(data)
if 'response' in jsondata:
jsondata = jsondata['response']
except HTTPError:
jsondata = None
if jsondata:
if CACHE:
cache = Caching.writeCache('serverupdate', '%s-%s' % (str(gameid), str(gameversion)), json.dumps(jsondata))
return jsondata
return None
def getMultipleUserOwnedGames(self, steamids):
futures = dict()
for steamid in steamids:
futures[steamid] = executor.submit(self.getOwnedGames, steamid)
result = dict()
for steamid in steamids:
result[steamid] = futures[steamid].result()
return result
def getDataForPremadefinder(self, steamids):
futures = dict()
futures['profiles'] = executor.submit(self.getProfiles, steamids)
futures['ownedGames'] = dict()
futures['userstats'] = dict()
futures['friends'] = dict()
for steamid in steamids:
futures['ownedGames'][steamid] = executor.submit(self.getOwnedGames, steamid)
futures['userstats'][steamid] = executor.submit(self.getUserstatsForGame, steamid, 730)
futures['friends'][steamid] = executor.submit(self.getFriends, steamid)
profiles = futures['profiles'].result()
for steamid in profiles:
profiles[steamid]['_friends'] = futures['friends'][steamid].result()
profiles[steamid]['_userstats'] = futures['userstats'][steamid].result()
profiles[steamid]['_ownedGames'] = futures['ownedGames'][steamid].result()
profiles[steamid]['_ownedPlayedGames'] = 'n/a'
if profiles[steamid]['_ownedGames']:
profiles[steamid]['_ownedPlayedGames'] = len([game for game in profiles[steamid]['_ownedGames']['games'] if game['playtime_forever'] > 0])
return profiles
if __name__ == "__main__":
# TODO(andre): Maybe run tests here?
print('This is a module.')
|