def __init__(self, _id, trigger, keys, count=2, interval=0.5, *args, **kwargs): if callable(trigger): self.__trigger = trigger else: raise TypeError('Wrong type, "trigger" must be a function.') try: keys = set(keys) self.__keys = [key if isinstance(key, Key) else KeyCode(char=key[0]) for key in keys] except Exception: raise TypeError('Wrong type, "keys" must be a list, tuple or set, ' 'and the type of its element must be "Key" or char.') if not self.__keys: raise ValueError('Wrong value, "keys" must be a Non empty list.') if 1 == len(self.__keys): if isinstance(count, int) and 0 < count: self.__count = count else: raise ValueError('Invalid value, "count" must be a positive integer.') if isinstance(interval, float) and 0 < interval < 1: self.__interval = interval else: raise ValueError('Invalid value, "interval" must be between 0 and 1.') else: self.__count = 2 self.__interval = 0.5 self.__id = _id self.__args = args self.__kwargs = kwargs
def __init__(self, actionOn: str, keyboard="", *args, **kwargs): self.key = KeyCode.from_char(actionOn) self.keyboard = keyboard super().__init__(*args, **kwargs) logger.info( f"{self.__class__.__name__} on \'{actionOn}\', {f'hold for {self.duration}s ' if self.hold else ''}then take a break of {self.breaktime}s. Repeat for {self.repeat} times." )
def handleRelease(key): print('Released: {}'.format(key)) # 종료 if key == KeyCode(char='5'): notice_exit_program() return False
def get_event() -> Event: handlers = { Key.left: MoveLeftEvent, Key.right: MoveRightEvent, Key.down: MoveDownEvent, Key.esc: GameExitEvent, KeyCode(char='z'): LeftSpinEvent, KeyCode(char='x'): RightSpinEvent } try: current_key = __class__.__current_key __class__.__current_key = None return handlers[current_key]() except KeyError: return VoidEvent()
def _start_listener(self) -> None: self.trigger_listener = TriggerListener( KeyCode.from_char("\\"), trigger_callback=None, exit_callback=self._exit_callback, ) self.trigger_listener.start()
def start_clicking(self): global pressed_key if pressed_key == KeyCode(char='c'): self.screen_cnt, self.screen_cords = scan( np.array(ImageGrab.grab(bbox=None))) self.running = True
def on_press(key): global Destination_Stop if key == Key.enter and Destination_Stop != '': ws.send( json.dumps({ "origin": Current_Stop, "destination": int(Destination_Stop), "redirect": True })) Destination_Stop = '' elif key == Key.backspace: Destination_Stop = Destination_Stop[0:len(Destination_Stop) - 1] ws.send( json.dumps({ "origin": Current_Stop, "destination": Destination_Stop, "digit": -1, "redirect": False })) else: for digit in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: if key == KeyCode(char=digit): Destination_Stop += digit ws.send( json.dumps({ "origin": Current_Stop, "destination": Destination_Stop, "digit": digit, "redirect": False }))
def on_release(self, key): # print('{0} released'.format(key)) if key in self.key_pressed: self.key_pressed.remove(key) if key == KeyCode.from_char('t'): self.listener.stop() return False
def start(com): global auto_mode com[0] = auto_mode global master #master = tkinter.Tk() #is_on = tkinter.Label(text="MACROS PAUSED", fg='black') global s_key, delay, stop_key db = sqlite3.connect("./config.db") cursor = db.cursor() cursor.execute('''SELECT id FROM conf WHERE name = ?''', ("pause", )) x = cursor.fetchone()[0] s_key = KeyCode.from_vk(x) """cursor.execute('''SELECT id FROM conf WHERE name = ?''', ("stop",)) x = cursor.fetchone()[0] stop_key = KeyCode.from_vk(x)""" cursor.execute('''SELECT cnt FROM nums WHERE name = ?''', ("cps", )) x = cursor.fetchone()[0] delay = 1 / max(x, 1) #delay = delay / 1000 keyboard_listener.start() mouse_listener.start() click(com) #master.mainloop() keyboard_listener.join() mouse_listener.join()
def drink_life_potions(self): print("Starting drink_life_potions") while self.RUN: if not self.TOGGLE: sleep(0.1) continue self.vision.capture_window(self.potions_box) life_10 = self.vision.pcat(x=105, y=15, channel="red", threshold=70) life_20 = self.vision.pcat(x=105, y=25, channel="red", threshold=80) life_30 = self.vision.pcat(x=105, y=35, channel="red", threshold=80) life_40 = self.vision.pcat(x=105, y=45, channel="red", threshold=80) life_50 = self.vision.pcat(x=102, y=55, channel="red", threshold=80) life_60 = self.vision.pcat(x=102, y=65, channel="red", threshold=80) life_70 = self.vision.pcat(x=105, y=75, channel="red", threshold=80) life_80 = self.vision.pcat(x=105, y=85, channel="red", threshold=80) life_90 = self.vision.pcat(x=105, y=95, channel="red", threshold=80) life_100 = self.vision.pcat(x=105, y=105, channel="red", threshold=80) life_110 = self.vision.pcat(x=105, y=115, channel="red", threshold=80) life_120 = self.vision.pcat(x=105, y=125, channel="red", threshold=80) life_130 = self.vision.pcat(x=105, y=135, channel="red", threshold=80) life_140 = self.vision.pcat(x=105, y=145, channel="red", threshold=70) life_150 = self.vision.pcat(x=105, y=155, channel="red", threshold=70) life_160 = self.vision.pcat(x=105, y=165, channel="red", threshold=60) life_170 = self.vision.pcat(x=105, y=175, channel="red", threshold=60) life_1 = self.vision.pcat(x=298, y=175, channel="red", threshold=60) life_2 = self.vision.pcat(x=338, y=175, channel="red", threshold=60) in_game = self.vision.pcat(238, 126, channel="green", threshold=70) if not life_120 and in_game: self.keyboard.quit() print("Emergency exit (life too low)") if not life_30: if life_1: self.keyboard.key(KeyCode.from_vk(self.KEYCODES[1])) print("Drinking from LP1") sleep(0.1) elif life_2: self.keyboard.key(KeyCode.from_vk(self.KEYCODES[2])) print("Drinking from LP2") sleep(0.1) elif in_game: self.keyboard.quit() print("Emergency exit (No more potions)")
def set_ended_key(self): """ sets the list of buttons on the keyboard that you can finish work on """ for key in list(Key): self.ended_key.append(key) for i in range(97, 122): self.ended_key.append(KeyCode.from_char(chr(i))) for key in self.arrows: self.ended_key.remove(key)
def on_release(self, key: KeyCode): # print('{0} release'.format(key)) keychar = str(key).replace("\'", "").lower() if keychar in self.key_pressed: self.key_pressed.remove(keychar) if key == KeyCode.from_char('t'): # Stop listenerd return False
def handle_hex(key): try: if isinstance(key, KeyCode) and '\\' in repr(key): #fix A-Z hex key issue when pressing Ctrl return KeyCode(char=chr(96 + ord(key.char))) except Exception as e: print('[ERROR] Exception:', e) return key
def on_press(key): data = ManualData() if key == Key.up: data.manualDrive = 1 print("Set command to drive forward") sendData(sock, data) elif key == Key.down: data.manualDrive = -1 print("Set command to drive backwards") sendData(sock, data) elif key == KeyCode.from_char('1'): data.drive = 100 print("Set command to drive backwards") sendData(sock, data) elif key == KeyCode.from_char('2'): data.drive = -100 print("Set command to drive backwards") sendData(sock, data) elif key == Key.right: data.manualTurn = 1 print("Set command to turn right") sendData(sock, data) elif key == Key.left: data.manualTurn = -1 print("Set command to turn left") sendData(sock, data) elif key == KeyCode.from_char('e'): data.dig = True print("Set command to excavate") sendData(sock, data) elif key == KeyCode.from_char('p'): data.packin = True print("Set command to pack in") sendData(sock, data) elif key == KeyCode.from_char('d'): data.dump = True print("Set command to dump") sendData(sock, data) elif key == Key.space: data.stop = True print("Set command to stop") sendData(sock, data) elif key == KeyCode.from_char('f'): data.forwardScan = True print("Scan LiDAR forward") sendData(sock, data) elif key == KeyCode.from_char('b'): data.backwardScan = True print("Scan LiDAR backwards") sendData(sock, data) elif key == KeyCode.from_char('a'): data.autonomousMode = True print("switch from manual to autonomous") sendData(sock, data) else: print("Not a valid command")
def sp(name): try: return getattr(Key, str(name)) except: try: return KeyCode(media_keys[str(name)]) except: return None
def move(self): if (self.screen.getmaxyx()[0] <= self.cmd_count): self.screen_clear() self.msg.linear.x = (self.flags[KeyCode(char='w')] - self.flags[KeyCode(char='s')]) * self.speed self.msg.angular.z = (self.flags[KeyCode(char='a')] - self.flags[KeyCode(char='d')]) * self.rot self.pub.publish(self.msg) text = "linear x:" + str(round(self.msg.linear.x, 2)) text += ", y:" + str(round(self.msg.linear.y, 2)) text += ", z:" + str(round(self.msg.linear.z, 2)) text += " angular x:" + str(round(self.msg.angular.x, 2)) text += ", y:" + str(round(self.msg.angular.y, 2)) text += ", z:" + str(round(self.msg.angular.z, 2)) self.screen.addstr(self.cmd_count, 0, text) self.screen.refresh() self.cmd_count += 1
def on_press(key): if key == Key.right: state.pose.position.y += .1 elif key == Key.left: state.pose.position.y -= .1 elif key == Key.up: state.pose.position.x += .1 elif key == Key.down: state.pose.position.x -= .1 elif key == Key.page_up: state.pose.position.z += .1 elif key == Key.page_down: state.pose.position.z -= .1 elif key == KeyCode.from_char('d'): rotate_state(-.1) elif key == KeyCode.from_char('q'): rotate_state(.1)
def take_screenshot(): global x print('Executing...') #if __name__ == '__main__': pyautogui.screenshot('image' + str(x) + '.png') myScreenshot = Image.open('image' + str(x) + '.png') text = pytesseract.image_to_string(myScreenshot, lang='eng') print('My text is : ') print(text) x += 1 print('Done') if Key.shift in current_keys: on_release(Key.shift) if KeyCode(char='a') in current_keys: on_release(KeyCode(char='a')) if KeyCode(char='A') in current_keys: on_release(KeyCode(char='A'))
def on_release(key): if key == Key.space: message = '0' s.send(str.encode(message)) elif key == KeyCode(char='1'): clear() message = '1' s.send(str.encode(message))
def _populate_tools(self): tools = { "brush": 'b', "bucket": 'f', "crop": 'c', "geo": [Key.ctrl, Key.alt, '.'], "select": [Key.ctrl, 'r'], "eraser": ['b', 'e'], "move": 't', "brush1": [Key.ctrl, Key.alt, KeyCode.from_vk(97)], "brush2": [Key.ctrl, Key.alt, KeyCode.from_vk(98)], "brush3": [Key.ctrl, Key.alt, KeyCode.from_vk(99)], "brush4": [Key.ctrl, Key.alt, KeyCode.from_vk(100)], "brush5": [Key.ctrl, Key.alt, KeyCode.from_vk(101)], "brush6": [Key.ctrl, Key.alt, KeyCode.from_vk(102)], "brush7": [Key.ctrl, Key.alt, KeyCode.from_vk(103)], "geo1": [Key.ctrl, Key.alt, '.'], "geo2": [Key.ctrl, Key.alt, ';'], "geo3": [Key.ctrl, '='], "geo4": [Key.ctrl, Key.alt, '~'], "geo5": [Key.ctrl, Key.alt, "'"], "selection1": [Key.ctrl, 'r'], "selection2": 'j', "selection3": [Key.ctrl, Key.alt, '\\'], "selection4": [Key.ctrl, Key.alt, ']'] } return tools
def update_key(self, what, value): if len(value.strip()) > 1: self.key_error_callback(what, value) else: key = KeyCode.from_char(value[0]) if what is SetupForm.action_widgets.LK: self.left_key = key else: self.right_key = key
def run(self): with open(self.file_name, 'r', encoding='utf-8') as file: keyboard_exec = Controller() line = file.readline() time.sleep(3) while line: obj = json.loads(line) if obj['name'] == 'keyboard': if obj['event'] == 'press': keyboard_exec.press(KeyCode.from_vk(obj['vk'])) time.sleep(0.01) elif obj['event'] == 'release': keyboard_exec.release(KeyCode.from_vk(obj['vk'])) time.sleep(0.01) line = file.readline() startExecuteBtn['text'] = '回放' startExecuteBtn['state'] = 'normal'
def __init__(self, key): """Initialize ARKey class.""" self.isctrl = False self.ischar = False if isinstance(key, (Key, KeyCode)): self.isctrl = (key == Key.ctrl_l) or (key == Key.ctrl_r) self.key = key elif isinstance(key, int): try: self.key = Key(KeyCode.from_vk(key)) except ValueError: self.key = KeyCode.from_vk(key) elif isinstance(key, str): self.key = KeyCode.from_char(key)
def randomize(n=20): from random import choice random_moves = deque([]) for _ in range(n): key = choice(['u', 'd', 'r', 'l', 'f', 'b', 'shift']) random_moves.append(KeyCode( char=key)) if key != 'shift' else random_moves.append(Key.shift) for n, move in enumerate(random_moves): on_press(move)
def run(self): if not os.path.exists(self.file_name): os.mkdir(self.file_name) with open(self.file_name, 'r', encoding='utf-8') as file: keyboard_exec = KeyBoardController() line = file.readline() # if not line: # print('no key') # return while line: if len(line) == 1: line = file.readline() continue obj = json.loads(line) # print(obj) if obj['name'] == 'keyboard': delay = obj['time'] / self.speed if delay > 1: self.listening_sleep(delay) else: time.sleep(delay) if obj['event'] == 'press': keyboard_exec.press(KeyCode.from_vk(obj['vk'])) elif obj['event'] == 'release': keyboard_exec.release(KeyCode.from_vk(obj['vk'])) if self.stoper: print('keystoper') # self.stoper = False break line = file.readline() keyboard_exec.release(keyboard.Key.ctrl) keyboard_exec.release(keyboard.Key.shift) keyboard_exec.release(keyboard.Key.alt) while self.parent.mouseActionrunner.isRunning(): time.sleep(0.1) # print('waiting mouse stop') print('动作播放完一次') if not self.stoper: self.end_run_a_round_signal.emit()
def actions(board): return [ [Key.left, board.move_left], [Key.right, board.move_right], [Key.up, KeyCode(char="x"), board.rotate_clockwise], [Key.ctrl, KeyCode(char="z"), board.rotate_counter_clockwise], [Key.space, board.hard_drop], [Key.shift, KeyCode(char="c"), board.hold], [Key.enter, display.start], [KeyCode(char="h"), display.controls], [KeyCode(char="e"), display.exit], [KeyCode(char="p"), display.pause], [KeyCode(char="r"), display.resume], [KeyCode(char="s"), display.leave_game_over], [KeyCode(char="l"), display.leave_game], [KeyCode(char="q"), shutdown] ] def listen():
def on_press(self, key): #print(f"pressed {key}") # use arrow keys to drive, space key to stop # feel free to add more keys if key == KeyCode.from_char('w'): self.directions[0] = True elif key == KeyCode.from_char('s'): self.directions[1] = True elif key == KeyCode.from_char('a'): self.directions[2] = True elif key == KeyCode.from_char('d'): self.directions[3] = True #elif key == Key.space: # self.signal_stop = True elif key == Key.shift: self.speed_up = True self.send_drive_signal()
def __init__(self, mouse_controller, button=Button.left): self.operation_delay = float(settings_dict['delay_between_operations']) #print("the delay between operation is: ", float(settings_dict['delay_between_operations'])) self.button = button self.mouse_controller = mouse_controller self.clicking = False self.program_running = True self.cycle_delay = float(settings_dict["delay_between_operations"]) self.working_hours = int(settings_dict["working_hours"]) self.working_minutes = int(settings_dict["working_minutes"]) self.miss_pressed_count = 0 self.max_cycles = int(settings_dict["max_cycles"]) #can't save this value... #self.start_pause_key = settings_dict["start_pause_key"] #self.quit_program_key = settings_dict["quit_program_key"] self.start_pause_key = KeyCode( char=str(settings_dict["start_pause_key"])) self.quit_program_key = KeyCode( char=str(settings_dict["quit_program_key"]))
def on_press(key): global s global exitKey try: if key == Key.enter: exitKey = "Enter" if key == KeyCode.from_char('s'): run() except AttributeError: raise Exception
def combo_press(vk): global combo_vk global quit combo_vk = vk # Press `ESC` to quit if vk == 27: quit = True return print('---- start combo -----', vk) while vk == combo_vk: keyboard_ctl.press(KeyCode.from_vk(vk)) time.sleep(0.002) assert vk == combo_vk keyboard_ctl.release(KeyCode.from_vk(vk)) time.sleep(0.1) print('--------------------------')
def keycode(self, name, is_dead): """Resolves a key description to a value that can be passed to :meth:`pynput.keyboard.Controller.press` and :meth:`~pynput.keyboard.Controller.release`. :param str name: The name of the key. This should typically be the actual character requested. If it starts with ``'<'`` and ends with ``'>'``, the key value is looked up in :class:`pynput.keyboard.Key`, otherwise it is passed straight to :meth:`pynput.keyboard.Controller.press`. :return: a key value """ if is_dead: return KeyCode.from_dead(name) elif name[0] == '<' and name[-1] == '>': return Key[name[1:-1]] else: return name