Suppenbiatch

CSGO AUTO ACCEPT V1.1 BETA

Apr 3rd, 2020
2,808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.20 KB | None | 0 0
  1. import configparser
  2. import operator
  3. import os
  4. import webbrowser
  5. from datetime import datetime, timedelta
  6. from time import time, sleep
  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):
  30.     if output:
  31.         if add_time:
  32.             m = datetime.now().strftime('%H:%M:%S') + ': ' + str(message)
  33.         else:
  34.             m = message
  35.         print(m)
  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.     queued_games = [game['data']['queue_pos'] for game in not_completed_games if game['status'] != 'error']
  178.     global retrying_games
  179.     retrying_games = []
  180.  
  181.     if queued_games:
  182.         if queued_games[0] < cfg['max_queue_position']:
  183.             global error_check_time
  184.             retrying_games = [game['data']['sharecode'] for game in not_completed_games]
  185.             error_check_time = time()
  186.         for i, val in enumerate(queued_games):
  187.             write('#%s: in Queue #%s.' % (i + 1, val), add_time=False)
  188.  
  189.     if len(not_completed_games) - len(queued_games) > 0:
  190.         write('An error occurred in %s game[s].' % (len(not_completed_games) - len(queued_games)), add_time=False)
  191.         retrying_games.append([game['data']['sharecode'] for game in not_completed_games])
  192.  
  193.     if completed_games:
  194.         for i in completed_games[num_completed * - 1:]:
  195.             sharecode = i['data']['sharecode']
  196.             game_url = i['data']['url']
  197.             info = ' '.join(i['data']['msg'].replace('-', '').replace('<br />', '. ').split('<')[0].rstrip(' ').split())
  198.             write('Sharecode: %s' % sharecode, add_time=False, push=push_urgency)
  199.             write('URL: %s' % game_url, add_time=False, push=push_urgency)
  200.             write('Status: %s.' % info, add_time=False, push=push_urgency)
  201.             pyperclip.copy(game_url)
  202.         write(None, add_time=False, push=push_urgency, push_now=True, output=False)
  203.  
  204.  
  205. # noinspection PyShadowingNames
  206. def Image_to_Text(image: Image, size: tuple, white_threshold: list, arg: str = ''):
  207.     image_data = image.getdata()
  208.     pixel_map, image_text = [], ''
  209.     for y in range(size[1]):
  210.         for x in range(size[0]):
  211.             if relate_list(image_data[y * size[0] + x], white_threshold, relate=operator.ge):
  212.                 pixel_map.append((0, 0, 0))
  213.             else:
  214.                 pixel_map.append((255, 255, 255))
  215.     temp_image = Image.new('RGB', (size[0], size[1]))
  216.     temp_image.putdata(pixel_map)
  217.     # temp_image.save('inv.png')
  218.     # image.save('org.png')
  219.     try:
  220.         image_text = pytesseract.image_to_string(temp_image, timeout=0.3, config=arg)
  221.     except RuntimeError as timeout_error:
  222.         pass
  223.     if image_text:
  224.         return ' '.join(image_text.replace(': ', ':').split())
  225.     else:
  226.         return False
  227.  
  228.  
  229. def getCfgData():
  230.     try:
  231.         get_cfg = {'activate_script': int(config.get('HotKeys', 'Activate Script'), 16), 'activate_push_notification': int(config.get('HotKeys', 'Activate Push Notification'), 16),
  232.                    '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),
  233.                    '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),
  234.                    'end_script': int(config.get('HotKeys', 'End Script'), 16),
  235.                    'screenshot_interval': config.getint('Screenshot', 'Interval'), 'steam_api_key': config.get('csgostats.gg', 'API Key'), 'last_x_matches': config.getint('csgostats.gg', 'Number of Requests'),
  236.                    'completed_matches': config.getint('csgostats.gg', 'Completed Matches'), 'max_queue_position': config.getint('csgostats.gg', 'Auto-Retrying for queue position below'),
  237.                    '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'),
  238.                    'tesseract_path': config.get('Warmup', 'Tesseract Path'), 'warmup_test_interval': config.getint('Warmup', 'Test Interval'), 'warmup_push_interval': config.get('Warmup', 'Push Interval'),
  239.                    'warmup_no_text_limit': config.getint('Warmup', 'No Text Limit')}
  240.         return get_cfg
  241.         # 'imgur_id': config.get('Imgur', 'Client ID'), 'imgur_secret': config.get('Imgur', 'Client Secret'),
  242.     except (configparser.NoOptionError, configparser.NoSectionError, ValueError):
  243.         write('ERROR IN CONFIG')
  244.         exit('CHECK FOR NEW CONFIG')
  245.  
  246.  
  247. # CONFIG HANDLING
  248. config = configparser.ConfigParser()
  249. config.read('config.ini')
  250. cfg = getCfgData()
  251. device = 0
  252.  
  253. # ACCOUNT HANDLING, GETTING ACCOUNT NAME
  254. accounts, current_account = [], 0
  255. getAccountsFromCfg()
  256.  
  257. # INITIALIZATION FOR getScreenShot
  258. screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
  259. toplist, winlist = [], []
  260. hwnd = 0
  261.  
  262. # BOOLEAN INITIALIZATION
  263. test_for_live_game, test_for_success, push_urgency, test_for_warmup, testing = False, False, False, False, False
  264.  
  265. # csgostats.gg VAR
  266. retrying_games = []
  267.  
  268. # WARMUP DETECTION SETUP
  269. pytesseract.pytesseract.tesseract_cmd = cfg['tesseract_path']
  270. push_times, no_text_found, push_counter = [], [], 0
  271. for i in cfg['warmup_push_interval'].split(','):
  272.     push_times.append(int(i))
  273. push_times.sort(reverse=True)
  274.  
  275. # PUSHBULLET VAR
  276. note = ''
  277.  
  278. # INITIALIZATION OF TIME VARS
  279. screenshot_time, error_check_time, warmup_test_timer, warmup_push_timer = time(), time(), time(), time()
  280.  
  281. write('READY')
  282. write('Current account is: %s\n' % accounts[current_account]['name'], add_time=False)
  283.  
  284. while True:
  285.     if win32api.GetAsyncKeyState(cfg['activate_script']) & 1:  # F9 (ACTIVATE / DEACTIVATE SCRIPT)
  286.         test_for_live_game = not test_for_live_game
  287.         write('TESTING: %s' % test_for_live_game)
  288.         if test_for_live_game:
  289.             playsound('sounds/activated_2.mp3')
  290.             time_searching = time()
  291.         else:
  292.             playsound('sounds/deactivated.mp3')
  293.  
  294.     if win32api.GetAsyncKeyState(cfg['activate_push_notification']) & 1:  # F8 (ACTIVATE / DEACTIVATE PUSH NOTIFICATION)
  295.         if not device:
  296.             try:
  297.                 device = pushbullet.PushBullet(cfg['pushbullet_api_key']).get_device(cfg['pushbullet_device_name'])
  298.             except (pushbullet.errors.PushbulletError, pushbullet.errors.InvalidKeyError):
  299.                 write('Pushbullet is wrongly configured.\nWrong API Key or DeviceName in config.ini')
  300.         if device:
  301.             push_urgency += 1
  302.             if push_urgency > 3:
  303.                 push_urgency = 0
  304.             push_info = ['not active', 'only if accepted', 'all game status related information', 'all information (game status/csgostats.gg information)']
  305.             write('Pushing: %s' % push_info[push_urgency])
  306.  
  307.     if win32api.GetAsyncKeyState(cfg['info_newest_match']) & 1:  # F7 Key (UPLOAD NEWEST MATCH)
  308.         write('Uploading / Getting status on newest match')
  309.         UpdateCSGOstats(getNewCSGOMatches(getOldSharecodes()[0]))
  310.  
  311.     if win32api.GetAsyncKeyState(cfg['info_multiple_matches']) & 1:  # F6 Key (GET INFO ON LAST X MATCHES)
  312.         write('Getting Info from last %s matches' % cfg['last_x_matches'])
  313.         # write('Outputting %s completed match[es]' % completed_matches, add_time=False)
  314.         getNewCSGOMatches(getOldSharecodes()[0])
  315.         UpdateCSGOstats(getOldSharecodes(num=cfg['last_x_matches'] * -1), num_completed=cfg['completed_matches'])
  316.  
  317.     if win32api.GetAsyncKeyState(cfg['open_live_tab']) & 1:  # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
  318.         win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
  319.         webbrowser.open_new_tab('https://csgostats.gg/player/' + accounts[current_account]['steam_id'] + '#/live')
  320.         write('new tab opened', add_time=False)
  321.         sleep(0.5)
  322.         win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
  323.  
  324.     if win32api.GetAsyncKeyState(cfg['switch_accounts']) & 1:  # F15 (SWITCH ACCOUNTS)
  325.         current_account += 1
  326.         if current_account > len(accounts) - 1:
  327.             current_account = 0
  328.         write('current account is: %s' % accounts[current_account]['name'], add_time=False)
  329.  
  330.     if win32api.GetAsyncKeyState(cfg['stop_warmup_ocr']) & 1:  # ESC (STOP WARMUP OCR)
  331.         write('STOPPING WARMUP TIME FINDER!')
  332.         test_for_warmup = False
  333.         no_text_found = []
  334.         warmup_push_timer, warmup_test_timer = time(), time()
  335.  
  336.     if win32api.GetAsyncKeyState(cfg['end_script']) & 1:  # POS1 (END SCRIPT)
  337.         write('Exiting Script')
  338.         break
  339.  
  340.     if retrying_games:
  341.         if time() - error_check_time > cfg['auto_retry_interval']:
  342.             error_check_time = time()
  343.             UpdateCSGOstats(retrying_games, num_completed=len(retrying_games))
  344.  
  345.     winlist = []
  346.     win32gui.EnumWindows(enum_cb, toplist)
  347.     csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
  348.  
  349.     # ONLY CONTINUING IF CSGO IS RUNNING
  350.     if not csgo:
  351.         continue
  352.     hwnd = csgo[0][0]
  353.  
  354.     # TESTING HERE
  355.     if win32api.GetAsyncKeyState(0x74) & 1:  # UNBOUND, TEST CODE
  356.         print('\n')
  357.         write('Executing TestCode')
  358.         print('\n')
  359.         # testing = not testing
  360.         push_counter = 0
  361.         test_for_warmup = True
  362.         warmup_test_timer, warmup_push_timer = time(), time()
  363.  
  364.     if testing:
  365.         # screenshot_time = time()
  366.         pass
  367.         # print('Took: %s ' % str(timedelta(milliseconds=int(time()*1000 - screenshot_time*1000))))
  368.     # TESTING ENDS HERE
  369.  
  370.     if test_for_live_game:
  371.         if time() - screenshot_time < cfg['screenshot_interval']:
  372.             continue
  373.         screenshot_time = time()
  374.         img = getScreenShot(hwnd, (1265, 760, 1295, 785))
  375.         if not img:
  376.             continue
  377.         accept_avg = color_average(img, [76, 176, 80, 90, 203, 95])
  378.  
  379.         if relate_list(accept_avg, [1, 2, 1], l2=[1, 1, 2]):
  380.             write('Trying to Accept', push=push_urgency + 1)
  381.  
  382.             test_for_success = True
  383.             test_for_live_game = False
  384.             accept_avg = []
  385.  
  386.             for _ in range(5):
  387.                 click(int(screen_width / 2), int(screen_height / 1.78))
  388.  
  389.             write('Trying to catch a loading map')
  390.             playsound('sounds/accept_found.mp3')
  391.             screenshot_time = time()
  392.  
  393.     if test_for_success:
  394.         if time() - screenshot_time < 40:
  395.             img = getScreenShot(hwnd, (2435, 65, 2555, 100))
  396.             not_searching_avg = color_average(img, [6, 10, 10])
  397.             searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
  398.  
  399.             not_searching = relate_list(not_searching_avg, [2, 5, 5])
  400.             searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
  401.  
  402.             img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
  403.             success_avg = color_average(img, [21, 123, 169])
  404.             success = relate_list(success_avg, [1, 8, 7])
  405.  
  406.             if success:
  407.                 write('Took %s since pressing accept.' % str(timedelta(seconds=int(time() - screenshot_time))), add_time=False, push=push_urgency + 1)
  408.                 write('Took %s since trying to find a game.' % str(timedelta(seconds=int(time() - time_searching))), add_time=False, push=push_urgency + 1)
  409.                 write('Game should have started', push=push_urgency + 2, push_now=True)
  410.                 test_for_success = False
  411.                 push_warmup = True
  412.                 playsound('sounds/done_testing.mp3')
  413.                 warmup_test_timer, warmup_push_timer = time()+5, time()+5
  414.  
  415.             if any([searching, not_searching]):
  416.                 write('Took: %s ' % str(timedelta(seconds=int(time() - screenshot_time))), add_time=False, push=push_urgency + 1)
  417.                 write('Game doesnt seem to have started. Continuing to search for accept Button!', push=push_urgency + 1, push_now=True)
  418.                 playsound('sounds/back_to_testing.mp3')
  419.                 test_for_success = False
  420.                 test_for_live_game = True
  421.  
  422.         else:
  423.             write('40 Seconds after accept, did not find loading map nor searching queue')
  424.             test_for_success = False
  425.             print(success_avg)
  426.             print(searching_avg)
  427.             print(not_searching_avg)
  428.             playsound('sounds/fail.mp3')
  429.             img.save(os.path.expanduser('~') + '\\Unknown Error.png')
  430.  
  431.     if test_for_warmup:
  432.         if time() - warmup_test_timer >= cfg['warmup_test_interval']:
  433.             img = getScreenShot(hwnd, (1036, 425, 1525, 456))  # 'WAITING FOR PLAYERS X:XX'
  434.             img_text = Image_to_Text(img, img.size, [225, 225, 225], arg='--psm 6')
  435.             warmup_test_timer = time()
  436.             if img_text:
  437.                 time_left = img_text.split()[-1].split(':')
  438.                 write(img_text, add_time=False)
  439.                 try:
  440.                     time_left = int(time_left[0]) * 60 + int(time_left[1])
  441.                 except ValueError:
  442.                     time_left = push_times[0] + 1
  443.                 if time_left <= push_times[push_counter]:
  444.                     push_counter += 1
  445.                     write(img_text, add_time=False, push=push_urgency + 1, output=False)
  446.             else:
  447.                 no_text_found.append(True)
  448.  
  449.         if push_counter >= len(push_times):
  450.             write('Warmup should be over in less then %s seconds!' % push_times[-1], push=push_urgency + 1, push_now=True)
  451.             push_counter = 0
  452.             no_text_found = []
  453.             test_for_warmup = False
  454.  
  455.         if len(no_text_found) >= cfg['warmup_no_text_limit']:
  456.             push_counter = 0
  457.             no_text_found = []
  458.             test_for_warmup = False
  459.             write('Did not find any warmup text.', push=push_urgency + 1, push_now=True)
  460.  
  461. exit('ENDED BY USER')
Add Comment
Please, Sign In to add comment