· 6 years ago · Apr 04, 2020, 05:56 PM
1import configparser
2import operator
3import os
4import webbrowser
5from datetime import datetime, timedelta
6from time import time, sleep
7
8import pushbullet
9import pyperclip
10import pytesseract
11import requests
12import win32api
13import win32con
14import win32gui
15from PIL import ImageGrab, Image
16from playsound import playsound
17
18
19def Avg(lst: list):
20 return sum(lst) / len(lst)
21
22
23# noinspection PyShadowingNames
24def enum_cb(hwnd, results):
25 winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
26
27
28# noinspection PyShadowingNames
29def write(message, add_time: bool = True, push: int = 0, push_now: bool = False, output: bool = True):
30 if add_time:
31 m = datetime.now().strftime('%H:%M:%S') + ': ' + str(message)
32 else:
33 m = message
34 if output:
35 print(m)
36
37 if push >= 3:
38 global note
39 if message:
40 note = note + m + '\n'
41 if push_now:
42 device.push_note('CSGO AUTO ACCEPT', note)
43 note = ''
44
45
46# noinspection PyShadowingNames
47def click(x: int, y: int):
48 win32api.SetCursorPos((x, y))
49 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
50 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
51
52
53# noinspection PyShadowingNames
54def relate_list(l_org, l1, l2=None, relate: operator = operator.le):
55 if not l_org:
56 return False
57 truth_list, l3 = [], []
58 for i, val in enumerate(l1, start=0):
59 l3.append(relate(l_org[i], val))
60 truth_list.append(all(l3))
61 l3 = []
62 if l2:
63 for i, val in enumerate(l2, start=len(l1)):
64 l3.append(relate(l_org[i], val))
65 truth_list.append(all(l3))
66 return any(truth_list)
67
68
69# noinspection PyShadowingNames
70def color_average(image: Image, compare_list: list):
71 average = []
72 r, g, b = [], [], []
73 data = image.getdata()
74 for i in data:
75 r.append(i[0])
76 g.append(i[1])
77 b.append(i[2])
78
79 rgb = [Avg(r), Avg(g), Avg(b)] * int(len(compare_list) / 3)
80 for i, val in enumerate(compare_list, start=0):
81 average.append(val - rgb[i])
82 average = list(map(abs, average))
83
84 return average
85
86
87# noinspection PyShadowingNames
88def getScreenShot(window_id: int, area: tuple = (0, 0, 0, 0)):
89 area = list(area)
90 win32gui.ShowWindow(window_id, win32con.SW_MAXIMIZE)
91 scaled_area = [screen_width / 2560, screen_height / 1440]
92 scaled_area = 2 * scaled_area
93 for i, _ in enumerate(area[-2:], start=len(area) - 2):
94 area[i] += 1
95 for i, val in enumerate(area, start=0):
96 scaled_area[i] = scaled_area[i] * val
97 scaled_area = list(map(int, scaled_area))
98 image = ImageGrab.grab(scaled_area)
99 return image
100
101
102# noinspection PyShadowingNames
103def getAccountsFromCfg():
104 steam_ids = ''
105 for i in config.sections():
106 if i.startswith('Account'):
107 steam_id = config.get(i, 'Steam ID')
108 auth_code = config.get(i, 'Authentication Code')
109 match_token = config.get(i, 'Match Token')
110 steam_ids += steam_id + ','
111 accounts.append({'steam_id': steam_id, 'auth_code': auth_code, 'match_token': match_token})
112
113 steam_ids = steam_ids.lstrip(',').rstrip(',')
114 profiles = requests.get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + cfg['steam_api_key'] + '&steamids=' + steam_ids).json()['response']['players']
115 for i in profiles:
116 for n in accounts:
117 if n['steam_id'] == i['steamid']:
118 n['name'] = i['personaname']
119 break
120
121
122# noinspection PyShadowingNames
123def getOldSharecodes(num: int = -1):
124 try:
125 last_game = open('last_game_' + accounts[current_account]['steam_id'] + '.txt', 'r')
126 games = last_game.readlines()
127 last_game.close()
128 except FileNotFoundError:
129 last_game = open('last_game_' + accounts[current_account]['steam_id'] + '.txt', 'w')
130 last_game.write(accounts[current_account]['match_token'] + '\n')
131 games = [accounts[current_account]['match_token']]
132 last_game.close()
133 last_game = open('last_game_' + accounts[current_account]['steam_id'] + '.txt', 'w')
134 games = games[-200:]
135 for i, val in enumerate(games):
136 games[i] = 'CSGO' + val.strip('\n').split('CSGO')[1]
137 last_game.write(games[i] + '\n')
138 last_game.close()
139 return games[num:]
140
141
142# noinspection PyShadowingNames
143def getNewCSGOMatches(game_id: str):
144 sharecodes = []
145 next_code = game_id
146 last_game = open('last_game_' + accounts[current_account]['steam_id'] + '.txt', 'a')
147 while next_code != 'n/a':
148 steam_url = 'https://api.steampowered.com/ICSGOPlayers_730/GetNextMatchSharingCode/v1?key=' + cfg['steam_api_key'] + '&steamid=' + accounts[current_account]['steam_id'] + '&steamidkey=' + accounts[current_account][
149 'auth_code'] + '&knowncode=' + game_id
150 try:
151 next_code = (requests.get(steam_url).json()['result']['nextcode'])
152 except KeyError:
153 write('WRONG Match Token, Authentication Code or Steam ID ')
154 return [game_id]
155
156 if next_code:
157 if next_code != 'n/a':
158 sharecodes.append(next_code)
159 game_id = next_code
160 last_game.write(next_code + '\n')
161 if sharecodes:
162 return sharecodes
163 else:
164 return [game_id]
165
166
167# noinspection PyShadowingNames
168def UpdateCSGOstats(sharecodes: list, num_completed: int = 1):
169 completed_games, not_completed_games, = [], []
170 for val in sharecodes:
171 response = requests.post('https://csgostats.gg/match/upload/ajax', data={'sharecode': val, 'index': '1'})
172 if response.json()['status'] == 'complete':
173 completed_games.append(response.json())
174 else:
175 not_completed_games.append(response.json())
176
177 # TEST GAME:
178 # completed_games = [{'status': 'complete', 'data': {'msg': 'Complete - <a href='/match/7584322'>View</a>', 'index': '1', 'sharecode': 'CSGO-7NiMO-RPjvj-MZNWP-9cRdx-vzYUN', 'queue_id': 8081108, 'demo_id': 7584322, 'url': 'https://csgostats.gg/match/7584322'}, 'error': 0}]
179 # not_completed_games = [{'status': 'queued', 'data': {'msg': 'in Queue #991 <span style='margin-left:8px;'></span> ~ Time Remaining 6h 54m', 'queue_id': 8391726, 'queue_pos': 991, 'in_queue': 1, 'demo_id': 0, 'url': 'https://csgostats.gg/match/processing/8391726', 'demo_url': '', 'start': False, 'index': '1', 'sharecode': 'CSGO-oL3Rt-2LudR-ELHsy-7yHRS-DmAEB'}, 'error': 0}, {'status': 'queued', 'data': {'msg': 'in Queue #1542 <span style='margin-left:8px;'></span> ~ Time Remaining 10h 43m 35s', 'queue_id': 8392294, 'queue_pos': 1542, 'in_queue': 1, 'demo_id': 0, 'url': 'https://csgostats.gg/match/processing/8392294', 'demo_url': '', 'start': False, 'index': '1', 'sharecode': 'CSGO-AEW5S-OXzc4-nqxkC-LhCYS-UnkjD'}, 'error': 0}, {'status': 'retrying', 'data': {'msg': 'Failed to parse demo file. Demo may be corrupt<br />Retrying, in Queue #89 <span style='margin-left:8px;'></span> ~ Time Remaining 38m 10s', 'queue_id': 8198239, 'queue_pos': 89, 'in_queue': 1, 'demo_id': 0, 'url': 'https://csgostats.gg/match/processing/8198239', 'demo_url': 'http://replay193.valve.net/730/003404294621881172683_0361751166.dem.bz2', 'start': False, 'index': '1', 'sharecode': 'CSGO-nWQrk-2Orsq-RUQtE-yXjLC-OA7dK'}, 'error': 2}, {'status': 'error', 'data': {'msg': 'Complete - <a href='/match/7584322'>View</a>', 'index': '1', 'sharecode': 'CSGO-7NiMO-RPjvj-MZNWP-9cRdx-vzYUN', 'queue_id': 8081108, 'demo_id': 7584322, 'url': 'https://csgostats.gg/match/7584322'}, 'error': 0}]
180
181 queued_games = [game['data']['queue_pos'] for game in not_completed_games if game['status'] != 'error']
182 global retrying_games
183 retrying_games = []
184
185 if queued_games:
186 if queued_games[0] < cfg['max_queue_position']:
187 global error_check_time
188 retrying_games = [game['data']['sharecode'] for game in not_completed_games]
189 error_check_time = time()
190 for i, val in enumerate(queued_games):
191 write('#%s: in Queue #%s.' % (i + 1, val), add_time=False)
192
193 if len(not_completed_games) - len(queued_games) > 0:
194 write('An error occurred in %s game[s].' % (len(not_completed_games) - len(queued_games)), add_time=False)
195 retrying_games.append([game['data']['sharecode'] for game in not_completed_games])
196
197 if completed_games:
198 for i in completed_games[num_completed * - 1:]:
199 sharecode = i['data']['sharecode']
200 game_url = i['data']['url']
201 info = ' '.join(i['data']['msg'].replace('-', '').replace('<br />', '. ').split('<')[0].rstrip(' ').split())
202 write('Sharecode: %s' % sharecode, add_time=False, push=push_urgency)
203 write('URL: %s' % game_url, add_time=False, push=push_urgency)
204 write('Status: %s.' % info, add_time=False, push=push_urgency)
205 pyperclip.copy(game_url)
206 write(None, add_time=False, push=push_urgency, push_now=True, output=False)
207
208
209# noinspection PyShadowingNames
210def Image_to_Text(image: Image, size: tuple, white_threshold: list, arg: str = ''):
211 image_data = image.getdata()
212 pixel_map, image_text = [], ''
213 for y in range(size[1]):
214 for x in range(size[0]):
215 if relate_list(image_data[y * size[0] + x], white_threshold, relate=operator.ge):
216 pixel_map.append((0, 0, 0))
217 else:
218 pixel_map.append((255, 255, 255))
219 temp_image = Image.new('RGB', (size[0], size[1]))
220 temp_image.putdata(pixel_map)
221 # temp_image.save('inv.png')
222 # image.save('org.png')
223 try:
224 image_text = pytesseract.image_to_string(temp_image, timeout=0.3, config=arg)
225 except RuntimeError as timeout_error:
226 pass
227 if image_text:
228 return ' '.join(image_text.replace(': ', ':').split())
229 else:
230 return False
231
232
233def getCfgData():
234 try:
235 get_cfg = {'activate_script': int(config.get('HotKeys', 'Activate Script'), 16), 'activate_push_notification': int(config.get('HotKeys', 'Activate Push Notification'), 16),
236 'info_newest_match': int(config.get('HotKeys', 'Get Info on newest Match'), 16), 'info_multiple_matches': int(config.get('HotKeys', 'Get Info on multiple Matches'), 16),
237 'open_live_tab': int(config.get('HotKeys', 'Live Tab Key'), 16), 'switch_accounts': int(config.get('HotKeys', 'Switch accounts for csgostats.gg'), 16), 'stop_warmup_ocr': int(config.get('HotKeys', 'Stop Warmup OCR'), 16),
238 'end_script': int(config.get('HotKeys', 'End Script'), 16),
239 'screenshot_interval': config.getint('Screenshot', 'Interval'), 'steam_api_key': config.get('csgostats.gg', 'API Key'), 'last_x_matches': config.getint('csgostats.gg', 'Number of Requests'),
240 'completed_matches': config.getint('csgostats.gg', 'Completed Matches'), 'max_queue_position': config.getint('csgostats.gg', 'Auto-Retrying for queue position below'),
241 'auto_retry_interval': config.getint('csgostats.gg', 'Auto-Retrying-Interval'), 'pushbullet_device_name': config.get('Pushbullet', 'Device Name'), 'pushbullet_api_key': config.get('Pushbullet', 'API Key'),
242 'tesseract_path': config.get('Warmup', 'Tesseract Path'), 'warmup_test_interval': config.getint('Warmup', 'Test Interval'), 'warmup_push_interval': config.get('Warmup', 'Push Interval'),
243 'warmup_no_text_limit': config.getint('Warmup', 'No Text Limit')}
244 return get_cfg
245 # 'imgur_id': config.get('Imgur', 'Client ID'), 'imgur_secret': config.get('Imgur', 'Client Secret'),
246 except (configparser.NoOptionError, configparser.NoSectionError, ValueError):
247 write('ERROR IN CONFIG')
248 exit('CHECK FOR NEW CONFIG')
249
250
251# CONFIG HANDLING
252config = configparser.ConfigParser()
253config.read('config.ini')
254cfg = getCfgData()
255device = 0
256
257# ACCOUNT HANDLING, GETTING ACCOUNT NAME
258accounts, current_account = [], 0
259getAccountsFromCfg()
260
261# INITIALIZATION FOR getScreenShot
262screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
263toplist, winlist = [], []
264hwnd = 0
265
266# BOOLEAN INITIALIZATION
267test_for_live_game, test_for_success, push_urgency, test_for_warmup, testing = False, False, False, False, False
268
269# csgostats.gg VAR
270retrying_games = []
271
272# WARMUP DETECTION SETUP
273pytesseract.pytesseract.tesseract_cmd = cfg['tesseract_path']
274push_times, no_text_found, push_counter = [], [], 0
275for i in cfg['warmup_push_interval'].split(','):
276 push_times.append(int(i))
277push_times.sort(reverse=True)
278
279# PUSHBULLET VAR
280note = ''
281
282# INITIALIZATION OF TIME VARS
283screenshot_time, error_check_time, warmup_test_timer, warmup_push_timer = time(), time(), time(), time()
284
285write('READY')
286write('Current account is: %s\n' % accounts[current_account]['name'], add_time=False)
287
288while True:
289 if win32api.GetAsyncKeyState(cfg['activate_script']) & 1: # F9 (ACTIVATE / DEACTIVATE SCRIPT)
290 test_for_live_game = not test_for_live_game
291 write('TESTING: %s' % test_for_live_game)
292 if test_for_live_game:
293 playsound('sounds/activated_2.mp3')
294 time_searching = time()
295 else:
296 playsound('sounds/deactivated.mp3')
297
298 if win32api.GetAsyncKeyState(cfg['activate_push_notification']) & 1: # F8 (ACTIVATE / DEACTIVATE PUSH NOTIFICATION)
299 if not device:
300 try:
301 device = pushbullet.PushBullet(cfg['pushbullet_api_key']).get_device(cfg['pushbullet_device_name'])
302 except (pushbullet.errors.PushbulletError, pushbullet.errors.InvalidKeyError):
303 write('Pushbullet is wrongly configured.\nWrong API Key or DeviceName in config.ini')
304 if device:
305 push_urgency += 1
306 if push_urgency > 3:
307 push_urgency = 0
308 push_info = ['not active', 'only if accepted', 'all game status related information', 'all information (game status/csgostats.gg information)']
309 write('Pushing: %s' % push_info[push_urgency])
310
311 if win32api.GetAsyncKeyState(cfg['info_newest_match']) & 1: # F7 Key (UPLOAD NEWEST MATCH)
312 write('Uploading / Getting status on newest match')
313 UpdateCSGOstats(getNewCSGOMatches(getOldSharecodes()[0]))
314
315 if win32api.GetAsyncKeyState(cfg['info_multiple_matches']) & 1: # F6 Key (GET INFO ON LAST X MATCHES)
316 write('Getting Info from last %s matches' % cfg['last_x_matches'])
317 # write('Outputting %s completed match[es]' % completed_matches, add_time=False)
318 getNewCSGOMatches(getOldSharecodes()[0])
319 UpdateCSGOstats(getOldSharecodes(num=cfg['last_x_matches'] * -1), num_completed=cfg['completed_matches'])
320
321 if win32api.GetAsyncKeyState(cfg['open_live_tab']) & 1: # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
322 win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
323 webbrowser.open_new_tab('https://csgostats.gg/player/' + accounts[current_account]['steam_id'] + '#/live')
324 write('new tab opened', add_time=False)
325 sleep(0.5)
326 win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
327
328 if win32api.GetAsyncKeyState(cfg['switch_accounts']) & 1: # F15 (SWITCH ACCOUNTS)
329 current_account += 1
330 if current_account > len(accounts) - 1:
331 current_account = 0
332 write('current account is: %s' % accounts[current_account]['name'], add_time=False)
333
334 if win32api.GetAsyncKeyState(cfg['stop_warmup_ocr']) & 1: # ESC (STOP WARMUP OCR)
335 write('STOPPING WARMUP TIME FINDER!')
336 test_for_warmup = False
337 no_text_found = []
338 warmup_push_timer, warmup_test_timer = time(), time()
339
340 if win32api.GetAsyncKeyState(cfg['end_script']) & 1: # POS1 (END SCRIPT)
341 write('Exiting Script')
342 break
343
344 if retrying_games:
345 if time() - error_check_time > cfg['auto_retry_interval']:
346 error_check_time = time()
347 UpdateCSGOstats(retrying_games, num_completed=len(retrying_games))
348
349 winlist = []
350 win32gui.EnumWindows(enum_cb, toplist)
351 csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
352
353 # ONLY CONTINUING IF CSGO IS RUNNING
354 if not csgo:
355 continue
356 hwnd = csgo[0][0]
357
358 # TESTING HERE
359 if win32api.GetAsyncKeyState(0x74) & 1: # UNBOUND, TEST CODE
360 print('\n')
361 write('Executing TestCode')
362 print('\n')
363 # testing = not testing
364 push_counter = 0
365 test_for_warmup = True
366 warmup_test_timer, warmup_push_timer = time(), time()
367
368 if testing:
369 # screenshot_time = time()
370 pass
371 # print('Took: %s ' % str(timedelta(milliseconds=int(time()*1000 - screenshot_time*1000))))
372 # TESTING ENDS HERE
373
374 if test_for_live_game:
375 if time() - screenshot_time < cfg['screenshot_interval']:
376 continue
377 screenshot_time = time()
378 img = getScreenShot(hwnd, (1265, 760, 1295, 785))
379 if not img:
380 continue
381 accept_avg = color_average(img, [76, 176, 80, 90, 203, 95])
382
383 if relate_list(accept_avg, [1, 2, 1], l2=[1, 1, 2]):
384 write('Trying to Accept', push=push_urgency + 1)
385
386 test_for_success = True
387 test_for_live_game = False
388 accept_avg = []
389
390 for _ in range(5):
391 click(int(screen_width / 2), int(screen_height / 1.78))
392
393 write('Trying to catch a loading map')
394 playsound('sounds/accept_found.mp3')
395 screenshot_time = time()
396
397 if test_for_success:
398 if time() - screenshot_time < 40:
399 img = getScreenShot(hwnd, (2435, 65, 2555, 100))
400 not_searching_avg = color_average(img, [6, 10, 10])
401 searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
402
403 not_searching = relate_list(not_searching_avg, [2, 5, 5])
404 searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
405
406 img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
407 success_avg = color_average(img, [21, 123, 169])
408 success = relate_list(success_avg, [1, 8, 7])
409
410 if success:
411 write('Took %s since pressing accept.' % str(timedelta(seconds=int(time() - screenshot_time))), add_time=False, push=push_urgency + 1)
412 write('Took %s since trying to find a game.' % str(timedelta(seconds=int(time() - time_searching))), add_time=False, push=push_urgency + 1)
413 write('Game should have started', push=push_urgency + 2, push_now=True)
414 test_for_success = False
415 test_for_warmup = True
416 playsound('sounds/done_testing.mp3')
417 warmup_test_timer, warmup_push_timer = time()+5, time()+5
418
419 if any([searching, not_searching]):
420 write('Took: %s ' % str(timedelta(seconds=int(time() - screenshot_time))), add_time=False, push=push_urgency + 1)
421 write('Game doesnt seem to have started. Continuing to search for accept Button!', push=push_urgency + 1, push_now=True)
422 playsound('sounds/back_to_testing.mp3')
423 test_for_success = False
424 test_for_live_game = True
425
426 else:
427 write('40 Seconds after accept, did not find loading map nor searching queue')
428 test_for_success = False
429 print(success_avg)
430 print(searching_avg)
431 print(not_searching_avg)
432 playsound('sounds/fail.mp3')
433 img.save(os.path.expanduser('~') + '\\Unknown Error.png')
434
435 if test_for_warmup:
436 if time() - warmup_test_timer >= cfg['warmup_test_interval']:
437 img = getScreenShot(hwnd, (1036, 425, 1525, 456)) # 'WAITING FOR PLAYERS X:XX'
438 img_text = Image_to_Text(img, img.size, [225, 225, 225], arg='--psm 6')
439 warmup_test_timer = time()
440 if img_text:
441 time_left = img_text.split()[-1].split(':')
442 write(img_text, add_time=False)
443 try:
444 time_left = int(time_left[0]) * 60 + int(time_left[1])
445 except ValueError:
446 time_left = push_times[0] + 1
447 if time_left <= push_times[push_counter]:
448 push_counter += 1
449 write(img_text, add_time=True, push=push_urgency + 1, output=False, push_now=True)
450 else:
451 no_text_found.append(True)
452
453 if push_counter >= len(push_times):
454 write('Warmup should be over in less then %s seconds!' % push_times[-1], push=push_urgency + 1, push_now=True)
455 push_counter = 0
456 no_text_found = []
457 test_for_warmup = False
458
459 if len(no_text_found) >= cfg['warmup_no_text_limit']:
460 push_counter = 0
461 no_text_found = []
462 test_for_warmup = False
463 write('Did not find any warmup text.', push=push_urgency + 1, push_now=True)
464
465exit('ENDED BY USER')