-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecker.py
196 lines (153 loc) · 8.6 KB
/
checker.py
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
import json, os, getopt
import requests as rq
from copy import deepcopy
class Checker:
def __init__(self, args):
self.parseArguments(args)
def runPipeline(self):
'''
Function for running the main checker pipeline. Checks for arguments and if any are present, appropriate action is taken, like displaying help or
updating config file. If no arguments are provided, a check will be run.
Returns None or a list consisting of check results. The list will either be empty if no new achievements were found or will contain dicts with
keys being emails assigned to particular checks and values being a list of strings disclosing game name and the number of new achievements.
'''
# load config file #
try:
with open('config.json') as config_file:
self.config = json.load(config_file)
except:
raise Exception("Error when loading config file. Please download config template from the repo. You can edit it using text editor or using commands.")
# check for cached app data #
if not os.path.exists("appdata.json"):
with open("appdata.json", "w") as appdata_file:
json.dump({}, appdata_file, indent=4)
with open('appdata.json') as appdata_file:
self.appdata = json.load(appdata_file)
if (len(self.arguments) == 0):
check_results = self.runChecks()
return check_results
# print help if needed #
if any([x in self.arguments.keys() for x in ('h', 'help')]):
self.printHelp()
return None
# execute general set commands if any #
if any([x in self.arguments.keys() for x in ("set_steam_api_key", "set_provider_email_adress")]):
for set_command in ("set_steam_api_key", "set_provider_email_adress"):
if set_command in self.arguments.keys():
self.config['general'][set_command.replace("set_", "")] = self.arguments[set_command]
self.writeConfig()
print("General config updated.")
return None
# create new check #
if "create_check" in self.arguments.keys():
if any([x not in self.arguments.keys() for x in ('check_name', 'check_email', 'check_games')]):
raise Exception("Error creating check, check_name, check_email and check_games must be provided.")
self.createCheck(self.arguments['check_name'], self.arguments['check_email'], self.arguments['check_games'])
return None
if "remove_check" in self.arguments.keys():
if "check_name" not in self.arguments.keys():
raise Exception("To remove check you need to provide name.")
self.removeCheck(self.arguments['check_name'])
return None
def printHelp(self):
print(
'''
This is a simple script for checking whether the number of achievements for games of interest have changed. If no commands are provided all checks will be run.
More information can be found in the README file.
Available commands:
-h, --help: Prints help information.
Commands for setting general configuration:
--set_steam_api_key [key]: Sets your steam API key.
--set_provider_email_adress [email]: Sets your email provider adress.
Commands for managing checks:
--create_check: Creates new check. Must provide --check_name, --check_email and --check_games.
--remove_check: Removes existing check. Must provide --check_name.
'''
)
def writeConfig(self):
with open('config.json', 'w') as config_file:
json.dump(self.config, config_file, indent=4)
def writeAppdata(self):
with open("appdata.json", 'w') as appdata_file:
json.dump(self.appdata, appdata_file, indent=4)
def parseArguments(self, args):
optlist, args = getopt.getopt(args,
'h', ['help',
"set_steam_api_key=", "set_provider_email_adress=",
"create_check", "remove_check",
"check_name=", "check_email=", "check_games="])
arguments = {o[0].replace("-", ""): o[1] for o in optlist}
self.arguments = arguments
def createCheck(self, name, email, games):
if name in self.config['checks'].keys():
raise Exception(f'Check with the name {name} already exists.')
self.config['checks'][name] = {
'email': email,
'games': [game.strip() for game in games.split(",")]
}
self.writeConfig()
print("Check created.")
def removeCheck(self, name):
if name not in self.config['checks'].keys():
raise Exception(f'Check with name {name} does not exist.')
del self.config['checks'][name]
self.writeConfig()
print("Check removed.")
def runChecks(self):
updated_appdata = deepcopy(self.appdata)
checks_with_new_achievements = {}
for check in self.config['checks'].values():
games_with_new_achievements = []
missing_game_data = [game for game in check['games'] if game not in self.appdata.keys()]
# check for missing appids #
if len(missing_game_data) != 0:
print(f"Downloading app_id for {', '.join(missing_game_data)}")
resp = rq.get('https://api.steampowered.com/ISteamApps/GetAppList/v2/')
if resp.status_code != 200:
print(resp)
raise Exception("Error downloading appdata from Steam API")
full_appdata = resp.json()['applist']['apps']
missing_appdata = [x for x in full_appdata if x['name'] in missing_game_data]
# check if appids for all missing games were downloaded #
if len(missing_appdata) != len(missing_game_data):
fetched_names = [x['name'] for x in missing_appdata]
missing_names = [x for x in missing_game_data if x not in fetched_names]
print(f"Warning: data for the following games not found in the Steam API. Make sure the names are correct: {', '.join(missing_names)}")
# save downloaded appdata #
for game in missing_appdata:
self.appdata[game['name']] = {
'appid': str(game['appid']),
'n_achievements': None
}
self.writeAppdata()
# go over games and download current number of achievements #
for game in check['games']:
if game not in self.appdata.keys():
print(f"Skipping {game}, no appid found")
continue
# fetch new data from Steam API #
resp = rq.get(f"https://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/?key={self.config['general']['steam_api_key']}&appid={self.appdata[game]['appid']}")
if resp.status_code != 200:
print(resp)
print(f"Warning: failed to fetch game data for {game['name']}.")
continue
data = resp.json()
if 'availableGameStats' not in data['game']:
print(f"Warning: no game stats found for {game}")
n_achievements = 0
elif 'achievements' not in data['game']['availableGameStats']:
print(f"Warning: no achievements found for {game}")
n_achievements = 0
else:
n_achievements = len(data['game']['availableGameStats']['achievements'])
if not self.appdata[game]['n_achievements']:
updated_appdata[game]['n_achievements'] = n_achievements
elif self.appdata[game]['n_achievements'] != n_achievements:
games_with_new_achievements.append(f"{game} has {n_achievements - self.appdata[game]['n_achievements']} new achievements.")
updated_appdata[game]['n_achievements'] = n_achievements
# if any new achievements are present, add to results list #
if games_with_new_achievements:
checks_with_new_achievements[check['email']] = games_with_new_achievements
self.appdata = updated_appdata
self.writeAppdata()
return checks_with_new_achievements