Suppenbiatch

CSGO AUTO ACCEPT V1.1.2

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