def bailie(): event_list = [] event_list.append( keyboard.KeyboardEvent('down', 36, name='j', time=0.0, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 36, name='j', time=0.01, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 36, name='j', time=0.02, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 36, name='j', time=0.20, modifiers=False, is_keypad=False)) keyboard.play(event_list)
def release_all_keys(): event_list = [] event_list.append( keyboard.KeyboardEvent('up', 30, name='a', time=0.0, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 31, name='s', time=0.01, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 32, name='d', time=0.02, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 17, name='w', time=0.03, modifiers=False, is_keypad=False)) keyboard.play(event_list)
def recordSkill(): keyboard.start_recording() time.sleep(5) eventlist = keyboard.stop_recording() i = 0 first_time = 0 print("event_list = []") if eventlist[0].event_type == "down" and eventlist[0].name == 'x': global practice global replay_state practice = bool(1 - practice) replay_state = bool(1 - replay_state) print("Practice state") else: for e in eventlist: if first_time == 0: first_time = e.time t = e.time - first_time print( "event_list.append(keyboard.KeyboardEvent('{}', {}, name='{}',time = {}, modifiers={}, is_keypad={}))" .format(e.event_type, e.scan_code, e.name, round(t, 2), False, False)) print("keyboard.play(event_list)") keyboard.play(eventlist)
def test_play_delay(self): last_time = time.time() events = [ make_event(KEY_DOWN, 'a', 1, 100), make_event(KEY_UP, 'a', 1, 100.01) ] keyboard.play(events, 1) self.do([], d_a + u_a) self.assertGreater(time.time() - last_time, 0.005)
def playback(recorded, user_time): time.sleep(5) print("Keys Playing...") time_end = time.time() + 60 * user_time while time.time() < time_end: time.sleep(1) keyboard.play(recorded) print("Keys played for " + str(user_time) + " minute(s)") print("recorder resetting...") time.sleep(1)
def execute(macro, speedup=1): """ For each key event in the macro, press/release This occurs with a strict timing attached for each executed event :param macro: List of time ordered keyboard events :param speedup Integer speed up value for playback. Default = 1 :return: None """ keyboard.play(macro, speed_factor=speedup)
def dummy_record(): current_slot = 0 record_slots = [] for i in range(0, TOTAL_SLOTS): record_slots.append(0) while True: for event in get_gamepad(): try: if event.code == record and event.state > int(0): print('Record P2') print("Press the", stop, "button to quit record") record_slots[current_slot] = keyboard.record(until=stop) if len(record_slots[current_slot]) < 2: record_slots[current_slot] = 0 print('Nothing recorded') print('End record') elif event.code == play and event.state > int(0): if record_slots[current_slot] != 0: print('Start replay', current_slot + 1) keyboard.play(record_slots[current_slot]) print('End replay') else: print('This slot is empty') elif event.code == random_play and event.state > int(0): found = False for i in range(0, TOTAL_SLOTS): if record_slots[i]: found = True if found: random_slot = randint(0, TOTAL_SLOTS - 1) while not record_slots[random_slot]: random_slot = randint(0, TOTAL_SLOTS - 1) print('Start random replay', random_slot + 1) keyboard.play(record_slots[random_slot]) print('End replay') else: print('No slot is recorded') elif event.code == prev_record and event.state > int(0): current_slot -= 1 if current_slot < 0: current_slot = TOTAL_SLOTS - 1 print('Switched to slot ', current_slot + 1) elif event.code == next_record and event.state > int(0): current_slot += 1 if current_slot > TOTAL_SLOTS - 1: current_slot = 0 print('Switched to slot ', current_slot + 1) except: print("Nothing recorded") pass
def replay(): # pyautogui.moveTo(width/2,height/2) #move mouse to middle of screen time.sleep(.2) base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) keyboard.start_recording() keyboard.stop_recording() mouse_events = pickle.load(open(base_dir +r'/events/mouse.p','rb')) keyboard_events = pickle.load(open(base_dir +r'/events/keyboard.p','rb')) print(keyboard_events) #Keyboard threadings: k_thread = threading.Thread(target = lambda :keyboard.play(keyboard_events[:-1])) k_thread.start() #Mouse threadings: m_thread = threading.Thread(target = lambda :mouse.play(mouse_events)) m_thread.start() #waiting for both threadings to be completed m_thread.join() k_thread.join()
def dummy_record(): while True: for event in get_gamepad(): try: if event.code == record and event.state > int(0): print('Record P2') print("Press the", stop, "button to quit record") recorded = keyboard.record(until=stop) print('End record') elif event.code == play and event.state > int(0): print('Start replay') keyboard.play(recorded) print('End replay') except: print("Nothing recorded") pass
def playback(record_keys, user_time, playback_speed): #thread1 global pause_bool time.sleep(5) thread2 = Thread(target = interrupt, args=[], daemon=True) # interrupt thread time_end = time.time() + 60 *user_time time.sleep(1) thread2.start() print("Keys Playing...") while time.time() < time_end: if pause_bool == 'y': keyboard.play(record_keys, speed_factor=playback_speed) if pause_bool == 'n': pause_bool = input('Playback paused, continue? (y/n):') if pause_bool == 'y': continue if pause_bool == 'n': sys.exit(0)
def long_up_down_flag(): event_list = [] event_list.append( keyboard.KeyboardEvent('down', 17, name='w', time=0.0, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 17, name='w', time=0.02, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 31, name='s', time=0.04, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 36, name='j', time=0.04, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 36, name='j', time=0.14, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 31, name='s', time=0.14, modifiers=False, is_keypad=False)) keyboard.play(event_list)
def lr_flyLag(): event_list = [] event_list.append( keyboard.KeyboardEvent('down', 32, name='d', time=0.0, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 32, name='d', time=0.02, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 32, name='d', time=0.03, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 37, name='k', time=0.04, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 32, name='d', time=0.07, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 37, name='k', time=0.07, modifiers=False, is_keypad=False)) keyboard.play(event_list)
def rl_flyLag(): event_list = [] event_list.append( keyboard.KeyboardEvent('down', 30, name='a', time=0.0, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 30, name='a', time=0.02, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 30, name='a', time=0.05, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('down', 37, name='k', time=0.05, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 30, name='a', time=0.08, modifiers=False, is_keypad=False)) event_list.append( keyboard.KeyboardEvent('up', 37, name='k', time=0.08, modifiers=False, is_keypad=False)) keyboard.play(event_list)
def tuQiu(): e1 = keyboard.KeyboardEvent('down', 31, name='s', time=0.94, modifiers=False, is_keypad=False) e2 = keyboard.KeyboardEvent('down', 32, name='d', time=0.96, modifiers=False, is_keypad=False) e3 = keyboard.KeyboardEvent('down', 36, name='j', time=0.98, modifiers=False, is_keypad=False) e4 = keyboard.KeyboardEvent('up', 32, name='d', time=1.00, modifiers=False, is_keypad=False) e5 = keyboard.KeyboardEvent('up', 36, name='j', time=1.03, modifiers=False, is_keypad=False) e6 = keyboard.KeyboardEvent('up', 31, name='s', time=1.07, modifiers=False, is_keypad=False) event_list = [e1, e2, e3, e4, e5, e6] keyboard.play(event_list)
def recordNew(rec): global until_key print('wait') keyboard.wait(record_key, True, trigger_on_release=True) # Record keymap print('record keymap') keymap = keyboard.read_key() print('{}'.format(keymap)) # Record the keystrokes print('record macro') rec[keymap] = keyboard.record(until=until_key)[1:-1] print(rec[keymap]) # Add hotkey keyboard.add_hotkey('{}'.format(keymap), lambda: keyboard.play(rec[keymap]))
def recordNew(rec): global until_key # Record keymap print('record keymap') #keymap = keyboard.record(until=until_key)[0].name keymap = keyboard.read_hotkey() print('{}'.format(keymap)) # Record the keystrokes print('record macro') #rec[keymap] = keyboard.record(until=until_key) #rec[keymap] = keyboard.record(until=until_key,trigger_on_release=True) rec[keymap] = keyboard.record(trigger_on_release=True) print(rec[keymap]) # Add hotkey keyboard.add_hotkey('{}'.format(keymap), lambda: keyboard.play(rec[keymap]))
def test_record_play(self): from threading import Thread, Lock lock = Lock() lock.acquire() self.recorded = None def t(): self.recorded = keyboard.record('esc') lock.release() Thread(target=t).start() self.click('a') self.press('shift') self.press('b') self.release('b') self.release('shift') self.press('esc') lock.acquire() expected = [(KEY_DOWN, 'a'), (KEY_UP, 'a'), (KEY_DOWN, 'shift'), (KEY_DOWN, 'b'), (KEY_UP, 'b'), (KEY_UP, 'shift'), (KEY_DOWN, 'esc')] for event_recorded, expected_pair in zip(self.recorded, expected): expected_type, expected_name = expected_pair self.assertEqual(event_recorded.event_type, expected_type) self.assertEqual(event_recorded.name, expected_name) keyboard._pressed_events.clear() keyboard.play(self.recorded, speed_factor=0) self.assertEqual(self.flush_events(), [(KEY_DOWN, 'a'), (KEY_UP, 'a'), (KEY_DOWN, 'shift'), (KEY_DOWN, 'b'), (KEY_UP, 'b'), (KEY_UP, 'shift'), (KEY_DOWN, 'esc')]) keyboard.play(self.recorded, speed_factor=100) self.assertEqual(self.flush_events(), [(KEY_DOWN, 'a'), (KEY_UP, 'a'), (KEY_DOWN, 'shift'), (KEY_DOWN, 'b'), (KEY_UP, 'b'), (KEY_UP, 'shift'), (KEY_DOWN, 'esc')]) # Should be ignored and not throw an error. keyboard.play([FakeEvent('fake type', 'a')])
def play_shortcut(name): selectedShortcut = 0 totalShortcuts = 0 with open("name_shortcuts.txt", 'r') as nfile: for line in nfile.readlines(): if name in line: selectedShortcut = totalShortcuts totalShortcuts += 1 kfile = open("keyboard_shortcuts.txt", 'rb+') for i in range(selectedShortcut + 1): keyboard_events = load(kfile) kfile.close() mfile = open("mouse_shortcuts.txt", 'rb+') for j in range(selectedShortcut + 1): mouse_events = load(mfile) mfile.close() #just to see what inputs will be done can be removed #-------------------------------------------------- print(str(mouse_events)) print(str(keyboard_events)) #-------------------------------------------------- #Uses threading to play both mouse and keyboard movements at the same time m_thread = threading.Thread( target=lambda: mouse.play(mouse_events, speed_factor=1)) k_thread = threading.Thread( target=lambda: keyboard.play(keyboard_events, speed_factor=1)) m_thread.start() #This one line of code fixed the keyboard inputs not working (even though the mouse inputs did) keyboard._listener.start_if_necessary() k_thread.start() m_thread.join() k_thread.join()
) running = True print("Playing the PKR in 5") seqExt.countdown() if not loopCnt: print("Playing recording once") loopCnt = 1 else: loopCnt = int(loopCnt) cycle = 1 timesToRun = "infinity" if loopCnt < 0 else loopCnt while running: if loopCnt != 1: print("Playing recording for time " + str(cycle) + '/' + str(timesToRun)) keyboard.play(pkr) if cycle == timesToRun: running = False cycle += 1 elif option == 'j': fName = seqExt.nameFile(recType="pkr") seqExt.PKRtoFile(pkr, fName) elif option == 'k': print("\nThe script will start recording your keypresses in 5") seqExt.countdown() print( "Your keypresses are now being recorded. Press ` (backtick) in any application to stop." ) pkr = keyboard.record(until="`") print("\nRecording session ended. What do you want to do now?") option = '' firstTime = True
def keySimulator(keys): #Perform Actions stored in the log keyboard.play(keys, speed_factor=1)
def playKeys(saveFile): with open(saveFile, "rb" )as file: data = pickle.load(file) keyboard.play(data) return
def _play_keyboard(self): logger.debug("Klavye kaydı oynatılıyor") keyboard.play(self.events.keyboard_events)
# multi-key, windows+d as example shows the desktop in Windows machines keyboard.send("windows+d") # send ALT+F4 in the same time, and then send space, # (be carful, this will close any current open window) keyboard.send("alt+F4, space") # press CTRL button keyboard.press("ctrl") # release the CTRL button keyboard.release("ctrl") # sends artificial keyboard events to the OS # simulating the typing of a given text # setting 0.1 seconds to wait between keypresses to look fancy keyboard.write("Python Programming is always fun!", delay=0.1) # record all keyboard clicks until esc is clicked events = keyboard.record('esc') # play these events keyboard.play(events) # print all typed strings in the events print(list(keyboard.get_typed_strings(events))) # log all pressed keys keyboard.on_release(lambda e: print(e.name)) # remove all keyboard hooks in use keyboard.unhook_all()
def test_play_stash(self): self.do(d_ctrl) keyboard.play(d_a+u_a, 0) self.do([], u_ctrl+d_a+u_a+d_ctrl)
time.sleep(0.5) waitTime = input("\nHow many seconds between press and release (0.8 is default): ") waitTime = float(waitTime) print("Waiting for 5 seconds...") time.sleep(5) print("Starting the script!") running = True while(running): keyboard.press('w') time.sleep(waitTime) keyboard.release('w') keyboard.press('a') time.sleep(waitTime) keyboard.release('a') keyboard.press('s') time.sleep(waitTime) keyboard.release('s') keyboard.press('d') time.sleep(waitTime) keyboard.release('d') elif (option == 'c'): files = os.listdir("local/movSeqs/") i = 0 for filename in files: print(i, ". ", filename, sep='') i = i + 1 fto = input("Type the number of the movSeq you want to run and press enter: ") #file to open filename = files[int(fto)] file = 'gotta come back to this later' keyboard.play()
def test_record_play(self): from threading import Thread, Lock lock = Lock() lock.acquire() self.recorded = None def t(): self.recorded = keyboard.record("esc") lock.release() Thread(target=t).start() self.click("a") self.press("shift") self.press("b") self.release("b") self.release("shift") self.press("esc") lock.acquire() expected = [ (KEY_DOWN, "a"), (KEY_UP, "a"), (KEY_DOWN, "shift"), (KEY_DOWN, "b"), (KEY_UP, "b"), (KEY_UP, "shift"), (KEY_DOWN, "esc"), ] for event_recorded, expected_pair in zip(self.recorded, expected): expected_type, expected_name = expected_pair self.assertEqual(event_recorded.event_type, expected_type) self.assertEqual(event_recorded.name, expected_name) keyboard._pressed_events.clear() keyboard.play(self.recorded, speed_factor=0) self.assertEqual( self.flush_events(), [ (KEY_DOWN, "a"), (KEY_UP, "a"), (KEY_DOWN, "shift"), (KEY_DOWN, "b"), (KEY_UP, "b"), (KEY_UP, "shift"), (KEY_DOWN, "esc"), ], ) keyboard.play(self.recorded, speed_factor=100) self.assertEqual( self.flush_events(), [ (KEY_DOWN, "a"), (KEY_UP, "a"), (KEY_DOWN, "shift"), (KEY_DOWN, "b"), (KEY_UP, "b"), (KEY_UP, "shift"), (KEY_DOWN, "esc"), ], ) # Should be ignored and not throw an error. keyboard.play([FakeEvent("fake type", "a")])
def test_play_nodelay(self): keyboard.play(d_a+u_a, 0) self.do([], d_a+u_a)
def test_play_delay(self): last_time = time.time() events = [make_event(KEY_DOWN, 'a', 1, 100), make_event(KEY_UP, 'a', 1, 100.01)] keyboard.play(events, 1) self.do([], d_a+u_a) self.assertGreater(time.time() - last_time, 0.005)
def test_play_stash(self): self.do(d_ctrl) keyboard.play(d_a + u_a, 0) self.do([], u_ctrl + d_a + u_a + d_ctrl)
#!/usr/bin/env python3 import keyboard import sys keywords = ["create", "delete"] recordings = {} args = sys.argv if len(args) == 1: print("Ex: environ create python") exit() name = args[1] if name == keywords[0]: if len(args) != 3: print("Please specify a name for this recording") exit() print(f"Recording setup for {args[2]}\nPress ESC to end\n") recordings[args[2]] = keyboard.record(until='esc') keyboard.play(recordings[args[2]], speed_factor=10) elif name == keywords[1]: if len(args) != 3: print("Please specify the name of the recording to delete") printf(f"Deleting recording {args[2]}\n") del recordings[args[2]] elif len(args) == 2: print(f"Setting up environment {name}")
def test_play_nodelay(self): keyboard.play(d_a + u_a, 0) self.do([], d_a + u_a)
#!/envs/drAIver/bin/python import keyboard #keyboard.add_hotkey('p', print) while True: print(keyboard.is_pressed('p')) keyboard.press_and_release('shift+s, space') keyboard.write('The quick brown fox jumps over the lazy dog.') keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey')) # Press PAGE UP then PAGE DOWN to type "foobar". keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar')) # Blocks until you press esc. keyboard.wait('esc') # Record events until 'esc' is pressed. recorded = keyboard.record(until='esc') # Then replay back at three times the speed. keyboard.play(recorded, speed_factor=3) # Type @@ then press space to replace with abbreviation. keyboard.add_abbreviation('@@', '*****@*****.**') # Block forever, like `while True`. keyboard.wait()
# -*- coding: utf-8 -*- import keyboard import fileinput import json import sys def print_event_json(event): print(event.to_json(ensure_ascii=sys.stdout.encoding != 'utf-8')) sys.stdout.flush() keyboard.hook(print_event_json) parse_event_json = lambda line: keyboard.KeyboardEvent(**json.loads(line)) keyboard.play(parse_event_json(line) for line in fileinput.input())
elif macrolist_input == '-a': # Redoo############################################################## macro_activate = input('Enter Macro Name ->') f = open(('Macros/' + macro_activate), 'r') play_macro = f.read() f.close() macro_play = True while macro_play: clear() print(play_macro) # Redoo############################################################## print('[PRESS HOTKEY (%s) TO ACTIVATE SELECTED MACRO]' % (key)) if keyboard.is_pressed(key): keyboard.play(play_macro, speed_factor=0) macro_play = False break elif macromenu_user_input == '-b': # Redoo############################################################## new_macro_name = input('New Macro Name ->') new_macro = keyboard.record(until='escape') f = open(('Macros/' + new_macro_name), 'w+') f.write(str(new_macro)) f.close() f = open('data_macro', 'a') f.write('\n' + new_macro_name) f.close() pass
# -*- coding: utf-8 -*- import keyboard import fileinput import json import sys def print_event_json(event): # Could use json.dumps(event.__dict__()), but this way we guarantee semantic order. if event.name: print('{{"event_type": "{}", "name": "{}", "scan_code": {}, "time": {}}}'.format(event.event_type, event.name, event.scan_code, event.time)) else: print('{{"event_type": "{}", "scan_code": {}, "time": {}}}'.format(event.event_type, event.scan_code, event.time)) sys.stdout.flush() keyboard.hook(print_event_json) parse_event_json = lambda line: keyboard.KeyboardEvent(**json.loads(line)) keyboard.play(parse_event_json(line) for line in fileinput.input())