Suppenbiatch

CSGO AUTO ACCEPT 1.2.0

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