Suppenbiatch

CSGO AUTO ACCPET V.1.1.8

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