This repository has been archived by the owner on Aug 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeypress.py
516 lines (464 loc) · 12.9 KB
/
keypress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 00:42:48 2018
This module provides an API to read Save/Load saves and to send them as chat
messages in-game.
@author: SonGuhun
"""
# =============================================================================
# 3rd party modules
# =============================================================================
import time
from win32api import keybd_event
import random
# noinspection PyPackageRequirements
import win32gui
import os
from urllib2 import URLError
from py2exeUtils import ConvertPath
import traceback
# =============================================================================
# SaveNLoad modules
# =============================================================================
from globalVariables import GITHUB_USERREPO
import cloud
# =============================================================================
# File-like and Save classes
# =============================================================================
class FileName:
"""
A file-like object that supports reading from local files.
Stores a file name as a string, and the read/readlines methods work by
opening the file, using the respective File class method and closing the
file.
"""
def __init__(self, file_path):
if not os.path.isdir(file_path):
if not os.path.exists(file_path):
open(file_path, 'w').close()
self.path = file_path
else:
self.path = ''
def read(self, *args):
with open(self.path, 'r') as f:
content = f.read(*args)
return content
def readlines(self, *args):
with open(self.path, 'r') as f:
content = f.readlines(*args)
return content
def write(self, *args):
with open(self.path, 'w') as f:
f.write(*args)
def writelines(self, *args):
with open(self.path, 'w') as f:
f.writelines(*args)
class Folder:
"""
A folder-like object that stores the contents of a local directory as a dict
of FileName instances.
Any folders
"""
def __init__(self, folder_path):
self.path = ConvertPath(folder_path)
if os.path.exists(folder_path):
contents = os.listdir(self.path)
self.files = {}
for file_ in contents:
self.files[file_] = FileName(self.path+file_)
else:
self.files = {}
def __getitem__(self, file_name):
return self.files[file_name]
def createFile(self, file_name):
self.files[file_name] = FileName(self.path + file_name)
class Save:
"""
A class that represents a save folder. It supports opening folders using
any of the folder-like classes, like Folder and GitHubFolder created for
SaveNLoad.
Member fields:
name : The name of the Save's folder in a saves directory
folder : A folder-like object representing the Save's folder
type : The type of the Save (how it is stored)
size : The number of numbered .txt files in the Save's folder
version : The major version number with which the Save was made in wc3.
The 'version' and 'size' members are initialized as 0. To retrieve the
actual size and version number of the
"""
_TYPES_ORDERED = ['local', 'github']
_TYPES = {'local': Folder,
'github': cloud.GitHubFolder if GITHUB_USERREPO else None}
def __init__(self, saves_path, save_name):
self.name = save_name
for saveType in Save._TYPES_ORDERED:
if Save._TYPES[saveType]:
self.folder = Save._TYPES[saveType](saves_path+save_name
if saveType == 'local' else save_name)
if self.folder.files:
self.type = saveType
break
if not self.folder.files:
self.folder = None
self.type = ''
self.size = 0
self.version = 0
def __getitem__(self, file_name):
return self.folder[file_name]
def getSize(self):
"""
Reads 'size.txt' inside a save folder to retrieve its size. Once the size
has been retrieved, it is stored in the 'size' member field.
"""
try:
self.size = int(self['size.txt'].read()[69:-43])
except (IOError, URLError):
traceback.print_exc()
self.size = 0
return self.size
def getVersion(self):
"""
Reads 'version.txt' inside a save folder to retrieve its size. Once it
has been retrieved, the version number is stored in the 'version'
member field.
If no 'version.txt' file is found, the Save is considered a version 1
Save.
"""
try:
self.version = int(self['version.txt'].read()[69:-43])
except Exception as error:
if isinstance(error,KeyError):
self.version = 1
else:
traceback.print_exc()
self.version = 0
return self.version
def _readData(self, number):
"""
Reads data from a numbered file .txt in a save directory.
Returns a list with each line of the file, parsed to the format accepted by the in-game save/load.
"""
if self.version == 2:
save_data = self[number+'.txt'].readlines()[2:-5]
save_data = [x[16:-4] for x in save_data]
else:
save_data = self[number+'.txt'].read()[69:-43]
save_data = save_data.split("\\\\n")
return save_data
def loadData(self, speed, wait_time):
"""
Retrives the Save's data from the saves directory. Then all the data is typed
automatically and sent as chat messages to be parsed in-game.
"""
time.sleep(wait_time)
sendChatMessage('-load ini', speed=speed)
time.sleep(0.5)
for x in range(0, self.size):
try:
if not typeSaveData(self._readData(str(x)), speed):
print 'Warcraft III window not in focus. Abort.'
return
except (IOError, URLError):
traceback.print_exc()
print "SaveID:", self.name, "file number", x, "could not be read."
time.sleep(0.5)
sendChatMessage('-load end', speed=speed)
def optimizeData(self, speed, wait_time):
self.folder.createFile('data.txt')
for x in range(0, self.size):
data = self._readData(str(x))
self['data.txt'].writelines([x + '\n' for x in data])
# =============================================================================
# Functions
# =============================================================================
def getCurWindowText():
return win32gui.GetWindowText(win32gui.GetForegroundWindow())
# Functions to Parse WC3 text files
def sendChatMessage(message, speed):
"""
Send a chat message in Warcraft III by typing ENTER + MESSAGE + ENTER
"""
press('ENTER')
write(message, speed)
press('ENTER')
def pasteChatMessage(speed):
press('ENTER')
#/speed)
press('v',speed)
# keyUp(Base['CTRL'])
press('ENTER')
import pyperclip
def typeSaveData(save_data, speed):
"""
Recieves a list of strings. Sends each string as a chat message in-game.
Returns false if the WC3 window is not in focus while typing.
Returns true upon successfully finishing the typing routine.
"""
keybd_event(Base['CTRL'], 0, 0, 0)
time.sleep(0.05*128/speed)
for line_data in save_data:
if getCurWindowText() == "Warcraft III":
# sendChatMessage(line_data, speed=speed)
pyperclip.copy(line_data)
#time.sleep(256*(0.1 + random.random()/10.0) / float(speed))
time.sleep(0.05)
pasteChatMessage(speed)
else:
time.sleep(0.05*128/speed)#/speed)
keybd_event(Base['CTRL'], 0, 2, 0)
return False
time.sleep(0.05*128/speed)#/speed)
keybd_event(Base['CTRL'], 0, 2, 0)
return True
# =============================================================================
# Keypress Script
# Special Thanks to Piotr Dabkowski (stackoverflow user) for this script
# http://stackoverflow.com/questions/14076207/simulating-a-key-press-event-in-python-2-7
# =============================================================================
def keyUp(key):
"""Releases a key given an integer."""
if getCurWindowText() != "Warcraft III":
return
keybd_event(key, 0, 2, 0)
def keyDown(key):
"""Presses down a key given an integer."""
if getCurWindowText() != "Warcraft III":
return
keybd_event(key, 0, 1, 0)
def press(key, speed=1):
"""Presses down then releases a key given a string"""
rest_time = 0.05/speed
if key in Base:
key = Base[key]
keyDown(key)
time.sleep(rest_time)
keyUp(key)
return True
if key in Combs:
for k in Combs[key]:
keyDown(Base[k])
time.sleep(rest_time)
for k in reversed(Combs[key]):
keyUp(Base[k])
time.sleep(rest_time)
return True
return False
def write(string, speed=1):
"""Types a string of letters"""
for s in string:
press(s, speed)
time.sleep((0.1 + random.random()/10.0) / float(speed))
Combs = {
'A': [
'SHIFT',
'a'],
'B': [
'SHIFT',
'b'],
'C': [
'SHIFT',
'c'],
'D': [
'SHIFT',
'd'],
'E': [
'SHIFT',
'e'],
'F': [
'SHIFT',
'f'],
'G': [
'SHIFT',
'g'],
'H': [
'SHIFT',
'h'],
'I': [
'SHIFT',
'i'],
'J': [
'SHIFT',
'j'],
'K': [
'SHIFT',
'k'],
'L': [
'SHIFT',
'l'],
'M': [
'SHIFT',
'm'],
'N': [
'SHIFT',
'n'],
'O': [
'SHIFT',
'o'],
'P': [
'SHIFT',
'p'],
'R': [
'SHIFT',
'r'],
'S': [
'SHIFT',
's'],
'T': [
'SHIFT',
't'],
'U': [
'SHIFT',
'u'],
'W': [
'SHIFT',
'w'],
'X': [
'SHIFT',
'x'],
'Y': [
'SHIFT',
'y'],
'Z': [
'SHIFT',
'z'],
'V': [
'SHIFT',
'v'],
'Q': [
'SHIFT',
'q'],
'?': [
'SHIFT',
'/'],
'>': [
'SHIFT',
'.'],
'<': [
'SHIFT',
','],
'"': [
'SHIFT',
"'"],
':': [
'SHIFT',
';'],
'|': [
'SHIFT',
'\\'],
'}': [
'SHIFT',
']'],
'{': [
'SHIFT',
'['],
'+': [
'SHIFT',
'='],
'_': [
'SHIFT',
'-'],
'!': [
'SHIFT',
'1'],
'@': [
'SHIFT',
'2'],
'#': [
'SHIFT',
'3'],
'$': [
'SHIFT',
'4'],
'%': [
'SHIFT',
'5'],
'^': [
'SHIFT',
'6'],
'&': [
'SHIFT',
'7'],
'*': [
'SHIFT',
'8'],
'(': [
'SHIFT',
'9'],
')': [
'SHIFT',
'0']}
Base = {
'0': 48,
'1': 49,
'2': 50,
'3': 51,
'4': 52,
'5': 53,
'6': 54,
'7': 55,
'8': 56,
'9': 57,
'a': 65,
'b': 66,
'c': 67,
'd': 68,
'e': 69,
'f': 70,
'g': 71,
'h': 72,
'i': 73,
'j': 74,
'k': 75,
'l': 76,
'm': 77,
'n': 78,
'o': 79,
'p': 80,
'q': 81,
'r': 82,
's': 83,
't': 84,
'u': 85,
'v': 86,
'w': 87,
'x': 88,
'y': 89,
'z': 90,
'.': 190,
'-': 189,
',': 188,
'=': 187,
'/': 191,
';': 186,
'[': 219,
']': 221,
'\\': 220,
"'": 222,
'ALT': 18,
'TAB': 9,
'CAPSLOCK': 20,
'ENTER': 13,
'BS': 8,
'CTRL': 17,
'ESC': 27,
' ': 32,
'END': 35,
'DOWN': 40,
'LEFT': 37,
'UP': 38,
'RIGHT': 39,
'SELECT': 41,
'PRINTSCR': 44,
'INS': 45,
'DEL': 46,
'LWIN': 91,
'RWIN': 92,
'LSHIFT': 160,
'SHIFT': 161,
'LCTRL': 162,
'RCTRL': 163,
'VOLUP': 175,
'DOLDOWN': 174,
'NUMLOCK': 144,
'SCROLL': 145}
# End of borrowed script