Suppenbiatch

CSGO AUTO ACCEPT V1.1.7

Apr 17th, 2020
2,727
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.73 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.     return sum(lst) / len(lst)
  22.  
  23.  
  24. # noinspection PyShadowingNames,PyUnusedLocal
  25. def enum_cb(hwnd, results):
  26.     winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
  27.  
  28.  
  29. # noinspection PyShadowingNames
  30. def 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
  67. def 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
  74. def 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
  87. def 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
  105. def 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
  120. def 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
  140. def 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
  160. def 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
  185. def 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
  228. def 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.  
  254. def 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
  274. appdata_path = os.getenv('APPDATA') + '\\CSGO AUTO ACCEPT\\'
  275. try:
  276.     os.mkdir(appdata_path)
  277. except FileExistsError:
  278.     pass
  279. overwrite_log = open(appdata_path+'\\overwrite_log.txt', 'wb')
  280. overwrite_log.write('0**\n'.encode())
  281. overwrite_log.close()
  282. console_window = ()
  283. if not sys.stdout.isatty():
  284.     console_window = ('', '\r')
  285. else:
  286.     console_window = ('\r', '')
  287.  
  288.  
  289.  
  290. # CONFIG HANDLING
  291. config = configparser.ConfigParser()
  292. config.read('config.ini')
  293. cfg = getCfgData()
  294. device = 0
  295.  
  296. # ACCOUNT HANDLING, GETTING ACCOUNT NAME
  297. accounts, current_account = [], 0
  298. getAccountsFromCfg()
  299.  
  300. # INITIALIZATION FOR getScreenShot
  301. screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
  302. toplist, winlist = [], []
  303. hwnd = 0
  304.  
  305. # BOOLEAN, TIME INITIALIZATION
  306. 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}
  307. time_table = {'screenshot_time': time.time(), 'error_check_time': time.time(), 'warmup_test_timer': time.time(), 'time_searching': time.time()}
  308.  
  309. # csgostats.gg VAR
  310. retrying_games = []
  311.  
  312. # WARMUP DETECTION SETUP
  313. pytesseract.pytesseract.tesseract_cmd = cfg['tesseract_path']
  314. push_times, no_text_found, push_counter = [], 0, 0
  315. for i in cfg['warmup_push_interval'].split(','):
  316.     push_times.append(int(i))
  317. push_times.sort(reverse=True)
  318. join_warmup_time = push_times[0] + 1
  319.  
  320. # PUSHBULLET VAR
  321. note = ''
  322. push_urgency = 0
  323.  
  324. write('READY')
  325. write('Current account is: %s\n' % accounts[current_account]['name'], add_time=False)
  326.  
  327. while 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 = retrying_games
  353.         for code in getNewCSGOMatches(getOldSharecodes()[0]):
  354.             if code not in [i for i in sharecodes]:
  355.                 sharecodes.append(code)
  356.         UpdateCSGOstats(sharecodes, num_completed=len(sharecodes))
  357.  
  358.     if win32api.GetAsyncKeyState(cfg['info_multiple_matches']) & 1:  # F6 Key (GET INFO ON LAST X MATCHES)
  359.         write('Getting Info from last %s matches' % cfg['last_x_matches'])
  360.         getNewCSGOMatches(getOldSharecodes()[0])
  361.         UpdateCSGOstats(getOldSharecodes(num=cfg['last_x_matches'] * -1), num_completed=cfg['completed_matches'])
  362.  
  363.     if win32api.GetAsyncKeyState(cfg['open_live_tab']) & 1:  # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
  364.         win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
  365.         webbrowser.open_new_tab('https://csgostats.gg/player/' + accounts[current_account]['steam_id'] + '#/live')
  366.         write('new tab opened', add_time=False)
  367.         time.sleep(0.5)
  368.         win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
  369.  
  370.     if win32api.GetAsyncKeyState(cfg['switch_accounts']) & 1:  # F15 (SWITCH ACCOUNTS)
  371.         current_account += 1
  372.         if current_account > len(accounts) - 1:
  373.             current_account = 0
  374.         write('current account is: %s' % accounts[current_account]['name'], add_time=False, overwrite='3')
  375.  
  376.     if win32api.GetAsyncKeyState(cfg['end_script']) & 1:  # POS1 (END SCRIPT)
  377.         write('Exiting Script')
  378.         break
  379.  
  380.     if retrying_games:
  381.         if time.time() - time_table['error_check_time'] > cfg['auto_retry_interval']:
  382.             time_table['error_check_time'] = time.time()
  383.             UpdateCSGOstats(retrying_games, num_completed=len(retrying_games))
  384.  
  385.     winlist = []
  386.     win32gui.EnumWindows(enum_cb, toplist)
  387.     csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
  388.  
  389.     # ONLY CONTINUING IF CSGO IS RUNNING
  390.     if not csgo:
  391.         continue
  392.     hwnd = csgo[0][0]
  393.  
  394.     # TESTING HERE
  395.     if win32api.GetAsyncKeyState(0x6F) & 1:  # UNBOUND, TEST CODE
  396.         # truth_table['testing'] = not truth_table['testing']
  397.         truth_table['debugging'] = not truth_table['debugging']
  398.         # truth_table['test_for_warmup'] = not truth_table['test_for_warmup']
  399.         # time_table['warmup_test_timer'] = time.time() + 2
  400.         write('DEBUGGING: %s\n' % truth_table['debugging'])
  401.  
  402.     if truth_table['testing']:
  403.         # time_table['screenshot_time'] = time.time()
  404.         pass
  405.         # print('Took: %s ' % str(timedelta(milliseconds=int(time.time(*1000 - time_table['screenshot_time']*1000))))
  406.     # TESTING ENDS HERE
  407.  
  408.     if truth_table['test_for_live_game']:
  409.         if time.time() - time_table['screenshot_time'] < cfg['screenshot_interval']:
  410.             continue
  411.         time_table['screenshot_time'] = time.time()
  412.         img = getScreenShot(hwnd, (1265, 760, 1295, 785))
  413.         if not img:
  414.             continue
  415.         accept_avg = color_average(img, [76, 176, 80, 89, 203, 94])
  416.         write(accept_avg, add_time=False)
  417.         if relate_list(accept_avg, [(1, 2, 1), (1, 1, 2)]):
  418.             write('Trying to Accept', push=push_urgency + 1)
  419.  
  420.             truth_table['test_for_success'] = True
  421.             truth_table['test_for_live_game'] = False
  422.             accept_avg = []
  423.  
  424.             for _ in range(5):
  425.                 click(int(screen_width / 2), int(screen_height / 1.78))
  426.  
  427.             write('Trying to catch a loading map')
  428.             playsound('sounds/accept_found.mp3')
  429.             time_table['screenshot_time'] = time.time()
  430.  
  431.     if truth_table['test_for_success']:
  432.         if time.time() - time_table['screenshot_time'] < 40:
  433.             img = getScreenShot(hwnd, (2435, 65, 2555, 100))
  434.             not_searching_avg = color_average(img, [6, 10, 10])
  435.             searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
  436.  
  437.             not_searching = relate_list(not_searching_avg, [(2, 5, 5)])
  438.             searching = relate_list(searching_avg, [(2.7, 55, 35), (1, 50, 35)])
  439.  
  440.             img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
  441.             success_avg = color_average(img, [21, 123, 169])
  442.             success = relate_list(success_avg, [(1, 8, 7)])
  443.  
  444.             if success:
  445.                 write('Took %s since pressing accept.' % str(timedelta(seconds=int(time.time() - time_table['screenshot_time']))), add_time=False, push=push_urgency + 1)
  446.                 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)
  447.                 write('Game should have started', push=push_urgency + 2, push_now=True)
  448.                 truth_table['test_for_success'] = False
  449.                 truth_table['test_for_warmup'] = True
  450.                 playsound('sounds/done_testing.mp3')
  451.                 time_table['warmup_test_timer'] = time.time() + 5
  452.  
  453.             if any([searching, not_searching]):
  454.                 write('Took: %s ' % str(timedelta(seconds=int(time.time() - time_table['screenshot_time']))), add_time=False, push=push_urgency + 1)
  455.                 write('Game doesnt seem to have started. Continuing to search for accept Button!', push=push_urgency + 1, push_now=True)
  456.                 playsound('sounds/back_to_testing.mp3')
  457.                 truth_table['test_for_success'] = False
  458.                 truth_table['test_for_live_game'] = True
  459.  
  460.         else:
  461.             write('40 Seconds after accept, did not find loading map nor searching queue')
  462.             truth_table['test_for_success'] = False
  463.             print(success_avg)
  464.             print(searching_avg)
  465.             print(not_searching_avg)
  466.             playsound('sounds/fail.mp3')
  467.             img.save(os.path.expanduser('~') + '\\Unknown Error.png')
  468.  
  469.     if truth_table['test_for_warmup']:
  470.         for i in range(112, 113):  # 136
  471.             win32api.GetAsyncKeyState(i) & 1
  472.         while True:
  473.             keys = []
  474.             for i in range(112, 113):
  475.                 keys.append(win32api.GetAsyncKeyState(i) & 1)
  476.             if any(keys):
  477.                 write('Break from warmup-loop')
  478.                 truth_table['test_for_warmup'] = False
  479.                 truth_table['first_ocr'] = True
  480.                 truth_table['first_push'] = True
  481.                 break
  482.  
  483.             if time.time() - time_table['warmup_test_timer'] >= cfg['warmup_test_interval']:
  484.                 img = getScreenShot(hwnd, (1036, 425, 1525, 456))  # 'WAITING FOR PLAYERS X:XX'
  485.                 img_text = Image_to_Text(img, img.size, (225, 225, 225), arg='--psm 6')
  486.                 time_table['warmup_test_timer'] = time.time()
  487.                 if img_text:
  488.                     time_left = img_text.split()[-1].split(':')
  489.                     # write(img_text, add_time=False)
  490.                     try:
  491.                         time_left = int(time_left[0]) * 60 + int(time_left[1])
  492.                         if truth_table['first_ocr']:
  493.                             join_warmup_time = time_left
  494.                             time_table['screenshot_time'] = time.time()
  495.                             truth_table['first_ocr'] = False
  496.  
  497.                     except ValueError:
  498.                         time_left = push_times[0] + 1
  499.  
  500.                     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
  501.                     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')
  502.                     if no_text_found > 0:
  503.                         no_text_found -= 1
  504.  
  505.                     if time_left <= push_times[push_counter]:
  506.                         push_counter += 1
  507.                         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)
  508.  
  509.                     if truth_table['first_push']:
  510.                         if abs((join_warmup_time - time_left) - (time.time() - time_table['screenshot_time'])) >= 5:
  511.                             truth_table['first_push'] = False
  512.                             write('Match should start in ' + str(time_left) + 'seconds, All players have connected', push=push_urgency + 2, push_now=True)
  513.  
  514.                 else:
  515.                     no_text_found += 1
  516.  
  517.             if push_counter >= len(push_times):
  518.                 push_counter = 0
  519.                 no_text_found = 0
  520.                 truth_table['test_for_warmup'] = False
  521.                 truth_table['first_ocr'] = True
  522.                 truth_table['first_push'] = True
  523.                 write('Warmup should be over in less then %s seconds!' % push_times[-1], push=push_urgency + 2, push_now=True)
  524.                 break
  525.  
  526.             if no_text_found >= cfg['warmup_no_text_limit']:
  527.                 push_counter = 0
  528.                 no_text_found = 0
  529.                 truth_table['test_for_warmup'] = False
  530.                 truth_table['first_ocr'] = True
  531.                 truth_table['first_push'] = True
  532.                 write('Did not find any warmup text.', push=push_urgency + 2, push_now=True)
  533.                 break
  534.  
  535. exit('ENDED BY USER')
Add Comment
Please, Sign In to add comment