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