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