· 6 years ago · Apr 22, 2020, 03:14 PM
1import configparser
2import operator
3import os
4import re
5import sys
6import time
7import webbrowser
8import winreg
9from datetime import datetime, timedelta
10
11import pushbullet
12import pyperclip
13import pytesseract
14import requests
15import win32api
16import win32con
17import win32gui
18from PIL import ImageGrab, Image
19from playsound import playsound
20
21
22def Avg(lst: list):
23 if not lst:
24 return 0
25 return sum(lst) / len(lst)
26
27
28# noinspection PyShadowingNames,PyUnusedLocal
29def enum_cb(hwnd, results):
30 winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
31
32
33# noinspection PyShadowingNames
34def write(message, add_time: bool = True, push: int = 0, push_now: bool = False, output: bool = True, overwrite: str = '0'):
35 if output:
36 message = str(message)
37 if add_time:
38 message = datetime.now().strftime('%H:%M:%S') + ': ' + message
39 global last_printed_line
40 splits = last_printed_line.split(b'**')
41 last_key = splits[0]
42 last_string = splits[1].strip(b'\n\r')
43 last_end = splits[-1]
44 if overwrite != '0':
45 ending = console_window['suffix']
46 if last_key == overwrite.encode():
47 if console_window['isatty']:
48 print(' ' * len(last_string.decode()), end=ending)
49 message = console_window['prefix'] + message
50 else:
51 if last_end != b'\n':
52 message = '\n' + message
53 else:
54 ending = '\n'
55 if last_end != b'\n':
56 message = '\n' + message
57
58 last_printed_line = (overwrite + '**' + message + '**' + ending).encode()
59 print(message, end=ending)
60
61 if push >= 3:
62 global note
63 if message:
64 note = note + str(message.strip('\n\r')) + '\n'
65 if push_now:
66 device.push_note('CSGO AUTO ACCEPT', note)
67 note = ''
68
69
70# noinspection PyShadowingNames
71def click(x: int, y: int):
72 win32api.SetCursorPos((x, y))
73 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
74 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
75
76
77# noinspection PyShadowingNames
78def relate_list(l_org, compare_list, relate: operator = operator.le):
79 if not l_org:
80 return False
81 truth_list = []
82 for list_part in compare_list:
83 partial_truth = []
84 for i, val in enumerate(list_part):
85 partial_truth.append(relate(l_org[i], val))
86 truth_list.append(all(partial_truth))
87 l_org = l_org[len(list_part):]
88 return any(truth_list)
89
90
91# noinspection PyShadowingNames
92def color_average(image: Image, compare_list: list):
93 average = []
94 r, g, b = [], [], []
95 data = image.getdata()
96 for i in data:
97 r.append(i[0])
98 g.append(i[1])
99 b.append(i[2])
100
101 rgb = [Avg(r), Avg(g), Avg(b)] * len(compare_list)
102 for part in compare_list:
103 for i, val in enumerate(part):
104 average.append(val - rgb[i])
105 average = list(map(abs, average))
106 return average
107
108
109# noinspection PyShadowingNames
110def getScreenShot(window_id: int, area: tuple = (0, 0, 0, 0)):
111 area = list(area)
112 win32gui.ShowWindow(window_id, win32con.SW_MAXIMIZE)
113 scaled_area = [screen_width / 2560, screen_height / 1440]
114 scaled_area = 2 * scaled_area
115 for i, _ in enumerate(area[-2:], start=len(area) - 2):
116 area[i] += 1
117 for i, val in enumerate(area, start=0):
118 scaled_area[i] = scaled_area[i] * val
119 scaled_area = list(map(int, scaled_area))
120 image = ImageGrab.grab(scaled_area)
121 return image
122
123
124# noinspection PyShadowingNames
125def getAccountsFromCfg():
126 steam_ids = ''
127 global accounts
128 for i in config.sections():
129 if i.startswith('Account'):
130 steam_id = config.get(i, 'Steam ID')
131 steam_id_3 = str(int(steam_id) - 76561197960265728)
132 auth_code = config.get(i, 'Authentication Code')
133 match_token = config.get(i, 'Match Token')
134 steam_ids += steam_id + ','
135 accounts.append({'steam_id': steam_id, 'steam_id_3': steam_id_3, 'auth_code': auth_code, 'match_token': match_token})
136
137 steam_ids = steam_ids.lstrip(',').rstrip(',')
138 profiles = requests.get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + cfg['steam_api_key'] + '&steamids=' + steam_ids).json()['response']['players']
139 name_list = [online_data['personaname'] for local_acc in accounts for online_data in profiles if online_data['steamid'] == local_acc['steam_id']]
140 for num, val in enumerate(accounts):
141 val['name'] = name_list[num]
142
143
144# noinspection PyShadowingNames
145def getCsgoPath(steam_id_3: str):
146 steam_reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\WOW6432Node\Valve\Steam')
147 steam_path = winreg.QueryValueEx(steam_reg_key, 'InstallPath')[0]
148 libraries = [steam_path + '\\steamapps']
149 with open(steam_path + '\\steamapps\\libraryfolders.vdf', 'r') as library_file:
150 library_data = library_file.readlines()
151 compare_str = re.compile('\\t"\d*"\\t\\t"')
152 libraries.extend([re.sub(compare_str, "", i.rstrip('"\n')) for i in library_data if bool(re.match(compare_str, i))])
153
154 csgo_path = [i for i in libraries if os.path.exists(i + '\\appmanifest_730.acf')][0] + '\\common\\Counter-Strike Global Offensive\\csgo\\'
155 if not csgo_path:
156 write('DID NOT FIND CSGO PATH', add_time=False)
157 exit('LORD PLZ HELP')
158
159 userdata_path = steam_path + '\\userdata\\' + steam_id_3 + '\\730\\local\\cfg\\'
160 with open(userdata_path + 'autoexec.cfg', 'a+') as autoexec:
161 autoexec.seek(0)
162 lines = autoexec.readlines()
163 if 'con_logfile "console_log.log"' not in [line.rstrip('\n') for line in lines]:
164 write('ADDED CONSOLE LOGGING OUTPUT TO "autoexec.cfg" FILE IN %s' % userdata_path, add_time=False)
165 write('YOU HAVE TO RESTART Counter-Strike FOR THE SCRIPT TO WORK', add_time=False)
166 autoexec.write('\ncon_logfile "console_log.log"\n')
167 if os.path.exists(csgo_path + '\\cfg\\autoexec.cfg'):
168 write('YOU HAVE TO DELETE THE "autoexec.cfg" in %s WITH AND MERGE IT WITH THE ONE IN %s' % (csgo_path + '\\cfg', userdata_path), add_time=False)
169 write('THE SCRIPT WONT WORK UNTIL THERE IS NO "autoexec.cfg" in %s' % csgo_path + '\\cfg', add_time=False)
170 exit()
171 return csgo_path
172
173
174# noinspection PyShadowingNames
175def getOldSharecodes(last_x: int = -1, from_x: str = ''):
176 if last_x >= 0:
177 return []
178 try:
179 last_game = open(appdata_path+'last_game_' + accounts[current_account]['steam_id'] + '.txt', 'r')
180 games = last_game.readlines()
181 last_game.close()
182 except FileNotFoundError:
183 last_game = open(appdata_path+'last_game_' + accounts[current_account]['steam_id'] + '.txt', 'w')
184 last_game.write(accounts[current_account]['match_token'] + '\n')
185 games = [accounts[current_account]['match_token']]
186 last_game.close()
187 last_game = open(appdata_path+'last_game_' + accounts[current_account]['steam_id'] + '.txt', 'w')
188 games = games[-200:]
189 for i, val in enumerate(games):
190 games[i] = 'CSGO' + val.strip('\n').split('CSGO')[1]
191 last_game.write(games[i] + '\n')
192 last_game.close()
193 if from_x:
194 try:
195 return games[(len(games) - games.index(from_x)) * -1:]
196 except ValueError:
197 return []
198 return games[last_x:]
199
200
201# noinspection PyShadowingNames
202def getNewCSGOSharecodes(game_id: str):
203 sharecodes = []
204 next_code = game_id
205 last_game = open(appdata_path+'last_game_' + accounts[current_account]['steam_id'] + '.txt', 'a')
206 while next_code != 'n/a':
207 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][
208 'auth_code'] + '&knowncode=' + game_id
209 try:
210 next_code = (requests.get(steam_url).json()['result']['nextcode'])
211 except KeyError:
212 write('WRONG Match Token, Authentication Code or Steam ID ')
213 return [{'sharecode': game_id, 'queue_pos': None}]
214
215 if next_code:
216 if next_code != 'n/a':
217 sharecodes.append(next_code)
218 game_id = next_code
219 last_game.write(next_code + '\n')
220 last_game.close()
221 return [{'sharecode': code, 'queue_pos': None} for code in sharecodes]
222
223
224# noinspection PyShadowingNames
225def UpdateCSGOstats(repeater=None, get_all_games=False):
226 all_games, completed_games, not_completed_games, = [], [], []
227
228 if repeater is None:
229 repeater = []
230 if repeater:
231 if get_all_games:
232 sharecodes = [getOldSharecodes(from_x=code['sharecode']) for code in repeater]
233 sharecodes = max(sharecodes, key=len)
234 else:
235 sharecodes = [code['sharecode'] for code in repeater]
236 all_games = [requests.post('https://csgostats.gg/match/upload/ajax', data={'sharecode': sharecode, 'index': '1'}).json() for sharecode in sharecodes]
237 else:
238 num = -1
239 sharecode = getOldSharecodes(num)[0]
240 while True:
241 response = requests.post('https://csgostats.gg/match/upload/ajax', data={'sharecode': sharecode, 'index': '1'})
242 all_games.append(response.json())
243 if response.json()['status'] != 'complete':
244 num -= 1
245 try:
246 sharecode = getOldSharecodes(num)[0]
247 except IndexError:
248 break
249 else:
250 break
251 temp_games = [{'sharecode': game['data']['sharecode']} for game in all_games if game['status'] != 'complete']
252 if temp_games and len(all_games) > 1:
253 all_games = all_games[:-1]
254
255 for game in all_games:
256 if game['status'] == 'complete':
257 completed_games.append(game)
258 else:
259 not_completed_games.append(game)
260
261 queued_games = [{'sharecode': game['data']['sharecode'], 'queue_pos': game['data']['queue_pos']} for game in not_completed_games if game['status'] != 'error']
262 corrupt_games = [{'sharecode': game['data']['sharecode'], 'queue_pos': game['data']['queue_pos']} for game in not_completed_games if game['status'] == 'error']
263
264 global queue_difference, time_table
265 if queued_games:
266 temp_string = ''
267 for i, val in enumerate(queued_games):
268 temp_string += '#' + str(i + 1) + ': in Queue #' + str(val['queue_pos']) + ' - '
269
270 if repeater:
271 current_queue_difference = Avg([last_game['queue_pos'] - game['queue_pos'] for game in queued_games for last_game in repeater if last_game['sharecode'] == game['sharecode'] and last_game['queue_pos'] is not None])
272 if current_queue_difference:
273 queue_difference.append(current_queue_difference / ((time.time() - time_table['time_since_retry']) / 60))
274 queue_difference = queue_difference[-10:]
275 matches_per_min = round(Avg(queue_difference), 1)
276 if matches_per_min != 0.0:
277 time_till_done = str(timedelta(seconds=int((queued_games[0]['queue_pos'] / matches_per_min) * 60)))
278 else:
279 time_till_done = '∞:∞:∞'
280 temp_string += str(matches_per_min) + ' matches/min - #1 done in ' + time_till_done
281 temp_string = temp_string.rstrip(' - ')
282 write(temp_string, add_time=False, overwrite='4')
283
284 time_table['time_since_retry'] = time.time()
285 repeater = [game for game in queued_games if game['queue_pos'] < cfg['max_queue_position']]
286 repeater.extend([game for game in corrupt_games])
287
288 if corrupt_games:
289 write('An error occurred in %s game[s].' % len(corrupt_games), overwrite='5')
290
291 if completed_games:
292 for i in completed_games:
293 sharecode = i['data']['sharecode']
294 game_url = i['data']['url']
295 info = ' '.join(i['data']['msg'].replace('-', '').replace('<br />', '. ').split('<')[0].rstrip(' ').split())
296 write('Sharecode: %s' % sharecode, add_time=False, push=push_urgency)
297 write('URL: %s' % game_url, add_time=False, push=push_urgency)
298 write('Status: %s.' % info, add_time=True, push=push_urgency)
299 pyperclip.copy(game_url)
300 write(None, add_time=False, push=push_urgency, push_now=True, output=False)
301 return repeater
302
303
304# noinspection PyShadowingNames,PyUnusedLocal
305def Image_to_Text(image: Image, size: tuple, white_threshold: tuple, arg: str = ''):
306 image_data = image.getdata()
307 pixel_map, image_text = [], ''
308 for y in range(size[1]):
309 for x in range(size[0]):
310 if relate_list(image_data[y * size[0] + x], [white_threshold], relate=operator.ge):
311 pixel_map.append((0, 0, 0))
312 else:
313 pixel_map.append((255, 255, 255))
314 temp_image = Image.new('RGB', (size[0], size[1]))
315 temp_image.putdata(pixel_map)
316 try:
317 image_text = pytesseract.image_to_string(temp_image, timeout=0.3, config=arg)
318 except RuntimeError as timeout_error:
319 pass
320 if image_text:
321 image_text = ' '.join(image_text.replace(': ', ':').split())
322 global truth_table
323 if truth_table['debugging']:
324 image.save(str(cfg['debug_path']) + '\\' + datetime.now().strftime('%H-%M-%S') + '_' + image_text.replace(':', '-') + '.png', format='PNG')
325 temp_image.save(str(cfg['debug_path']) + '\\' + datetime.now().strftime('%H-%M-%S') + '_' + image_text.replace(':', '-') + '_temp.png', format='PNG')
326 return image_text
327 else:
328 return False
329
330
331def getCfgData():
332 try:
333 get_cfg = {'activate_script': int(config.get('HotKeys', 'Activate Script'), 16), 'activate_push_notification': int(config.get('HotKeys', 'Activate Push Notification'), 16),
334 'info_newest_match': int(config.get('HotKeys', 'Get Info on newest Match'), 16),
335 'open_live_tab': int(config.get('HotKeys', 'Live Tab Key'), 16), 'switch_accounts': int(config.get('HotKeys', 'Switch accounts for csgostats.gg'), 16),
336 'end_script': int(config.get('HotKeys', 'End Script'), 16),
337 'screenshot_interval': config.getint('Screenshot', 'Interval'), 'debug_path': config.get('Screenshot', 'Debug Path'), 'steam_api_key': config.get('csgostats.gg', 'API Key'),
338 'last_x_matches': config.getint('csgostats.gg', 'Number of Requests'),
339 'completed_matches': config.getint('csgostats.gg', 'Completed Matches'), 'max_queue_position': config.getint('csgostats.gg', 'Auto-Retrying for queue position below'),
340 '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'),
341 'tesseract_path': config.get('Warmup', 'Tesseract Path'), 'warmup_test_interval': config.getint('Warmup', 'Test Interval'), 'warmup_push_interval': config.get('Warmup', 'Push Interval'),
342 'warmup_no_text_limit': config.getint('Warmup', 'No Text Limit')}
343 return get_cfg
344 # 'imgur_id': config.get('Imgur', 'Client ID'), 'imgur_secret': config.get('Imgur', 'Client Secret'), 'stop_warmup_ocr': int(config.get('HotKeys', 'Stop Warmup OCR'), 16), 'info_multiple_matches': int(config.get('HotKeys', 'Get Info on multiple Matches'), 16),
345 except (configparser.NoOptionError, configparser.NoSectionError, ValueError):
346 write('ERROR IN CONFIG')
347 exit('CHECK FOR NEW CONFIG')
348
349
350# OVERWRITE SETUP
351appdata_path = os.getenv('APPDATA') + '\\CSGO AUTO ACCEPT\\'
352try:
353 os.mkdir(appdata_path)
354except FileExistsError:
355 pass
356last_printed_line = b'0**\n'
357console_window = {}
358if not sys.stdout.isatty():
359 console_window = {'prefix': '\r', 'suffix': '', 'isatty': False}
360else:
361 console_window = {'prefix': '', 'suffix': '\r', 'isatty': True}
362
363# CONFIG HANDLING
364config = configparser.ConfigParser()
365config.read('config.ini')
366cfg = getCfgData()
367device = 0
368
369# ACCOUNT HANDLING, GETTING ACCOUNT NAME, GETTING CSGO PATH, CHECKING AUTOEXEC
370accounts, current_account = [], 0
371getAccountsFromCfg()
372csgo_path = getCsgoPath(accounts[current_account]['steam_id_3'])
373match_server_ready = re.compile('^Server reservation check .* ready-up!$')
374with open(csgo_path + 'console_log.log', 'w') as log:
375 log.write('')
376
377
378# INITIALIZATION FOR getScreenShot
379screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
380hwnd = 0
381toplist, csgo = [], []
382
383# BOOLEAN, TIME INITIALIZATION
384truth_table = {'test_for_accept_button': False, 'test_for_success': False, 'test_for_warmup': False, 'first_ocr': True, 'testing': False, 'debugging': False, 'first_push': True, 'test_for_server': False}
385time_table = {'screenshot_time': time.time(), 'time_since_retry': time.time(), 'warmup_test_timer': time.time(), 'time_searching': time.time(), 'not_searching_cc': time.time(), 'searching_cc': time.time()}
386test_for_accept_counter = 0
387
388# csgostats.gg VAR
389retryer = []
390
391# WARMUP DETECTION SETUP
392pytesseract.pytesseract.tesseract_cmd = cfg['tesseract_path']
393push_times, no_text_found, push_counter = [], 0, 0
394for i in cfg['warmup_push_interval'].split(','):
395 push_times.append(int(i))
396push_times.sort(reverse=True)
397join_warmup_time = push_times[0] + 1
398
399# PUSHBULLET VAR
400note = ''
401push_urgency = 0
402
403write('READY')
404write('Current account is: %s\n' % accounts[current_account]['name'], add_time=False)
405
406while True:
407 if win32api.GetAsyncKeyState(cfg['activate_script']) & 1: # F9 (ACTIVATE / DEACTIVATE SCRIPT)
408 truth_table['test_for_server'] = not truth_table['test_for_server']
409 write('TESTING: %s' % truth_table['test_for_server'], overwrite='1')
410 if truth_table['test_for_server']:
411 playsound('sounds/activated_2.mp3')
412 time_table['time_searching'] = time.time()
413 else:
414 playsound('sounds/deactivated.mp3')
415
416 if win32api.GetAsyncKeyState(cfg['activate_push_notification']) & 1: # F8 (ACTIVATE / DEACTIVATE PUSH NOTIFICATION)
417 if not device:
418 try:
419 device = pushbullet.PushBullet(cfg['pushbullet_api_key']).get_device(cfg['pushbullet_device_name'])
420 except (pushbullet.errors.PushbulletError, pushbullet.errors.InvalidKeyError):
421 write('Pushbullet is wrongly configured.\nWrong API Key or DeviceName in config.ini')
422 if device:
423 push_urgency += 1
424 if push_urgency > 3:
425 push_urgency = 0
426 push_info = ['not active', 'only if accepted', 'all game status related information', 'all information (game status/csgostats.gg information)']
427 write('Pushing: %s' % push_info[push_urgency], overwrite='2')
428
429 if win32api.GetAsyncKeyState(cfg['info_newest_match']) & 1: # F7 Key (UPLOAD NEWEST MATCH)
430 write('Uploading / Getting status on newest match')
431 queue_difference = []
432 new_sharecodes = getNewCSGOSharecodes(getOldSharecodes(-1)[0])
433 for new_code in new_sharecodes:
434 retryer.append(new_code) if new_code['sharecode'] not in [old_code['sharecode'] for old_code in retryer] else retryer
435 retryer = UpdateCSGOstats(retryer, get_all_games=True)
436
437 if win32api.GetAsyncKeyState(cfg['open_live_tab']) & 1: # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
438 win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
439 webbrowser.open_new_tab('https://csgostats.gg/player/' + accounts[current_account]['steam_id'] + '#/live')
440 write('new tab opened', add_time=False)
441 time.sleep(0.5)
442 win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
443
444 if win32api.GetAsyncKeyState(cfg['switch_accounts']) & 1: # F15 (SWITCH ACCOUNTS)
445 current_account += 1
446 if current_account > len(accounts) - 1:
447 current_account = 0
448 getCsgoPath(accounts[current_account]['steam_id_3'])
449 write('current account is: %s' % accounts[current_account]['name'], add_time=False, overwrite='3')
450
451 if win32api.GetAsyncKeyState(cfg['end_script']) & 1: # POS1 (END SCRIPT)
452 write('Exiting Script')
453 break
454
455 if retryer:
456 if time.time() - time_table['time_since_retry'] > cfg['auto_retry_interval']:
457 retryer = UpdateCSGOstats(retryer)
458
459 winlist = []
460 win32gui.EnumWindows(enum_cb, toplist)
461 csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
462 if not csgo:
463 continue
464 hwnd = csgo[0][0]
465
466 # TESTING HERE
467 if win32api.GetAsyncKeyState(0x6F) & 1: # UNBOUND, TEST CODE
468 truth_table['debugging'] = not truth_table['debugging']
469 write('DEBUGGING: %s\n' % truth_table['debugging'])
470
471 if truth_table['testing']:
472 # time_table['screenshot_time'] = time.time()
473 pass
474 # print('Took: %s ' % str(timedelta(milliseconds=int(time.time(*1000 - time_table['screenshot_time']*1000))))
475 # TESTING ENDS HERE
476
477 if truth_table['test_for_server']:
478 if time.time() - time_table['searching_cc'] > 0.2:
479 time_table['searching_cc'] = time.time()
480 continue
481 with open(csgo_path + 'console_log.log', 'rb+') as log:
482 game_start = [line.decode('utf-8', 'ignore').encode("utf-8").rstrip(b'\n\r').decode() for line in log.readlines()]
483 log.seek(0)
484 log.truncate()
485 start = time.time_ns()
486 server_ready = any([bool(re.match(match_server_ready, i)) for i in game_start])
487 if server_ready:
488 test_for_accept_counter = 0
489 truth_table['test_for_accept_button'] = True
490 # truth_table['test_for_server'] = False
491 write('Server found, starting to look for accept button')
492 else:
493 if time.time() - time_table['not_searching_cc'] > 20:
494 time_table['not_searching_cc'] = time.time()
495 with open(csgo_path + 'console_log.log', 'w') as log:
496 log.write('')
497
498 if truth_table['test_for_accept_button']:
499 if time.time() - time_table['screenshot_time'] < cfg['screenshot_interval']:
500 continue
501 time_table['screenshot_time'] = time.time()
502 img = getScreenShot(hwnd, (1265, 760, 1295, 785))
503 if not img:
504 continue
505 accept_avg = color_average(img, [(76, 176, 80), (89, 203, 94)])
506 if relate_list(accept_avg, [(2, 2, 2), (2, 2, 2)]):
507 write('Trying to Accept', push=push_urgency + 1)
508
509 truth_table['test_for_success'] = True
510 truth_table['test_for_accept_button'] = False
511 truth_table['test_for_server'] = False
512 accept_avg = []
513
514 for _ in range(5):
515 click(int(screen_width / 2), int(screen_height / 1.78))
516 pass
517
518 write('Trying to catch a loading map')
519 playsound('sounds/accept_found.mp3')
520 time_table['screenshot_time'] = time.time()
521 test_for_accept_counter += 1
522 if test_for_accept_counter > 10:
523 write('NO ACCEPT BUTTON FOUND AFTER 10 seconds')
524 write('Continuing to HELP')
525 truth_table['test_for_accept_button'] = False
526
527 if truth_table['test_for_success']:
528 if time.time() - time_table['screenshot_time'] < 40:
529 img = getScreenShot(hwnd, (2435, 65, 2555, 100))
530 not_searching_avg = color_average(img, [(6, 10, 10)])
531 searching_avg = color_average(img, [(6, 163, 97), (4, 63, 35)])
532
533 not_searching = relate_list(not_searching_avg, [(2, 5, 5)])
534 searching = relate_list(searching_avg, [(2.7, 55, 35), (1, 50, 35)])
535
536 img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
537 success_avg = color_average(img, [(21, 123, 169)])
538 success = relate_list(success_avg, [(1, 8, 7)])
539
540 if success:
541 write('\tTook %s since pressing accept.' % str(timedelta(seconds=int(time.time() - time_table['screenshot_time']))), add_time=False, push=push_urgency + 1)
542 write('\tTook %s since trying to find a game.' % str(timedelta(seconds=int(time.time() - time_table['time_searching']))), add_time=False, push=push_urgency + 1)
543 write('Game should have started', push=push_urgency + 2, push_now=True)
544 truth_table['test_for_success'] = False
545 truth_table[''] = True
546 playsound('sounds/done_testing.mp3')
547 time_table['warmup_test_timer'] = time.time() + 5
548 continue
549
550 if any([searching, not_searching]):
551 write('\tTook: %s ' % str(timedelta(seconds=int(time.time() - time_table['screenshot_time']))), add_time=False, push=push_urgency + 1)
552 write('Game doesnt seem to have started. Continuing to search for accept Button!', push=push_urgency + 1, push_now=True)
553 playsound('sounds/back_to_testing.mp3')
554 truth_table['test_for_success'] = False
555 truth_table['test_for_server'] = True
556 continue
557
558 else:
559 write('40 Seconds after accept, did not find a loading map nor searching queue')
560 truth_table['test_for_success'] = False
561 # noinspection PyUnboundLocalVariable
562 print(success_avg)
563 # noinspection PyUnboundLocalVariable
564 print(searching_avg)
565 # noinspection PyUnboundLocalVariable
566 print(not_searching_avg)
567 playsound('sounds/fail.mp3')
568 # noinspection PyUnboundLocalVariable
569 img.save(os.path.expanduser('~') + '\\Unknown Error.png')
570
571 if truth_table['test_for_warmup']:
572
573 for i in range(112, 113): # 136
574 win32api.GetAsyncKeyState(i) & 1
575 while True:
576 keys = []
577 for i in range(112, 113):
578 keys.append(win32api.GetAsyncKeyState(i) & 1)
579 if any(keys):
580 write('Break from warmup-loop')
581 truth_table['test_for_warmup'] = False
582 truth_table['first_ocr'] = True
583 truth_table['first_push'] = True
584 break
585
586 if time.time() - time_table['warmup_test_timer'] >= cfg['warmup_test_interval']:
587 img = getScreenShot(hwnd, (1036, 425, 1525, 456)) # 'WAITING FOR PLAYERS X:XX'
588 img_text = Image_to_Text(img, img.size, (225, 225, 225), arg='--psm 6')
589 time_table['warmup_test_timer'] = time.time()
590 if img_text:
591 time_left = img_text.split()[-1].split(':')
592 # write(img_text, add_time=False)
593 try:
594 time_left = int(time_left[0]) * 60 + int(time_left[1])
595 if truth_table['first_ocr']:
596 join_warmup_time = time_left
597 time_table['screenshot_time'] = time.time()
598 truth_table['first_ocr'] = False
599
600 except (ValueError, IndexError):
601 continue
602
603 time_left_data = timedelta(seconds=int(time.time() - time_table['screenshot_time'])), time.strftime('%H:%M:%S', time.gmtime(abs((join_warmup_time - time_left) - (time.time() - time_table['screenshot_time'])))), img_text
604 write('Time since start: %s - Time Difference: %s - Time left: %s' % (time_left_data[0], time_left_data[1], time_left_data[2]), add_time=False, overwrite='1')
605 if no_text_found > 0:
606 no_text_found -= 1
607
608 if time_left <= push_times[push_counter]:
609 push_counter += 1
610 write('Time since start: %s\nTime Difference: %s\nTime left: %s' % (time_left_data[0], time_left_data[1], time_left_data[2]), push=push_urgency + 1, push_now=True, output=False)
611
612 if truth_table['first_push']:
613 if abs((join_warmup_time - time_left) - (time.time() - time_table['screenshot_time'])) >= 5:
614 truth_table['first_push'] = False
615 write('Match should start in ' + str(time_left) + ' seconds, All players have connected', push=push_urgency + 2, push_now=True)
616
617 else:
618 no_text_found += 1
619
620 if push_counter >= len(push_times):
621 push_counter = 0
622 no_text_found = 0
623 truth_table['test_for_warmup'] = False
624 truth_table['first_ocr'] = True
625 truth_table['first_push'] = True
626 write('Warmup should be over in less then %s seconds!' % push_times[-1], push=push_urgency + 2, push_now=True)
627 break
628
629 if no_text_found >= cfg['warmup_no_text_limit']:
630 push_counter = 0
631 no_text_found = 0
632 truth_table['test_for_warmup'] = False
633 truth_table['first_ocr'] = True
634 truth_table['first_push'] = True
635 write('Did not find any warmup text.', push=push_urgency + 2, push_now=True)
636 break
637if console_window['isatty']:
638 if last_printed_line.split(b'**')[-1] != b'\n':
639 print('')
640exit('ENDED BY USER')