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