Suppenbiatch

CSGO AUTO ACCEPT V1.06

Mar 25th, 2020
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.10 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
  7.  
  8. import pushbullet
  9. import pyperclip
  10. import requests
  11. import win32api
  12. import win32con
  13. import win32gui
  14. from PIL import ImageGrab
  15. from playsound import playsound
  16.  
  17.  
  18. def Avg(lst):
  19.     return sum(lst) / len(lst)
  20.  
  21.  
  22. # noinspection PyShadowingNames
  23. def enum_cb(hwnd, results):
  24.     winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
  25.  
  26.  
  27. def write(message, add_time=True, push=0, push_now=False):
  28.     if message:
  29.         if add_time:
  30.             m = datetime.now().strftime("%H:%M:%S") + ": " + str(message)
  31.         else:
  32.             m = message
  33.         print(m)
  34.  
  35.     if push >= 3:
  36.         global note
  37.         if message:
  38.             note = note + m + "\n"
  39.         if push_now:
  40.             device.push_note("CSGO AUTO ACCEPT", note)
  41.             note = ""
  42.  
  43.  
  44. def click(x, y):
  45.     win32api.SetCursorPos((x, y))
  46.     win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
  47.     win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
  48.  
  49.  
  50. # noinspection PyShadowingNames,PyShadowingNames
  51. def relate_list(l_org, l1, l2=[], relate=operator.le):
  52.     if not l_org:
  53.         return False
  54.     truth_list, l3 = [], []
  55.     for i, val in enumerate(l1, start=0):
  56.         l3.append(relate(l_org[i], val))
  57.     truth_list.append(all(l3))
  58.     l3 = []
  59.     if l2:
  60.         for i, val in enumerate(l2, start=3):
  61.             l3.append(relate(l_org[i], val))
  62.         truth_list.append(all(l3))
  63.     return any(truth_list)
  64.  
  65.  
  66. # noinspection PyShadowingNames,PyShadowingNames
  67. def color_average(image, compare_list):
  68.     average = []
  69.     r, g, b = [], [], []
  70.     data = image.getdata()
  71.     for i in data:
  72.         r.append(i[0])
  73.         g.append(i[1])
  74.         b.append(i[2])
  75.  
  76.     rgb = [Avg(r), Avg(g), Avg(b)] * int(len(compare_list) / 3)
  77.  
  78.     for i, val in enumerate(compare_list, start=0):
  79.         average.append(val - rgb[i])
  80.     average = list(map(abs, average))
  81.  
  82.     return average
  83.  
  84.  
  85. # noinspection PyShadowingNames,PyShadowingNames
  86. def getScreenShot(window_id, area=(0, 0, 0, 0)):
  87.     area = list(area)
  88.     scaled_area = [screen_width / 2560, screen_height / 1440]
  89.     scaled_area = 2 * scaled_area
  90.     for i, _ in enumerate(area[-2:], start=len(area) - 2):
  91.         area[i] += 1
  92.     for i, val in enumerate(area, start=0):
  93.         scaled_area[i] = scaled_area[i] * val
  94.     scaled_area = list(map(int, scaled_area))
  95.     win32gui.ShowWindow(window_id, win32con.SW_MAXIMIZE)
  96.     image = ImageGrab.grab(scaled_area)
  97.     return image
  98.  
  99.  
  100. # noinspection PyShadowingNames
  101. def getOldSharecodes(num=-1):
  102.     try:
  103.         last_game = open("last_game_"+accounts[current_account]["steam_id"]+".txt", "r")
  104.         games = last_game.readlines()
  105.         last_game.close()
  106.     except FileNotFoundError:
  107.         last_game = open("last_game_"+accounts[current_account]["steam_id"]+".txt", "w")
  108.         last_game.write(accounts[current_account]["match_token"] + "\n")
  109.         games = [accounts[current_account]["match_token"]]
  110.         last_game.close()
  111.     last_game = open("last_game_"+accounts[current_account]["steam_id"]+".txt", "w")
  112.     games = games[-200:]
  113.     for i, val in enumerate(games):
  114.         games[i] = "CSGO" + val.strip("\n").split("CSGO")[1]
  115.         last_game.write(games[i] + "\n")
  116.     last_game.close()
  117.     return games[num:]
  118.  
  119.  
  120. def getNewCSGOMatches(game_id):
  121.     sharecodes = []
  122.     next_code = game_id
  123.     last_game = open("last_game_"+accounts[current_account]["steam_id"]+".txt", "a")
  124.     while next_code != "n/a":
  125.         steam_url = "https://api.steampowered.com/ICSGOPlayers_730/GetNextMatchSharingCode/v1?key=" + steam_api_key + "&steamid=" + accounts[current_account]["steam_id"] + "&steamidkey=" + accounts[current_account]["auth_code"] + "&knowncode=" + game_id
  126.         try:
  127.             next_code = (requests.get(steam_url).json()["result"]["nextcode"])
  128.         except KeyError:
  129.             write("WRONG GAME_CODE, GAME_ID or STEAM_ID ")
  130.             return 0
  131.  
  132.         if next_code:
  133.             if next_code != "n/a":
  134.                 sharecodes.append(next_code)
  135.                 game_id = next_code
  136.                 last_game.write(next_code + "\n")
  137.     if sharecodes:
  138.         return sharecodes
  139.     else:
  140.         return [game_id]
  141.  
  142.  
  143. # noinspection PyShadowingNames
  144. def UpdateCSGOstats(sharecodes, num_completed=1):
  145.     completed_games, analyze_games = [], []
  146.     for val in sharecodes:
  147.         response = requests.post("https://csgostats.gg/match/upload/ajax", data={'sharecode': val, 'index': '1'})
  148.         if response.json()["status"] == "complete":
  149.             completed_games.append(response.json())
  150.         else:
  151.             analyze_games.append(response.json())
  152.         # TEST GAME:
  153.         # analyze_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}]
  154.     output = [completed_games[num_completed * -1:], analyze_games]
  155.     for i in output:
  156.         for json_dict in i:
  157.             sharecode = json_dict["data"]["sharecode"]
  158.             game_url = json_dict["data"]["url"]
  159.             info = json_dict["data"]["msg"].split("<")[0].replace('-', '').rstrip(" ")
  160.             write('Sharecode: %s' % sharecode, add_time=False, push=push_urgency)
  161.             write("URL: %s" % game_url, add_time=False, push=push_urgency)
  162.             write("Status: %s." % info, add_time=False, push=push_urgency)
  163.     write(None, add_time=False, push=push_urgency, push_now=True)
  164.     if completed_games:
  165.         pyperclip.copy(completed_games[-1]["data"]["url"])
  166.     return game_url
  167.  
  168.  
  169. def getHotKeys():
  170.     get_keys = [int(config.get("HotKeys", "Activate Script"), 16), int(config.get("HotKeys", "Activate Push Notification"), 16), int(config.get("HotKeys", "Get Info on newest Match"), 16),
  171.                 int(config.get("HotKeys", "Get Info on multiple Matches"), 16), int(config.get("HotKeys", "Live Tab Key"), 16), int(config.get("HotKeys", "Switch accounts for csgostats.gg"), 16),
  172.                 int(config.get("HotKeys", "End Script"), 16)]
  173.     return get_keys
  174.  
  175.  
  176. config = configparser.ConfigParser()
  177. config.read("config.ini")
  178. steam_api_key = config.get("csgostats.gg", "API Key")
  179. screenshot_interval = config.getint("Screenshot", "Interval")
  180. keys = getHotKeys()
  181. device = 0
  182.  
  183.  
  184. accounts, current_account = [], 0
  185. steam_ids = ","
  186. for i in config.sections():
  187.     if i.startswith("Account"):
  188.         # display_name = config.get(i, "Display Name")
  189.         steam_id = config.get(i, "Steam ID")
  190.         auth_code = config.get(i, "Authentication Code")
  191.         match_token = config.get(i, "Match Token")
  192.         steam_ids += steam_id + ","
  193.         accounts.append({"steam_id": steam_id, "auth_code": auth_code, "match_token": match_token})
  194.  
  195. steam_ids = steam_ids.lstrip(",").rstrip(",")
  196. profiles = requests.get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=" + steam_api_key + "&steamids=" + steam_ids).json()["response"]["players"]
  197. for i in profiles:
  198.     for n in accounts:
  199.         if n["steam_id"] == i["steamid"]:
  200.             n["name"] = i["personaname"]
  201.             break
  202.  
  203. screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
  204. toplist, winlist = [], []
  205. hwnd = 0
  206.  
  207. test_for_live_game, test_for_success, push_urgency, testing = False, False, False, False
  208. # accept_avg = []
  209.  
  210. note = ""
  211.  
  212. start_time = time()
  213. write("READY")
  214. write("current account is: %s" % accounts[current_account]["name"], add_time=False)
  215. print("\n")
  216.  
  217. while True:
  218.     if win32api.GetAsyncKeyState(keys[0]) & 1:  # F9 (ACTIVATE / DEACTIVATE SCRIPT)
  219.         test_for_live_game = not test_for_live_game
  220.         write("TESTING: %s" % test_for_live_game)
  221.         if test_for_live_game:
  222.             playsound('sounds/activated.mp3')
  223.             time_searching = time()
  224.         else:
  225.             playsound('sounds/deactivated.mp3')
  226.  
  227.     if win32api.GetAsyncKeyState(keys[1]) & 1:  # F8 (ACTIVATE / DEACTIVATE PUSH NOTIFICATION)
  228.         if not device:
  229.             PushBulletDeviceName = config.get('Pushbullet', 'Device Name')
  230.             PushBulletAPIKey = config.get('Pushbullet', 'API Key')
  231.             try:
  232.                 device = pushbullet.PushBullet(PushBulletAPIKey).get_device(PushBulletDeviceName)
  233.             except pushbullet.errors.PushbulletError or pushbullet.errors.InvalidKeyError:
  234.                 write("Pushbullet is wrongly configured.\nWrong API Key or DeviceName in config.ini")
  235.         if device:
  236.             push_urgency += 1
  237.             if push_urgency > 3:
  238.                 push_urgency = 0
  239.             push_info = ["not active", "only if accepted", "all game status related information", "all information (game status/csgostats.gg information)"]
  240.             write("Pushing: %s" % push_info[push_urgency])
  241.  
  242.     if win32api.GetAsyncKeyState(keys[2]) & 1:  # F7 Key (UPLOAD NEWEST MATCH)
  243.         write("Uploading / Getting status on newest match")
  244.         pyperclip.copy(UpdateCSGOstats(getNewCSGOMatches(getOldSharecodes()[0])))
  245.  
  246.     if win32api.GetAsyncKeyState(keys[3]) & 1:  # F6 Key (GET INFO ON LAST X MATCHES)
  247.         last_x_matches = config.getint("csgostats.gg", "Number of Requests")
  248.         completed_matches = config.getint("csgostats.gg", "Completed Matches")
  249.         write("Getting Info from last %s matches" % last_x_matches)
  250.         # write("Outputting %s completed match[es]" % completed_matches, add_time=False)
  251.         getNewCSGOMatches(getOldSharecodes()[0])
  252.         UpdateCSGOstats(getOldSharecodes(num=last_x_matches * -1), num_completed=completed_matches)
  253.  
  254.     if win32api.GetAsyncKeyState(keys[4]) & 1:  # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
  255.         webbrowser.open_new_tab("https://csgostats.gg/player/" + accounts[current_account]["steam_id"] + "#/live")
  256.         write("new tab opened", add_time=False)
  257.  
  258.     if win32api.GetAsyncKeyState(keys[5]) & 1:  # F15 (SWITCH ACCOUNTS)
  259.         current_account += 1
  260.         if current_account > len(accounts)-1:
  261.             current_account = 0
  262.         print(current_account)
  263.         write("current account is: %s" % accounts[current_account]["name"], add_time=False)
  264.  
  265.     if win32api.GetAsyncKeyState(keys[6]) & 1:  # POS1/HOME Key
  266.         write("Exiting Script")
  267.         break
  268.  
  269.     winlist = []
  270.     win32gui.EnumWindows(enum_cb, toplist)
  271.     csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
  272.     if not csgo:
  273.         continue
  274.     hwnd = csgo[0][0]
  275.  
  276.     # TESTING HERE
  277.     if win32api.GetAsyncKeyState(0) & 1:  # F5, TEST CODE
  278.         print("\n")
  279.         write("Executing TestCode")
  280.         print("\n")
  281.         testing = not testing
  282.  
  283.     if testing:
  284.         # start_time = time()
  285.         img = getScreenShot(hwnd, (2435, 65, 2555, 100))
  286.         not_searching_avg = color_average(img, [6, 10, 10])
  287.         searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
  288.         not_searching = relate_list(not_searching_avg, [2, 5, 5])
  289.         searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
  290.         img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
  291.         success_avg = color_average(img, [21, 123, 169])
  292.         success = relate_list(success_avg, [1, 8, 7])
  293.         # print("Took: %s " % str(timedelta(milliseconds=int(time()*1000 - start_time*1000))))
  294.     # TESTING ENDS HERE
  295.  
  296.     if test_for_live_game:
  297.         if time() - start_time < screenshot_interval:
  298.             continue
  299.         start_time = time()
  300.         img = getScreenShot(hwnd, (1265, 760, 1295, 785))
  301.         if not img:
  302.             continue
  303.         accept_avg = color_average(img, [76, 176, 80, 90, 203, 95])
  304.  
  305.         if relate_list(accept_avg, [1, 2, 1], l2=[1, 1, 2]):
  306.             write("Trying to Accept", push=push_urgency + 1)
  307.  
  308.             test_for_success = True
  309.             test_for_live_game = False
  310.             accept_avg = []
  311.  
  312.             for _ in range(5):
  313.                 click(int(screen_width / 2), int(screen_height / 1.78))
  314.                 # sleep(0.5)
  315.                 # pass
  316.  
  317.             write("Trying to catch a loading map")
  318.             playsound('sounds/accept_found.mp3')
  319.             start_time = time()
  320.  
  321.     if test_for_success:
  322.         if time() - start_time < 40:
  323.             img = getScreenShot(hwnd, (2435, 65, 2555, 100))
  324.             not_searching_avg = color_average(img, [6, 10, 10])
  325.             searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
  326.  
  327.             not_searching = relate_list(not_searching_avg, [2, 5, 5])
  328.             searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
  329.  
  330.             img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
  331.             success_avg = color_average(img, [21, 123, 169])
  332.             success = relate_list(success_avg, [1, 8, 7])
  333.  
  334.             if success:
  335.                 write("Took %s since pressing accept." % str(timedelta(seconds=int(time() - start_time))), add_time=False, push=push_urgency + 1)
  336.                 write("Took %s since trying to find a game." % str(timedelta(seconds=int(time() - time_searching))), add_time=False, push=push_urgency + 1)
  337.                 write("Game should have started", push=push_urgency + 2, push_now=True)
  338.                 test_for_success = False
  339.                 playsound('sounds/done_testing.mp3')
  340.  
  341.             if any([searching, not_searching]):
  342.                 write("Took: %s " % str(timedelta(seconds=int(time() - start_time))), add_time=False, push=push_urgency + 1)
  343.                 write("Game doesnt seem to have started. Continuing to search for accept Button!", push=push_urgency + 1, push_now=True)
  344.                 playsound('sounds/back_to_testing.mp3')
  345.                 test_for_success = False
  346.                 test_for_live_game = True
  347.  
  348.         else:
  349.             write("40 Seconds after accept, did not find loading map nor searching queue")
  350.             test_for_success = False
  351.             print(success_avg)
  352.             print(searching_avg)
  353.             print(not_searching_avg)
  354.             playsound('sounds/fail.mp3')
  355.             img.save(os.path.expanduser("~") + '\\Unknown Error.png')
Add Comment
Please, Sign In to add comment