· 6 years ago · Mar 22, 2020, 07:36 PM
1import configparser
2import operator
3import os
4import webbrowser
5from datetime import datetime, timedelta
6from time import time
7
8import pyperclip
9import requests
10import win32api
11import win32con
12import win32gui
13from PIL import ImageGrab
14from playsound import playsound
15from pushbullet import PushBullet
16
17
18def Avg(lst):
19 return sum(lst) / len(lst)
20
21
22def enum_cb(hwnd, results):
23 winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
24
25
26def write(message, add_time=True, push=0, push_now=False):
27 if message:
28 if add_time:
29 m = datetime.now().strftime("%H:%M:%S") + ": " + str(message)
30 else:
31 m = message
32 print(m)
33
34 if push >= 2:
35 global note
36 if message:
37 note = note + m + "\n"
38 if push_now:
39 device.push_note("CSGO AUTO ACCEPT", note)
40 # print(note)
41 note = ""
42
43
44def 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
50def relate_list(l_org, l1, l2=[], relate=operator.le):
51 if not l_org:
52 return False
53 truth_list, l3 = [], []
54 for i, val in enumerate(l1, start=0):
55 l3.append(relate(l_org[i], val))
56 truth_list.append(all(l3))
57 l3 = []
58 if l2:
59 for i, val in enumerate(l2, start=3):
60 l3.append(relate(l_org[i], val))
61 truth_list.append(all(l3))
62 return any(truth_list)
63
64
65def color_average(image, compare_list):
66 average = []
67 r, g, b = [], [], []
68 data = image.getdata()
69 for i in data:
70 r.append(i[0])
71 g.append(i[1])
72 b.append(i[2])
73
74 rgb = [Avg(r), Avg(g), Avg(b)] * int(len(compare_list) / 3)
75
76 for i, val in enumerate(compare_list, start=0):
77 average.append(val - rgb[i])
78 average = list(map(abs, average))
79
80 return average
81
82
83def getScreenShot(window_id, area=(0, 0, 0, 0)):
84 area = list(area)
85 scaled_area = [screen_width / 2560, screen_height / 1440]
86 scaled_area = 2 * scaled_area
87 for i, _ in enumerate(area[-2:], start=len(area) - 2):
88 area[i] += 1
89 for i, val in enumerate(area, start=0):
90 scaled_area[i] = scaled_area[i] * val
91 scaled_area = list(map(int, scaled_area))
92 win32gui.ShowWindow(window_id, win32con.SW_MAXIMIZE)
93 image = ImageGrab.grab(scaled_area)
94 return image
95
96
97def getOldSharecodes(num=-1):
98 last_game = open("last_game.txt", "r")
99 games = last_game.readlines()
100 last_game.close()
101 last_game = open("last_game.txt", "w")
102 games = games[-200:]
103 for i, val in enumerate(games):
104 games[i] = "CSGO" + val.strip("\n").split("CSGO")[1]
105 last_game.write(games[i] + "\n")
106 last_game.close()
107 return games[num:]
108
109
110def getNewCSGOMatches(game_id):
111 sharecodes = []
112 next_code = game_id
113 last_game = open("last_game.txt", "a")
114 while next_code != "n/a":
115 steam_url = "https://api.steampowered.com/ICSGOPlayers_730/GetNextMatchSharingCode/v1?key=" + steam_api_key + "&steamid=" + steam_id + "&steamidkey=" + game_code + "&knowncode=" + game_id
116 try:
117 next_code = (requests.get(steam_url).json()["result"]["nextcode"])
118 except KeyError:
119 write("WRONG GAME_CODE, GAME_ID or STEAM_ID ")
120 return 0
121
122 if next_code:
123 if next_code != "n/a":
124 sharecodes.append(next_code)
125 game_id = next_code
126 last_game.write(next_code + "\n")
127 else:
128 write("Found %s Game[s]" % len(sharecodes))
129 return sharecodes
130
131
132def UpdateCSGOstats(sharecodes):
133 if any(sharecodes):
134 for i in sharecodes:
135 write('Added Sharecode: %s' % i, push=push_urgency)
136 response = requests.post("https://csgostats.gg/match/upload/ajax", data={'sharecode': i, 'index': '1'})
137 info = response.json()["data"]["msg"].split("<")[0].replace('-', '').rstrip(" ")
138 game_url = response.json()["data"]["url"]
139 write("URL: %s" % game_url, add_time=False, push=push_urgency)
140 write("Game %s." % info, add_time=False, push=push_urgency)
141 # print(response.json())
142 write(None, add_time=False, push=push_urgency, push_now=True)
143
144
145def getHotKeys():
146 getKeys = []
147 getKeys.append(int(config.get("HotKeys", "Activate Script"), 16))
148 getKeys.append(int(config.get("HotKeys", "Activate Push Notification"), 16))
149 getKeys.append(int(config.get("HotKeys", "Upload newest Match"), 16))
150 getKeys.append(int(config.get("HotKeys", "Get Info on newest Match"), 16))
151 getKeys.append(int(config.get("HotKeys", "Get Info on multiple Matches"), 16))
152 getKeys.append(int(config.get("HotKeys", "Live Tab Key"), 16))
153 getKeys.append(int(config.get("HotKeys", "End Script"), 16))
154 return getKeys
155
156
157config = configparser.ConfigParser()
158config.read("config.ini")
159
160steam_api_key = config.get("csgostats.gg", "API Key")
161steam_id = config.get("csgostats.gg", "Steam ID")
162game_code = config.get("csgostats.gg", "Game Code")
163
164keys = getHotKeys()
165
166PushBulletDeviceName, PushBulletAPIKey = 0, 0
167
168screen_width, screen_height = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
169toplist, winlist = [], []
170hwnd = 0
171
172test_for_live_game, test_for_success, push_urgency, testing = False, False, False, False
173accept_avg = []
174
175note = ""
176
177start_time = time()
178write("Ready")
179
180while True:
181 if win32api.GetAsyncKeyState(keys[0]) & 1: # F9 (ACTIVATE / DEACTIVATE SCRIPT)
182 test_for_live_game = not test_for_live_game
183 write("TESTING: %s" % test_for_live_game)
184 if test_for_live_game:
185 playsound('sounds/activated.mp3')
186 time_searching = time()
187 else:
188 playsound('sounds/deactivated.mp3')
189
190 if win32api.GetAsyncKeyState(keys[1]) & 1: # F8 (ACTIVATE / DEACTIVATE PUSH NOTIFICATION)
191 push_urgency += 1
192 if push_urgency > 2:
193 push_urgency = 0
194 push_info = ["not active", "little information", "all information"]
195 write("Pushing: %s" % push_info[push_urgency])
196
197 if not PushBulletDeviceName:
198 PushBulletDeviceName = config.get('Pushbullet', 'DeviceName')
199 PushBulletAPIKey = config.get('Pushbullet', 'API Key')
200 device = PushBullet(PushBulletAPIKey).get_device(PushBulletDeviceName)
201
202 if win32api.GetAsyncKeyState(keys[2]) & 1: # F7 Key (UPLOAD NEWEST MATCH)
203 newest_match = getNewCSGOMatches(getOldSharecodes()[0])
204 if newest_match:
205 pyperclip.copy(newest_match[0])
206 UpdateCSGOstats(newest_match)
207
208 if win32api.GetAsyncKeyState(keys[3]) & 1: # F6 Key (GET INFO ON NEWEST MATCH)
209 UpdateCSGOstats(getOldSharecodes())
210
211 if win32api.GetAsyncKeyState(keys[4]) & 1: # F5 Key (GET INFO ON LAST X MATCHES)
212 last_x_matches = config.getint("csgostats.gg", "Get Info from")
213 UpdateCSGOstats(getOldSharecodes(num=last_x_matches * -1))
214
215 if win32api.GetAsyncKeyState(keys[5]) & 1: # F13 Key (OPEN WEB BROWSER ON LIVE GAME TAB)
216 webbrowser.open_new_tab("https://csgostats.gg/player/" + steam_id + "#/live")
217
218 if win32api.GetAsyncKeyState(keys[6]) & 1: # POS1/HOME Key
219 write("Exiting Script")
220 break
221
222 winlist = []
223 win32gui.EnumWindows(enum_cb, toplist)
224 csgo = [(hwnd, title) for hwnd, title in winlist if 'counter-strike: global offensive' in title.lower()]
225 if not csgo:
226 continue
227 hwnd = csgo[0][0]
228
229 # TESTING HERE
230 if win32api.GetAsyncKeyState(0x73) & 1: # F5, TEST CODE
231 write("Executing TestCode")
232 testing = not testing
233
234 if testing:
235 # start_time = time()
236 img = getScreenShot(hwnd, (2435, 65, 2555, 100))
237 not_searching_avg = color_average(img, [6, 10, 10])
238 searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
239 not_searching = relate_list(not_searching_avg, [2, 5, 5])
240 searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
241 img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
242 success_avg = color_average(img, [21, 123, 169])
243 success = relate_list(success_avg, [1, 8, 7])
244 # print("Took: %s " % str(timedelta(milliseconds=int(time()*1000 - start_time*1000))))
245 # TESTING ENDS HERE
246
247 if test_for_live_game:
248 if time() - start_time < 4:
249 continue
250 start_time = time()
251 img = getScreenShot(hwnd, (1265, 760, 1295, 785))
252 if not img:
253 continue
254 accept_avg = color_average(img, [76, 176, 80, 90, 203, 95])
255
256 if relate_list(accept_avg, [1, 2, 1], l2=[1, 1, 2]):
257 write("Trying to Accept", push=push_urgency)
258
259 test_for_success = True
260 test_for_live_game = False
261 accept_avg = []
262
263 for _ in range(5):
264 click(int(screen_width / 2), int(screen_height / 1.78))
265 # sleep(0.5)
266 # pass
267
268 write("Trying to catch a loading map")
269 playsound('sounds/accept_found.mp3')
270 start_time = time()
271
272 if test_for_success:
273 if time() - start_time < 40:
274 img = getScreenShot(hwnd, (2435, 65, 2555, 100))
275 not_searching_avg = color_average(img, [6, 10, 10])
276 searching_avg = color_average(img, [6, 163, 97, 4, 63, 35])
277
278 not_searching = relate_list(not_searching_avg, [2, 5, 5])
279 searching = relate_list(searching_avg, [2.7, 55, 35], l2=[1, 50, 35])
280
281 img = getScreenShot(hwnd, (467, 1409, 1300, 1417))
282 success_avg = color_average(img, [21, 123, 169])
283 success = relate_list(success_avg, [1, 8, 7])
284
285 if success:
286 write("Took %s since pressing accept." % str(timedelta(seconds=int(time() - start_time))), add_time=False, push=push_urgency)
287 write("Took %s since trying to find a game." % str(timedelta(seconds=int(time() - time_searching))), add_time=False, push=push_urgency)
288 write("Game should have started", push=push_urgency + 1, push_now=True)
289 test_for_success = False
290 playsound('sounds/done_testing.mp3')
291
292 if any([searching, not_searching]):
293 write("Took: %s " % str(timedelta(seconds=int(time() - start_time))),add_time=False, push=push_urgency)
294 write("Game doesnt seem to have started. Continuing to search for accept Button!", push=push_urgency, push_now=True)
295 playsound('sounds/back_to_testing.mp3')
296 test_for_success = False
297 test_for_live_game = True
298
299 else:
300 write("Unknown Error")
301 test_for_success = False
302 print(success_avg)
303 print(searching_avg)
304 print(not_searching_avg)
305 playsound('sounds/fail.mp3')
306 img.save(os.path.expanduser("~") + '\\Unknown Error.png')