예제 #1
1
 def start(self):
     """Register hotkeys and waits for exit"""
     # The main hot_key
     keyboard.add_hotkey('esc', self.toggle_clicking)
     # Hotkeys for changing speed
     keyboard.add_hotkey('right', self.change_speed, args=(-1,))
     keyboard.add_hotkey('left', self.change_speed, args=(1,))
     keyboard.add_hotkey('up', self.change_speed, args=(0,))
     keyboard.add_hotkey('down', self.change_speed, args=(0,))
     print("Stick Click is ready.")
     print("Press CTRL+ALT to exit.")
     print("Press ESC to start/stop clicking.")
     # Exit Hotkey
     keyboard.wait('ctrl+alt')
예제 #2
0
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(100,100,400,200)
        self.setWindowTitle('M1N3')
        self.locs = []
        
        self.adding_points = False
        self.should_m1n3 = False
        self.m1n1ng = False
        self.loop_index = 0

        self.looting = False
        self.should_loot = False
        self.loot_timer = QTimer()
        self.loot_timer.timeout.connect(self.loot)

        self.m1n3_timer = QTimer()
        self.m1n3_timer.timeout.connect(self.m1n3)

        self.standby_timer = QTimer()
        self.standby_timer.timeout.connect(self.standby)
        self.standby_timer.start(1000)

        keyboard.add_hotkey('ctrl+s', self.add_point)
        keyboard.add_hotkey('ctrl+t', self.toggle_add)
        keyboard.add_hotkey('ctrl+p', self.print_points)
        keyboard.add_hotkey('ctrl+m', self.toggle_should_m1n3)
        keyboard.add_hotkey('ctrl+`', self.toggle_should_loot)
        self.show()
예제 #3
0
 def test_add_hotkey_single_step_nonsuppress_repeated(self):
     queue = keyboard._queue.Queue()
     keyboard.add_hotkey('ctrl+shift+a+b', lambda: queue.put(True), suppress=False)
     self.do(d_shift+d_ctrl+d_a+d_b)
     self.do(d_shift+d_ctrl+d_a+d_b)
     self.assertTrue(queue.get(timeout=0.5))
     self.assertTrue(queue.get(timeout=0.5))
예제 #4
0
파일: qsorder.py 프로젝트: k3it/qsorder
def hotkey():
    global nopyhk
    if nopyhk:
        return
    # add hotkey
    try:
        keyboard.add_hotkey('ctrl+alt+' + HOTKEY.lower(), manual_dump)
    except:
        nopyhk = True
예제 #5
0
def start_app():
    logging.debug(
        '\nVariables at start:\nEncoding: {}\nHotkey: {}\nSwitch combination: {}\nLogging level: {}'.format(
            options['encoding'],
            options['hotkey'],
            options['switch_combination'],
            options['log_level']))
    global running
    logging.info('App is running...')
    keyboard.add_hotkey(options['hotkey'], main)
    running = True
예제 #6
0
파일: __init__.py 프로젝트: exaile/exaile
    def __init__(self, exaile):
        import keyboard
        from xl.player import PLAYER, QUEUE

        self.handlers = [
            # use lambda here because gi function isn't hashable
            keyboard.add_hotkey(
                'select media', lambda: exaile.gui.main.window.present()
            ),
            keyboard.add_hotkey('stop media', PLAYER.stop),
            keyboard.add_hotkey('play/pause media', PLAYER.toggle_pause),
            keyboard.add_hotkey('next track', QUEUE.next),
            keyboard.add_hotkey('previous track', QUEUE.prev),
        ]
예제 #7
0
 def test_remove_hotkey_internal_multistep_start(self):
     remove = keyboard.add_hotkey('shift+a, b', trigger, suppress=True)
     self.assertTrue(all(keyboard._listener.blocking_hotkeys.values()))
     self.assertTrue(all(keyboard._listener.filtered_modifiers.values()))
     self.assertNotEqual(keyboard._hotkeys, {})
     remove()
     self.assertTrue(not any(keyboard._listener.filtered_modifiers.values()))
     self.assertTrue(not any(keyboard._listener.blocking_hotkeys.values()))
     self.assertEqual(keyboard._hotkeys, {})
예제 #8
0
    def triggers(self, combination, keys):
        self.triggered = False

        def on_triggered():
            self.triggered = True

        keyboard.add_hotkey(combination, on_triggered)
        for group in keys:
            for key in group:
                self.assertFalse(self.triggered)
                self.press(key)
            for key in reversed(group):
                self.release(key)

        keyboard.remove_hotkey(combination)

        self.wait_for_events_queue()

        return self.triggered
예제 #9
0
def tray():
    global icon, thread
    icon = None
    thread = None

    name = 'ED - Autopilot'
    icon = Icon(name=name, title=name)
    logo = Image.open(resource_path('src/logo.png'))
    icon.icon = logo

    icon.menu = Menu(
        MenuItem(
            'Scan Off',
            set_state(0),
            checked=get_state(0),
            radio=True
        ),
        MenuItem(
            'Scan on Primary Fire',
            set_state(1),
            checked=get_state(1),
            radio=True
        ),
        MenuItem(
            'Scan on Secondary Fire',
            set_state(2),
            checked=get_state(2),
            radio=True
        ),
        MenuItem('Exit', lambda : exit_action())
    )

    keyboard.add_hotkey('home', start_action)
    keyboard.add_hotkey('end', stop_action)

    icon.run(setup)
예제 #10
0
    def test_remove_hotkey(self):
        keyboard.press("a")
        keyboard.add_hotkey("a", self.fail)
        keyboard.clear_all_hotkeys()
        keyboard.press("a")
        keyboard.add_hotkey("a", self.fail)
        keyboard.clear_all_hotkeys()
        keyboard.press("a")

        keyboard.clear_all_hotkeys()

        keyboard.add_hotkey("a", self.fail)
        with self.assertRaises(ValueError):
            keyboard.remove_hotkey("b")
        keyboard.remove_hotkey("a")
예제 #11
0
 def test_add_hotkey_multi_step_last_timeout(self):
     keyboard.add_hotkey('a, b', trigger, timeout=0.01, suppress=True)
     self.do(du_a, [])
     time.sleep(0.05)
     self.do(du_b, du_a+du_b)
예제 #12
0
    def process(self, err_queue):
        try:
            file_path = self.file_out_path.get().strip()

            #Проверки
            if file_path == "":
                tm.showerror("Ошибка", "Выберите файл")
                self.back_to_chill()
                return
            if not os.path.splitext(file_path)[1] in self.extensions:
                question = tm.askyesno(
                    "Предупреждение",
                    "Неправильный тип файла. Хотите создать новый .docx файл с тем же именем?"
                )
                if not question:
                    self.back_to_chill()
                    return
                else:
                    self.file_out_path.set(self.file_out_path.get() + ".docx")
                    file_path += ".docx"
            if not os.path.exists(file_path):
                question = tm.askyesno(
                    "Предупреждение",
                    "Файла не существует. Вы хотите создать его?")
                if not question:
                    self.back_to_chill()
                    return
            #============================================

            #Открываем файл
            self.document = docx.Document()

            def really_processing():
                try:
                    screen_path = os.path.join(self.cur_dir, "__TEMP__.png")
                    screen_path = os.path.abspath(screen_path)
                    img = ""
                    #Делаем скриншот
                    if self.chosen_opt.get() == CHSE_OWN:
                        ch1x = int(self.btn_choose1_X.get())
                        ch1y = int(self.btn_choose1_Y.get())
                        ch2x = int(self.btn_choose2_X.get())
                        ch2y = int(self.btn_choose2_Y.get())
                        capture_space = {
                            "top": ch1x,
                            "left": ch1y,
                            "width": ch2x - ch1x,
                            "height": ch2y - ch1y
                        }
                        with mss.mss() as print_screen:
                            img = print_screen.grab(capture_space)
                        mss.tools.to_png(img.rgb, img.size, output=screen_path)
                    elif self.chosen_opt.get() == CHSE_FS:
                        with mss.mss() as print_screen:
                            img = print_screen.shot(output=screen_path)

                    #Работа с docx и doc файлами
                    section = self.document.sections[0]
                    section.left_margin = docx.shared.Cm(1)
                    section.right_margin = docx.shared.Cm(1)
                    section.top_margin = docx.shared.Cm(1)
                    section.bottom_margin = docx.shared.Cm(1)
                    self.document.add_picture(screen_path,
                                              width=section.page_width -
                                              section.left_margin -
                                              section.right_margin)

                    self.document.save(file_path)
                    os.remove(screen_path)
                except Exception as err:
                    err_queue.put((err.__class__, traceback.format_exc()))
                    self.root.event_generate("<<On error>>")

            keyboard.add_hotkey(self.key_name.get(), really_processing)
        except Exception as err:
            err_queue.put((err.__class__, traceback.format_exc()))
            self.root.event_generate("<<On error>>")
예제 #13
0
def uninstall(package_name: str, verbose: bool, debug: bool, no_color: bool,
              logfile: str, yes: bool, silent: bool, python: bool,
              no_cache: bool):

    metadata = generate_metadata(None, silent, verbose, debug, no_color, yes,
                                 logfile, None, None)

    super_cache = check_supercache_valid()

    if no_cache:
        super_cache = False

    if logfile:
        logfile = logfile.replace('.txt', '.log')
        createConfig(logfile, logging.INFO, 'Install')

    if python:

        flags = []

        package_names = package_name.split(',')

        for name in package_names:
            handle_python_package(name, 'uninstall', metadata)

        sys.exit()

    status = 'Initializing'
    setup_name = ''
    keyboard.add_hotkey('ctrl+c',
                        lambda: handle_exit(status, setup_name, metadata))

    packages = package_name.split(',')

    if super_cache:
        res, time = handle_cached_request()

    else:
        status = 'Networking'
        write_verbose('Sending GET Request To /rapidquery/packages', metadata)
        write_debug('Sending GET Request To /rapidquery/packages', metadata)
        log_info('Sending GET Request To /rapidquery/packages', logfile)
        res, time = send_req_all()
        res = json.loads(res)
    correct_names = get_correct_package_names(res)
    corrected_package_names = []

    for name in packages:
        if name in correct_names:
            corrected_package_names.append(name)
        else:
            corrections = difflib.get_close_matches(name, correct_names)
            if corrections:
                if silent:
                    click.echo(
                        click.style(
                            'Incorrect / Invalid Package Name Entered. Aborting Uninstallation.',
                            fg='red'))
                    log_info(
                        'Incorrect / Invalid Package Name Entered. Aborting Uninstallation',
                        logfile)
                    handle_exit(status, setup_name, metadata)

                if yes:
                    write(f'Autocorrecting To {corrections[0]}', 'green',
                          metadata)
                    log_info(f'Autocorrecting To {corrections[0]}', logfile)
                    write(f'Successfully Autocorrected To {corrections[0]}',
                          'green', metadata)
                    log_info(f'Successfully Autocorrected To {corrections[0]}',
                             logfile)
                    corrected_package_names.append(corrections[0])

                else:
                    write(f'Autocorrecting To {corrections[0]}',
                          'bright_magenta', metadata)
                    write_verbose(f'Autocorrecting To {corrections[0]}',
                                  metadata)
                    write_debug(f'Autocorrecting To {corrections[0]}',
                                metadata)
                    log_info(f'Autocorrecting To {corrections[0]}', logfile)
                    if click.prompt(
                            'Would You Like To Continue? [y/n]') == 'y':
                        package_name = corrections[0]
                        corrected_package_names.append(package_name)
                    else:
                        sys.exit()
            else:
                write(f'Could Not Find Any Packages Which Match {name}',
                      'bright_magenta', metadata)
                write_debug(f'Could Not Find Any Packages Which Match {name}',
                            metadata)
                write_verbose(
                    f'Could Not Find Any Packages Which Match {name}',
                    metadata)
                log_info(f'Could Not Find Any Packages Which Match {name}',
                         logfile)

    write_debug(install_debug_headers, metadata)
    for header in install_debug_headers:
        log_info(header, logfile)

    index = 0

    for package in corrected_package_names:
        pkg = res[package]
        packet = Packet(package, pkg['package-name'], pkg['win64'],
                        pkg['darwin'], pkg['debian'], pkg['win64-type'],
                        pkg['darwin-type'], pkg['debian-type'],
                        pkg['custom-location'], pkg['install-switches'],
                        pkg['uninstall-switches'], None)
        proc = None
        keyboard.add_hotkey('ctrl+c', lambda: kill_proc(proc, metadata))

        kill_running_proc(packet.json_name, metadata)

        if super_cache:
            write(
                f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 6)}s',
                'bright_yellow', metadata)
            write_debug(
                f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 9)}s',
                metadata)
            log_info(
                f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 6)}s',
                metadata)
        else:
            write(
                f'Rapidquery Successfully Received {packet.json_name}.json in {round(time, 6)}s',
                'bright_green', metadata)
            log_info(
                f'Rapidquery Successfully Received {packet.json_name}.json in {round(time, 6)}s',
                logfile)

        # Getting UninstallString or QuietUninstallString From The Registry Search Algorithm
        write_verbose("Fetching uninstall key from the registry...", metadata)
        log_info("Fetching uninstall key from the registry...", logfile)

        start = timer()
        key = get_uninstall_key(packet.json_name)
        end = timer()

        # If The UninstallString Or QuietUninstallString Doesn't Exist
        # if not key:
        #     write_verbose('No registry keys found', verbose, no_color, silent)
        #     log_info('No registry keys found', logfile)
        #     if "uninstall-command" in pkg:
        #         if pkg['uninstall-command'] == '':
        #             write(
        #                 f'Could Not Find Any Existing Installations Of {packet.json_name}', 'yellow', no_color, silent)
        #             log_error(
        #                 f'Could Not Find Any Existing Installations Of {packet.json_name}', logfile)
        #             closeLog(logfile, 'Uninstall')
        #             index += 1
        #             continue
        #         else:
        #             write_verbose("Executing the uninstall command",
        #                           verbose, no_color, silent)
        #             log_info("Executing the uninstall command", logfile)

        #             try:
        #                 proc = Popen(shlex.split(
        #                     pkg['uninstall-command']), stdout=PIPE, stdin=PIPE, stderr=PIPE)
        #                 proc.wait()
        #                 if proc.returncode != 0:
        #                     write(f'Installation Failed, Make Sure You Accept All Prompts Asking For Admin permission', 'red', no_color, silent)
        #                     handle_exit(status, 'None', no_color, silent)
        #             except FileNotFoundError:

        #                 proc = Popen(shlex.split(
        #                     pkg['uninstall-command']), stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
        #                 proc.wait()
        #                 if proc.returncode != 0:
        #                     write(f'Installation Failed, Make Sure You Accept All Prompts Asking For Admin permission', 'red', no_color, silent)
        #                     handle_exit(status, 'None', no_color, silent)

        #             write(
        #                 f"Successfully Uninstalled {package_name}", "bright_magenta", no_color, silent)

        #             index += 1
        #             write_debug(
        #                 f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion', debug, no_color, silent)
        #             log_info(
        #                 f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion', logfile)
        #             closeLog(logfile, 'Uninstall')
        #             continue
        #     else:
        # write(
        #     f'Could Not Find Any Existing Installations Of {package_name}', 'yellow', no_color, silent)
        # closeLog(logfile, 'Uninstall')
        # index += 1
        # continue

        if not key:
            write(
                f'Could Not Find Any Existing Installations Of {packet.display_name}',
                'yellow', metadata)
            closeLog(logfile, 'Uninstall')
            index += 1
            continue

        write_verbose("Uninstall key found.", metadata)
        log_info("Uninstall key found.", logfile)

        write(
            f'Successfully Retrieved Uninstall Key In {round(end - start, 4)}s',
            'cyan', metadata)
        log_info(
            f'Successfully Retrieved Uninstall Key In {round(end - start, 4)}s',
            logfile)

        command = ''

        # Key Can Be A List Or A Dictionary Based On Results

        if isinstance(key, list):
            if key:
                key = key[0]

        write(f'Uninstalling {packet.display_name}', 'green', metadata)

        # If QuietUninstallString Exists (Preferable)
        if 'QuietUninstallString' in key:
            command = key['QuietUninstallString']
            command = command.replace('/I', '/X')
            command = command.replace('/quiet', '/passive')

            additional_switches = None
            if packet.uninstall_switches:
                if packet.uninstall_switches != []:
                    write_verbose("Adding additional uninstall switches",
                                  metadata)
                    log_info("Adding additional uninstall switches", logfile)
                    additional_switches = packet.uninstall_switches

            if additional_switches:
                for switch in additional_switches:
                    command += ' ' + switch

            write_verbose("Executing the quiet uninstall command", metadata)
            log_info("Executing the quiet uninstall command", logfile)

            run_cmd(command, metadata, 'uninstallation')

            write(f"Successfully Uninstalled {packet.display_name}",
                  "bright_magenta", metadata)

            write_verbose("Uninstallation completed.", metadata)
            log_info("Uninstallation completed.", logfile)

            index += 1
            write_debug(
                f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion',
                metadata)
            log_info(
                f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion',
                logfile)
            closeLog(logfile, 'Uninstall')

        # If Only UninstallString Exists (Not Preferable)
        if 'UninstallString' in key and 'QuietUninstallString' not in key:
            command = key['UninstallString']
            command = command.replace('/I', '/X')
            command = command.replace('/quiet', '/passive')
            command = f'"{command}"'
            for switch in packet.uninstall_switches:
                command += f' {switch}'

            # Run The UninstallString
            write_verbose("Executing the Uninstall Command", metadata)
            log_info("Executing the Uninstall Command", logfile)

            run_cmd(command, metadata, 'uninstallation')

            write(f'Successfully Uninstalled {packet.display_name}',
                  'bright_magenta', metadata)
            write_verbose("Uninstallation completed.", metadata)
            log_info("Uninstallation completed.", logfile)
            index += 1
            write_debug(
                f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion',
                metadata)
            log_info(
                f'Terminated debugger at {strftime("%H:%M:%S")} on uninstall::completion',
                logfile)
            closeLog(logfile, 'Uninstall')
예제 #14
0
import keyboard
from PIL import ImageGrab


def screenshot():
    # 2021년 1월 27일 10시 30분 30초 > _20210127_103030
    curr_time = time.strftime("_%Y%d_%H%M%S")
    img = ImageGrab.grab()
    img.save("image{}.png".format(curr_time))  #ex) image_20210127_103030.png


keyboard.add_hotkey("F9", screenshot)  #사용자가 F9 키를 누르면 스크린샷 저장

keyboard.wait("esc")  #사용자가 esc를 누를 때까지 프로그램 수행
예제 #15
0
 def test_add_hotkey_multi_step_suppress_regression_1(self):
     keyboard.add_hotkey('a, b', trigger, suppress=True)
     self.do(d_c+d_a+u_c+u_a+du_c, d_c+d_a+u_c+u_a+du_c)
예제 #16
0
 def test_add_hotkey_multistep_suppress_fail(self):
     keyboard.add_hotkey('a, b', trigger, suppress=True)
     self.do(du_a+du_c, du_a+du_c)
예제 #17
0
 def test_add_hotkey_single_step_suppress_regression_1(self):
     keyboard.add_hotkey('a', trigger, suppress=True)
     self.do(d_c+d_a+u_c+u_a, d_c+d_a+u_c+u_a)
예제 #18
0
                datetime.now()
            ])
            _key_press_rec_iter += 1
            # print(_key_press_rec_iter)
            # print("done")


# def do_this(temp1,temp2):
#     print(temp1)
#     print(temp2)
#     # time.sleep(1)

# keyboard.add_hotkey(('ctrl+shift+p'),do_this,args=('This one is working !','But How ?'),timeout=0.5,trigger_on_release = False)
keyboard.add_hotkey('ctrl+shift+t',
                    add_key_press_rec,
                    args=(time.time(), recording_start_time),
                    timeout=0.5,
                    trigger_on_release=False)


class BodyGameRuntime(object):
    def __init__(self):
        global _key_press_rec_iter, _key_press_rec_label_uni, _key_press_rec_label_bil, _key_press_rec, recording_start_time
        pygame.init()

        # Set the width and height of the screen [width, height]
        self._infoObject = pygame.display.Info()
        self._screen = pygame.display.set_mode(
            (self._infoObject.current_w >> 1, self._infoObject.current_h >> 1),
            HWSURFACE | DOUBLEBUF | OPENGL, 32)
예제 #19
0
"""

author: @endormi

Keyboard hotkey

"""

import keyboard

keyboard.add_hotkey('ctrl + z', print, args=('this is', 'a hotkey'))
keyboard.wait('esc')
예제 #20
0
	left_click()
	
	global pos_select_left, pos_select_right
	pos_select_right = cursor_position.get_cursor_position()

	ctypes.windll.user32.mouse_event(0x0001+0x8000, pos_select_left[0], pos_select_left[1], 0, 0)
	#Wait or fail.
	time.sleep(0.1)
	ctypes.windll.user32.mouse_event(0x0002, 0, 0, 0, 0)
	ctypes.windll.user32.mouse_event(0x0001+0x8000, pos_select_right[0], pos_select_right[1], 0, 0)
	ctypes.windll.user32.mouse_event(0x0004, 0, 0, 0, 0)


#click control:
##single click:
keyboard.add_hotkey(left_click_key, lambda: left_click())
keyboard.add_hotkey(right_click_key, lambda: right_click())

#double click:
keyboard.add_hotkey(double_left_click_key, lambda: double_left_click())

#Text select control:
keyboard.add_hotkey(select_text_begin_key, lambda: select_text_begin())
keyboard.add_hotkey(select_text_end_key, lambda: select_text_end())

#Cursor movement control:
##fast speed:
keyboard.add_hotkey(move_left_fast_key, lambda: move_left(16))
keyboard.add_hotkey(move_right_fast_key, lambda: move_right(16))
keyboard.add_hotkey(move_up_fast_key, lambda: move_up(16))
keyboard.add_hotkey(move_down_fast_key, lambda: move_down(16))
예제 #21
0
        for y in range(ylhs, yrhs):
            coord = map_mdt_coord(x, y)
            pixels[x-xlhs, y-ylhs] = mandelbrot(coord[0], coord[1])

    img.show()

# show_mandelbrot(0, image_width, 0, image_height)

zoom_scale = 1.0
def zoom_in():
    global image_width, image_height, zoom_scale

    zoom_scale = zoom_scale * 2.0

    image_width = int(WIDTH * zoom_scale)
    image_height = image_width // 2

    xlhs = (image_width - WIDTH) // 2
    xrhs = xlhs + WIDTH

    ylhs = xlhs // 2
    yrhs = xrhs // 2

    print("{} {} {} {}".format(xlhs, xrhs, ylhs, yrhs))
    show_mandelbrot(xlhs, xrhs, ylhs, yrhs)

def move_left():
    pass

keyboard.add_hotkey('s', zoom_in)
keyboard.wait()
예제 #22
0
import keyboard

print("Нажмите желаемую комбинацию клавиш")
shortcut = keyboard.read_hotkey()
print("Вы выбрали:", shortcut)


def on_triggered():
    print("Triggered!")


keyboard.add_hotkey(shortcut, on_triggered, suppress=True)
# keyboard.add_hotkey('ctrl+shift', on_triggered)
# suppress = True подавляет другие возможные пересечения.

print("Нажмите ESC для остановки")
keyboard.wait("esc")
예제 #23
0
파일: minigame.py 프로젝트: amloewi/breaker
    # os.system("""osascript -e 'do shell script "{}" with administrator privileges'""".format(path))

    if False:
        from tkinter import simpledialog, Tk  # One of the ones where you can't tk.f
        root = Tk()
        root.withdraw()
        pwd = simpledialog.askstring("Breaker",
                                     "Breaker needs your password!",
                                     show='*',
                                     parent=root)
        root.destroy()

        script = """from minigame import minigame; import keyboard; keyboard.add_hotkey("windows+shift+y", minigame)"""
        os.system(""" echo {} | sudo -S python3 -c '{}'""".format(pwd, script))
    else:
        keyboard.add_hotkey('windows+shift+y',
                            set_flag)  #lambda:print('hello!')) #set_flag)

    # print(pwd)
    # but what is this RUNNING?
    # keyboard.add_hotkey('windows+shift+y', set_flag) #lambda:print('hello!')) #set_flag)

    # from tkinter import *
    #
    # def getpwd():
    #     password = ''
    #     root = Tk()
    #     pwdbox = Entry(root, show = '*')
    #     def onpwdentry(evt):
    #          password = pwdbox.get()
    #          root.destroy()
    #     def onokclick():
예제 #24
0
 def test_add_hotkey_multi_step_suffix_timeout(self):
     keyboard.add_hotkey('a, b, a', trigger, timeout=0.01, suppress=True)
     self.do(du_a+du_b, [])
     time.sleep(0.05)
     self.do(du_a, du_a+du_b)
     self.do(du_b+du_a, triggered_event)
예제 #25
0
    if success:
        uploaded_image = im.upload_image(filename, title='Thowaway Title')
        link = uploaded_image.link
        pyperclip.copy(link)

        os.remove(filename)

        with open('link_log.txt', 'a') as f:
            f.write(filename + ' --> ' + link + '\n')

    else:
        with open('link_log.txt', 'a') as f:
            f.write(filename + ' --> failure\n')


if __name__ == '__main__':

    if sys.executable.endswith('pythonw.exe'):
        sys.stdout = open(os.devnull, 'w')
        sys.stderr = open(
            os.path.join(os.getenv('TEMP'),
                         'stderr-' + os.path.basename(sys.argv[0])), 'w')

    for i in range(1, desktop.screenCount() + 1):
        with open('key_log.txt', 'a') as f:
            f.write('it worked for \'alt+shift+{}\'\n'.format(i))
        keyboard.add_hotkey('alt+shift+{}'.format(i), save_screen, args=[i])

    keyboard.wait('alt+shift+q')
예제 #26
0
        if wait_time > 0:
            time.sleep(wait_time)


# info
start = time.time()
pag.press("L")
press_load_time = time.time() - start
print("oad press time:", press_load_time)
print("Max typing speed: cca", round(60 / press_load_time))
# init
try:
    rawconfig = rf(CONFIG_FILE)
except:
    error("Missing config.txt!")
try:
    config = parse_config(rawconfig)
except:
    error("Invalid config.txt!")
try:
    text = rf(config["textfile"])
except:
    error("Could not find text file!")
if "mistakes" in config:
    text = apply_random(text)
kb.add_hotkey(config['start'], start_typing)
# destruct
input("Press enter to end program...")
kb.unhook_all_hotkeys()
sys.exit()
예제 #27
0
 def test_add_hotkey_multistep_suppress_incomplete(self):
     keyboard.add_hotkey('a, b', trigger, suppress=True)
     self.do(du_a+du_b, triggered_event)
예제 #28
0
        ctypes.windll.user32.SetCursorPos(int(offsetX + predictedPoint[0]),
                                          int(offsetY + predictedPoint[1]))
        time.sleep(0.005)
        leftClick()
        ctypes.windll.user32.SetCursorPos(int(last[0]), int(last[1]))

    print("nabbin' a loot")
    #cv.imshow("frame", frame)
    #cv.waitKey(10)


print(
    "\nPath of Automation:\n" +
    "     _         _              _                _      ____ _ _      _             \n"
    +
    "    / \  _   _| |_ ___       | |    ___   ___ | |_   / ___| (_) ___| | _____ _ __ \n"
    +
    "   / _ \| | | | __/ _ \ _____| |   / _ \ / _ \| __| | |   | | |/ __| |/ / _ \ '__|\n"
    +
    "  / ___ \ |_| | || (_) |_____| |__| (_) | (_) | |_  | |___| | | (__|   <  __/ |   \n"
    +
    " /_/   \_\__,_|\__\___/      |_____\___/ \___/ \__|  \____|_|_|\___|_|\_\___|_|   \n\n"
    + "by LazyGuyWithRSI\n\n")

init()

print("Ready to grab some loot!\n")

keyboard.add_hotkey(HOTKEY, grabLoot)
while True:
    time.sleep(0.03)  #keep it alive
예제 #29
0
 def test_add_hotkey_multistep_suppress_repeated_prefix(self):
     keyboard.add_hotkey('a, a, c', trigger, suppress=True, trigger_on_release=True)
     self.do(du_a+du_a+du_c, triggered_event)
예제 #30
0
from wx import App
from main_frame import MainFrame
import keyboard

# Options
hash_lang = 'RU'  # Available choices: 'EN', 'RU'

# App initialization
app = App()
main_frame = MainFrame(hash_lang)

# Listener
keyboard.add_hotkey('F1', lambda: main_frame.prev_item())
keyboard.add_hotkey('F2', lambda: main_frame.next_item())
keyboard.add_hotkey('F3', lambda: main_frame.search_first_no_hash_item())
keyboard.add_hotkey('F4', lambda: main_frame.search_last_no_hash_item())

keyboard.add_hotkey('F5', lambda: keyboard.write(main_frame.item_name()))
keyboard.add_hotkey('F6', lambda: main_frame.set_hash_to_item())
keyboard.add_hotkey('F7', lambda: main_frame.set_no_hash_to_item())
keyboard.add_hotkey('F8', lambda: main_frame.save())

app.MainLoop()
예제 #31
0
import keyboard
import os

ans = ""

def exit_():
	f = open("log.txt","w") 
	f.write(ans) 
	f.close()
	
	os._exit(1)

while True:
    try: 
    	keyboard.add_hotkey('shift+esc', exit_)
        if keyboard.read_key():
        	key = keyboard.read_key()
        	ans += key
        else:
            pass
    except:
        break
예제 #32
0
from googletrans import Translator
import keyboard
import pyperclip


def ceviri():
    trans = Translator()

    yazi = pyperclip.paste()

    t = trans.translate(yazi, dest='tr')

    i = trans.translate(yazi, dest='en')
    print(f'{i.text} {t.text}')
    if t.src == 'en':
        pyperclip.copy(t.text)

    if i.src == 'tr':
        pyperclip.copy(i.text)


keyboard.add_hotkey('tab', lambda: ceviri())

keyboard.wait()
예제 #33
0
import time
import keyboard
from PIL import ImageGrab


def screenshot():
    curr_time = time.strftime("_%Y%m%d_%H%M%S")
    img = ImageGrab.grab()
    img.save("image{}.png".format(curr_time))


keyboard.add_hotkey("F9", screenshot)  # F9 누르면 스크린샷 저장

keyboard.wait("esc")  # 사용자가 esc를 누를 때까지 수행

def stopArm():
    ARM_DATA_JSON["LAC"] = 0
    ARM_DATA_JSON["UAC"] = 0
    ARM_DATA_JSON["TRT"] = 0
    ARM_DATA_JSON["GRPR"] = 0
    ARM_DATA_JSON["GRPX"] = 0
    ARM_DATA_JSON["GRPY"] = 0
    sendDataToArm(ARM_DATA_JSON)


if __name__ == "__main__":
    ARM_SERIAL.open()

    keyboard.add_hotkey("q", lambda: setFieldAndSend("LAC", 150))
    keyboard.add_hotkey("a", lambda: setFieldAndSend("LAC", 0))
    keyboard.add_hotkey("z", lambda: setFieldAndSend("LAC", -150))

    keyboard.add_hotkey("w", lambda: setFieldAndSend("UAC", 150))
    keyboard.add_hotkey("s", lambda: setFieldAndSend("UAC", 0))
    keyboard.add_hotkey("x", lambda: setFieldAndSend("UAC", -150))

    keyboard.add_hotkey("l", lambda: setFieldAndSend("TRT", 150))
    keyboard.add_hotkey("k", lambda: setFieldAndSend("TRT", 0))
    keyboard.add_hotkey("j", lambda: setFieldAndSend("TRT", -150))

    keyboard.add_hotkey("p", lambda: setFieldAndSend("GRPR", 150))
    keyboard.add_hotkey("o", lambda: setFieldAndSend("GRPR", 0))
    keyboard.add_hotkey("i", lambda: setFieldAndSend("GRPR", -150))
예제 #35
0
파일: Gui.py 프로젝트: joventuraz/Eule.py
    def add_profile(self):
        self.listener.stop()
        text, ok = QInputDialog.getText(self, 'Add new Profile',
                                        'Profile Name:', QLineEdit.Normal, "")
        if ok and text and text not in [
                box.name for box in self.profile_boxes
        ]:
            profile = {
                'name': text,
                "hotkeys": [None, None, None, None, 'LeftClick', 'RightClick'],
                "delays": [0, 0, 0, 0, 0, 0],
            }
            self.settings.skill_macro['profiles'][text] = profile
            self.profile_amt += 1
            skills = QGroupBox(self)
            skills.setTitle(profile['name'])
            skills_layout = QGridLayout(skills)
            self.layout.addWidget(skills, self.profile_amt, 0)
            self.profile_boxes.append(skills)

            label = QLabel(skills)
            label.setText('Key')
            skills_layout.addWidget(label, 0, 0)

            label = QLabel(skills)
            label.setText('Delay (in ms)')
            skills_layout.addWidget(label, 1, 0)

            skills.name = profile['name']
            skills.key_buttons = []
            skills.spinboxes = []

            for i, (hotkey, delay) in enumerate(
                    zip(
                        profile['hotkeys'],
                        profile['delays'],
                    )):
                button = QPushButton(skills)
                button.setText(hotkey)
                button.key_code = hotkey
                button.clicked.connect(self.set_key)
                skills_layout.addWidget(button, 0, i + 1)
                if i >= 4:
                    button.setDisabled(True)
                skills.key_buttons.append(button)

                spinbox = QSpinBox(skills)
                spinbox.setMinimum(0)
                spinbox.setMaximum(100000)
                spinbox.setSingleStep(10)
                spinbox.setValue(delay)
                skills_layout.addWidget(spinbox, 1, i + 1)
                skills.spinboxes.append(spinbox)
                if i == 4:
                    spinbox.setDisabled(True)

            radiobutton = QRadioButton(self.radiobuttons)
            radiobutton.setText(profile['name'])
            radiobutton.setChecked(
                profile['name'] == self.settings.skill_macro['active'])
            self.radiobuttons_layout.addWidget(radiobutton)
            self.radiobuttons_x.append(radiobutton)

            button = QPushButton(skills)
            button.setText('Delete')
            button.clicked.connect(lambda state: self.delete_profile(text))
            skills_layout.addWidget(button, 0, 7)

        elif text in [box.name for box in self.profile_boxes]:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Warning)
            msg.setText("This Profile Name already exists!")
            msg.setInformativeText('Pick a different Profile Name!')
            msg.setWindowTitle("Profile Name exists!")
            msg.exec_()

        if not self.listener.paused:
            self.listener.start()
        elif self.settings.hotkeys['pause']:
            keyboard.add_hotkey(self.settings.hotkeys['pause'],
                                self.listener.pause)
예제 #36
0
import keyboard

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

keyboard.press_and_release('shift+s, space')

# 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)
예제 #37
0
 def test_add_hotkey_multi_step_first_timeout(self):
     keyboard.add_hotkey('a, b', trigger, timeout=0.01, suppress=True)
     time.sleep(0.03)
     self.do(du_a+du_b, triggered_event)
예제 #38
0
import keyboard
import time
from PIL import ImageGrab


def screenshot():
    curr_time = time.strftime("_%Y%m%d_%H%M%S")
    img = ImageGrab.grab()
    img.save("image{}.png".format(curr_time))


keyboard.add_hotkey("F9", screenshot)

keyboard.wait("esc")
예제 #39
0
 def test_add_hotkey_multi_step_success_timeout(self):
     keyboard.add_hotkey('a, b', trigger, timeout=0.05, suppress=True)
     self.do(du_a, [])
     time.sleep(0.01)
     self.do(du_b, triggered_event)
예제 #40
0
 def run(self):
     keyboard.add_hotkey(self.key_combo, self.val)
     while self.status is True:
         if(self.key is True):
             print("Hello!")
             self.key = False
예제 #41
0
 def test_add_hotkey_multi_step_allow(self):
     keyboard.add_hotkey('a, b', lambda: trigger() or True, suppress=True)
     self.do(du_a+du_b, triggered_event+du_a+du_b)
예제 #42
0
def DisableHotkeys(hotkeys=["alt + f4", "alt + tab"]):
    for i in range(len(hotkeys)):
        keyboard.add_hotkey(hotkeys[i], lambda: None, suppress=True)
예제 #43
0
 def test_add_hotkey_single_step_nosuppress_with_modifiers_out_of_order(self):
     queue = keyboard._queue.Queue()
     keyboard.add_hotkey('ctrl+shift+a', lambda: queue.put(True), suppress=False)
     self.do(d_shift+d_ctrl+d_a)
     self.assertTrue(queue.get(timeout=0.5))
예제 #44
0
def EnableHotkeys(hotkeys=["alt + f4", "alt + tab"]):
    for i in range(len(hotkeys)):
        keyboard.add_hotkey(hotkeys[i], lambda: None, suppress=False)
    #keyboard.add_hotkey("ctrl + alt + del", lambda: None, suppress =True)
예제 #45
0
 def test_add_hotkey_multistep_suppress_incomplete(self):
     keyboard.add_hotkey('a, b', trigger, suppress=True)
     self.do(du_a, [])
     self.assertEqual(keyboard._listener.blocking_hotkeys[(1,)], [])
     self.assertEqual(len(keyboard._listener.blocking_hotkeys[(2,)]), 1)
예제 #46
0
파일: collect.py 프로젝트: loupzeur/AI-Game
 def loadAI(self,path):
     self.run_AI = True
     self.model = load_model(path)
     keyboard.add_hotkey('ctrl + space',self._switchAICtl)
예제 #47
0
 def test_add_hotkey_multistep_suppress_modifier(self):
     keyboard.add_hotkey('shift+a, b', trigger, suppress=True)
     self.do(d_shift+du_a+u_shift+du_b, triggered_event)
예제 #48
0
파일: win.py 프로젝트: danbradham/hotline
 def initialize(self, app):
     import keyboard
     keyboard.add_hotkey('ctrl + space', app.show)
예제 #49
0
 def test_add_hotkey_multistep_suppress_three_steps(self):
     keyboard.add_hotkey('a, b, c', trigger, suppress=True)
     self.do(du_a+du_b+du_c, triggered_event)
예제 #50
0
def chat_main(client):
    """ (Clubhouse) -> NoneType

    Main function for chat
    """
    max_limit = 200
    channel_speaker_permission = False
    _wait_func = None
    _ping_func = None

    def _request_speaker_permission(client, channel_name, user_id):
        """ (str) -> bool

        Raise hands for permissions
        """
        if not channel_speaker_permission:
            client.audience_reply(channel_name, True, False)
            _wait_func = _wait_speaker_permission(client, channel_name,
                                                  user_id)
            print(
                "[/] You've raised your hand. Wait for the moderator to give you the permission."
            )

    @set_interval(30)
    def _ping_keep_alive(client, channel_name):
        """ (str) -> bool

        Continue to ping alive every 30 seconds.
        """
        client.active_ping(channel_name)
        return True

    @set_interval(10)
    def _wait_speaker_permission(client, channel_name, user_id):
        """ (str) -> bool

        Function that runs when you've requested for a voice permission.
        """
        # Get some random users from the channel.
        _channel_info = client.get_channel(channel_name)
        if _channel_info['success']:
            for _user in _channel_info['users']:
                if _user['user_id'] != user_id:
                    user_id = _user['user_id']
                    break
            # Check if the moderator allowed your request.
            res_inv = client.accept_speaker_invite(channel_name, user_id)
            if res_inv['success']:
                print("[-] Now you have a speaker permission.")
                print(
                    "    Please re-join this channel to activate a permission."
                )
                return False
        return True

    while True:
        # Choose which channel to enter.
        # Join the talk on success.
        user_id = client.HEADERS.get("CH-UserID")
        print_channel_list(client, max_limit)
        channel_name = input("[.] Enter channel_name: ")
        channel_info = client.join_channel(channel_name)
        if not channel_info['success']:
            # Check if this channel_name was taken from the link
            channel_info = client.join_channel(channel_name, "link", "e30=")
            if not channel_info['success']:
                print(
                    f"[-] Error while joining the channel ({channel_info['error_message']})"
                )
                continue

        # List currently available users (TOP 20 only.)
        # Also, check for the current user's speaker permission.
        channel_speaker_permission = False
        console = Console()
        table = Table(show_header=True, header_style="bold magenta")
        table.add_column("user_id", style="cyan", justify="right")
        table.add_column("username")
        table.add_column("name")
        table.add_column("is_speaker")
        table.add_column("is_moderator")
        users = channel_info['users']
        i = 0
        for user in users:
            i += 1
            if i > max_limit:
                break
            table.add_row(
                str(user['user_id']),
                str(user['name']),
                str(user['username']),
                str(user['is_speaker']),
                str(user['is_moderator']),
            )
            # Check if the user is the speaker
            if user['user_id'] == int(user_id):
                channel_speaker_permission = bool(user['is_speaker'])
        console.print(table)

        # Check for the voice level.
        if RTC:
            token = channel_info['token']
            RTC.joinChannel(token, channel_name, "", int(user_id))
        else:
            print("[!] Agora SDK is not installed.")
            print("    You may not speak or listen to the conversation.")

        # Activate pinging
        client.active_ping(channel_name)
        _ping_func = _ping_keep_alive(client, channel_name)
        _wait_func = None

        # Add raise_hands key bindings for speaker permission
        # Sorry for the bad quality
        if not channel_speaker_permission:

            if sys.platform == "darwin":  # OSX
                _hotkey = "9"
            elif sys.platform == "win32":  # Windows
                _hotkey = "ctrl+shift+h"

            print(
                f"[*] Press [{_hotkey}] to raise your hands for the speaker permission."
            )
            keyboard.add_hotkey(_hotkey,
                                _request_speaker_permission,
                                args=(client, channel_name, user_id))

        input("[*] Press [Enter] to quit conversation.\n")
        keyboard.unhook_all()

        # Safely leave the channel upon quitting the channel.
        if _ping_func:
            _ping_func.set()
        if _wait_func:
            _wait_func.set()
        if RTC:
            RTC.leaveChannel()
        client.leave_channel(channel_name)
예제 #51
0
 def test_add_hotkey_multistep_suppress_repeated_key(self):
     keyboard.add_hotkey('a, b', trigger, suppress=True)
     self.do(du_a+du_a+du_b, du_a+triggered_event)
     self.assertEqual(keyboard._listener.blocking_hotkeys[(2,)], [])
     self.assertEqual(len(keyboard._listener.blocking_hotkeys[(1,)]), 1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# SOURCE: https://github.com/boppreh/keyboard/blob/master/examples/customizable_hotkey.py


# pip install keyboard
import keyboard

print('Press and release your desired shortcut: ')

shortcut = keyboard.read_shortcut()
print('Shortcut selected:', shortcut)


def on_triggered():
    print("Triggered!")

keyboard.add_hotkey(shortcut, on_triggered)

print("Press ESC to stop.")
keyboard.wait('esc')
예제 #53
0
 def test_add_hotkey_multi_step_suppress_replays(self):
     keyboard.add_hotkey('a, b, c', trigger, suppress=True)
     self.do(du_a+du_b+du_a+du_b+du_space, du_a+du_b+du_a+du_b+du_space)
예제 #54
0
                          fg='black',
                          bg="black")
    label.config(width=360, height=120, cursor="none")
    label.master.overrideredirect(True)
    label.master.geometry("+0+0")
    label.master.lift()
    label.master.wm_attributes("-topmost", True)
    label.master.wm_attributes("-transparentcolor", "black")
    label.bind("<Button-1>", lambda event: toggle_black_screen(event.widget))
    hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
    globalExStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOOLWINDOW
    win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, globalExStyle)
    label.pack()

    # Keybindings
    keyboard.add_hotkey('ctrl+ü', toggle_game_close)
    keyboard.add_hotkey('ctrl+shift+ü', exit_script)
    keyboard.add_hotkey('ctrl+´', minimize_blacklisted)
    keyboard.add_hotkey("p", take_pic)
    keyboard.add_hotkey("v", toggle_survival)
    keyboard.add_hotkey("ctrl+shift+e",
                        callback=toggle_black_screen,
                        args=(label, ))

    # permanent infinite loops
    threads = list()
    threads.append(threading.Thread(target=auto_click_left))
    threads.append(threading.Thread(target=auto_click_right))
    threads.append(threading.Thread(target=survive))

    for thread in threads:
예제 #55
0
import keyboard
import core

arrowDownHotkey = core.getHotKeyCombination() + str('up')

def process():
    print("process: onArrowUp! api: ", core.getAndroidApi() )
    if core.getAndroidApi() is 23:
        core.adbKeyEvent('280')
    elif core.getAndroidApi() is 25:
        core.adbKeyEvent('KEYCODE_SYSTEM_NAVIGATION_UP')
    else:
        print("not defined for such api")

print 'Registrate ARROW_UP hotkey: ', arrowDownHotkey
keyboard.add_hotkey(arrowDownHotkey, process)
예제 #56
0
def install(
    package_name: str,
    verbose: bool,
    debug: bool,
    no_progress: bool,
    no_color: bool,
    logfile: str,
    yes: bool,
    silent: bool,
    python: bool,
    install_directory: str,
    virus_check: bool,
    no_cache: bool,
    sync: bool,
    reduce: bool,
    rate_limit: int,
    node: bool,
):
    if logfile:
        logfile = logfile.replace('=', '')
    metadata = generate_metadata(no_progress, silent, verbose, debug, no_color,
                                 yes, logfile, virus_check, reduce)

    if logfile:
        logfile = logfile.replace('.txt', '.log')
        createConfig(logfile, logging.INFO, 'Install')

    if python:

        package_names = package_name.split(',')

        for name in package_names:
            handle_python_package(name, 'install', metadata)

        sys.exit()

    if node:
        package_names = package_name.split(',')
        for name in package_names:
            handle_node_package(name, 'install', metadata)

        sys.exit()

    super_cache = check_supercache_valid()
    if no_cache:
        super_cache = False

    status = 'Initializing'
    setup_name = ''
    keyboard.add_hotkey('ctrl+c',
                        lambda: handle_exit(status, setup_name, metadata))

    packages = package_name.strip(' ').split(',')

    if super_cache:
        res, time = handle_cached_request()

    else:
        status = 'Networking'
        write_verbose('Sending GET Request To /packages', metadata)
        write_debug('Sending GET Request To /packages', metadata)
        log_info('Sending GET Request To /packages', logfile)
        res, time = send_req_all()
        res = json.loads(res)
        update_supercache(res)
        del res['_id']

    correct_names = get_correct_package_names(res)
    corrected_package_names = []

    for name in packages:
        if name in correct_names:
            corrected_package_names.append(name)
        else:
            corrections = difflib.get_close_matches(name, correct_names)
            if corrections:
                if silent:
                    click.echo(
                        click.style(
                            'Incorrect / Invalid Package Name Entered. Aborting Installation.',
                            fg='red'))
                    log_info(
                        'Incorrect / Invalid Package Name Entered. Aborting Installation',
                        logfile)
                    handle_exit(status, setup_name, metadata)

                if yes:
                    write(f'Autocorrecting To {corrections[0]}', 'green',
                          metadata)
                    log_info(f'Autocorrecting To {corrections[0]}', logfile)
                    write(f'Successfully Autocorrected To {corrections[0]}',
                          'green', metadata)
                    log_info(f'Successfully Autocorrected To {corrections[0]}',
                             logfile)
                    corrected_package_names.append(corrections[0])

                else:
                    write(f'Autocorrecting To {corrections[0]}',
                          'bright_magenta', metadata)
                    write_verbose(f'Autocorrecting To {corrections[0]}',
                                  metadata)
                    write_debug(f'Autocorrecting To {corrections[0]}',
                                metadata)
                    log_info(f'Autocorrecting To {corrections[0]}', logfile)
                    if click.prompt(
                            'Would You Like To Continue? [y/n]') == 'y':
                        package_name = corrections[0]
                        corrected_package_names.append(package_name)
                    else:
                        sys.exit()
            else:
                write(f'Could Not Find Any Packages Which Match {name}',
                      'bright_magenta', metadata)
                write_debug(f'Could Not Find Any Packages Which Match {name}',
                            metadata)
                write_verbose(
                    f'Could Not Find Any Packages Which Match {name}',
                    metadata)
                log_info(f'Could Not Find Any Packages Which Match {name}',
                         logfile)

    write_debug(install_debug_headers, metadata)
    for header in install_debug_headers:
        log_info(header, logfile)

    index = 0

    if not sync:
        if len(corrected_package_names) > 5:
            write(
                'electric Doesn\'t Support More Than 5 Parallel Downloads At Once Currently. Use The --sync Flag To Synchronously Download The Packages',
                'red', metadata)
        if len(corrected_package_names) > 1:
            packets = []
            for package in corrected_package_names:
                pkg = res[package]
                custom_dir = None
                if install_directory:
                    custom_dir = install_directory + f'\\{pkg["package-name"]}'
                else:
                    custom_dir = install_directory
                packet = Packet(package, pkg['package-name'], pkg['win64'],
                                pkg['darwin'], pkg['debian'],
                                pkg['win64-type'], pkg['darwin-type'],
                                pkg['debian-type'], pkg['custom-location'],
                                pkg['install-switches'],
                                pkg['uninstall-switches'], custom_dir)
                installation = find_existing_installation(
                    package, packet.json_name)
                if installation:
                    write_debug(
                        f"Aborting Installation As {packet.json_name} is already installed.",
                        metadata)
                    write_verbose(
                        f"Found an existing installation of => {packet.json_name}",
                        metadata)
                    write(
                        f"Found an existing installation {packet.json_name}.",
                        'bright_yellow', metadata)
                    installation_continue = click.prompt(
                        f'Would you like to reinstall {packet.json_name} [y/n]'
                    )
                    if installation_continue == 'y' or installation_continue == 'y' or yes:
                        os.system(f'electric uninstall {packet.json_name}')
                        os.system(f'electric install {packet.json_name}')
                        return
                    else:
                        handle_exit(status, setup_name, metadata)

                write_verbose(f"Package to be installed: {packet.json_name}",
                              metadata)
                log_info(f"Package to be installed: {packet.json_name}",
                         logfile)

                write_verbose(
                    f'Finding closest match to {packet.json_name}...',
                    metadata)
                log_info(f'Finding closest match to {packet.json_name}...',
                         logfile)
                packets.append(packet)

            if super_cache:
                write(
                    f'Rapidquery Successfully SuperCached Packages in {round(time, 6)}s',
                    'bright_yellow', metadata)
                write_debug(
                    f'Rapidquery Successfully SuperCached Packages in {round(time, 9)}s',
                    metadata)
                log_info(
                    f'Rapidquery Successfully SuperCached Packages in {round(time, 6)}s',
                    logfile)
            else:
                write(
                    f'Rapidquery Successfully Received packages.json in {round(time, 6)}s',
                    'bright_yellow', metadata)
                write_debug(
                    f'Rapidquery Successfully Received packages.json in {round(time, 9)}s',
                    metadata)
                log_info(
                    f'Rapidquery Successfully Received packages.json in {round(time, 6)}s',
                    logfile)

                write_verbose('Generating system download path...', metadata)
                log_info('Generating system download path...', logfile)

            manager = PackageManager(packets, metadata)
            paths = manager.handle_multi_download()
            log_info('Finished Rapid Download...', logfile)
            log_info(
                'Using Rapid Install To Complete Setup, Accept Prompts Asking For Admin Permission...',
                logfile)
            manager.handle_multi_install(paths)
            return

    for package in corrected_package_names:
        pkg = res[package]
        packet = Packet(package, pkg['package-name'], pkg['win64'],
                        pkg['darwin'], pkg['debian'], pkg['win64-type'],
                        pkg['darwin-type'], pkg['debian-type'],
                        pkg['custom-location'], pkg['install-switches'],
                        pkg['uninstall-switches'], install_directory)
        installation = find_existing_installation(package, packet.json_name)

        if installation:
            write_debug(
                f"Aborting Installation As {packet.json_name} is already installed.",
                metadata)
            write_verbose(
                f"Found an existing installation of => {packet.json_name}",
                metadata)
            write(f"Found an existing installation {packet.json_name}.",
                  'bright_yellow', metadata)
            installation_continue = click.prompt(
                f'Would you like to reinstall {packet.json_name} [y/n]')
            if installation_continue == 'y' or installation_continue == 'y' or yes:
                os.system(f'electric uninstall {packet.json_name}')
                os.system(f'electric install {packet.json_name}')
                return
            else:
                handle_exit(status, setup_name, metadata)
        write_verbose(f"Package to be installed: {packet.json_name}", metadata)
        log_info(f"Package to be installed: {packet.json_name}", logfile)

        write_verbose(f'Finding closest match to {packet.json_name}...',
                      metadata)
        log_info(f'Finding closest match to {packet.json_name}...', logfile)

        if index == 0:
            if super_cache:
                write(
                    f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 6)}s',
                    'bright_yellow', metadata)
                write_debug(
                    f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 9)}s',
                    metadata)
                log_info(
                    f'Rapidquery Successfully SuperCached {packet.json_name} in {round(time, 6)}s',
                    logfile)
            else:
                write(
                    f'Rapidquery Successfully Received {packet.json_name}.json in {round(time, 6)}s',
                    'bright_yellow', metadata)
                write_debug(
                    f'Rapidquery Successfully Received {packet.json_name}.json in {round(time, 9)}s',
                    metadata)
                log_info(
                    f'Rapidquery Successfully Received {packet.json_name}.json in {round(time, 6)}s',
                    logfile)

        write_verbose('Generating system download path...', metadata)
        log_info('Generating system download path...', logfile)

        start = timer()

        status = 'Download Path'
        download_url = get_download_url(packet)
        status = 'Got Download Path'
        end = timer()

        val = round(Decimal(end) - Decimal(start), 6)
        write(f'Electrons Transferred In {val}s', 'cyan', metadata)
        log_info(f'Electrons Transferred In {val}s', logfile)

        write('Initializing Rapid Download...', 'green', metadata)
        log_info('Initializing Rapid Download...', logfile)

        # Downloading The File From Source
        write_verbose(f"Downloading from '{download_url}'", metadata)
        log_info(f"Downloading from '{download_url}'", logfile)
        status = 'Downloading'

        if rate_limit == -1:
            path = download(download_url, no_progress, silent,
                            packet.win64_type)
        else:
            bucket = TokenBucket(tokens=10 * rate_limit, fill_rate=rate_limit)

            limiter = Limiter(
                bucket=bucket,
                filename=f"{tempfile.gettempdir()}\Setup{packet.win64_type}",
            )

            urlretrieve(
                url=download_url,
                filename=f"{tempfile.gettempdir()}\Setup{packet.win64_type}",
                reporthook=limiter)

            path = f"{tempfile.gettempdir()}\Setup{packet.win64_type}"

        status = 'Downloaded'

        write('\nFinished Rapid Download', 'green', metadata)
        log_info('Finished Rapid Download', logfile)

        if virus_check:
            write('Scanning File For Viruses...', 'blue', metadata)
            check_virus(path, metadata)

        write(
            'Using Rapid Install, Accept Prompts Asking For Admin Permission...',
            'cyan', metadata)
        log_info(
            'Using Rapid Install To Complete Setup, Accept Prompts Asking For Admin Permission...',
            logfile)
        if debug:
            click.echo('\n')
        write_debug(
            f'Installing {packet.json_name} through Setup{packet.win64}',
            metadata)
        log_info(f'Installing {packet.json_name} through Setup{packet.win64}',
                 logfile)
        start_snap = get_environment_keys()
        status = 'Installing'
        # Running The Installer silently And Completing Setup
        install_package(path, packet, metadata)

        status = 'Installed'
        final_snap = get_environment_keys()

        if final_snap.env_length > start_snap.env_length or final_snap.sys_length > start_snap.sys_length:
            write('Refreshing Environment Variables...', 'green', metadata)
            start = timer()
            log_info('Refreshing Environment Variables', logfile)
            write_debug(
                'Refreshing Env Variables, Calling Batch Script At scripts/refreshvars.cmd',
                metadata)
            write_verbose('Refreshing Environment Variables', metadata)
            refresh_environment_variables()
            end = timer()
            write_debug(
                f'Successfully Refreshed Environment Variables in {round(end - start)} seconds',
                metadata)

        write(f'Successfully Installed {packet.display_name}!',
              'bright_magenta', metadata)
        log_info(f'Successfully Installed {packet.display_name}!', logfile)

        if metadata.reduce_package:
            write('Successfully Cleaned Up Installer From Temp Directory...',
                  'green', metadata)
            os.remove(path)

        write_verbose('Installation and setup completed.', metadata)
        log_info('Installation and setup completed.', logfile)
        write_debug(
            f'Terminated debugger at {strftime("%H:%M:%S")} on install::completion',
            metadata)
        log_info(
            f'Terminated debugger at {strftime("%H:%M:%S")} on install::completion',
            logfile)
        closeLog(logfile, 'Install')

        index += 1
    end = timer()
예제 #57
0
        '10': ':keycap_ten:'
    }

    newString = ""

    for item in string:
        # print("ITEM = {}".format(item))
        if item in alphabet:
            newString = newString + " " + ":regional_indicator_{}:".format(
                item)
        elif item == "?":
            newString = newString + " " + ":question:"
        elif item == "!":
            newString = newString + " " + ":exclamation:"
        elif item in numbers.keys():
            newString = newString + " " + numbers[item]
        elif item == " ":
            newString = newString + "   "
        else:
            pass

    # print("DEBUGGING: newString = {}".format(str(newString)))
    pyperclip.copy(newString)


print(" [+] Your hotkey is {}.".format(keyToUse))

keyboard.add_hotkey(keyToUse, run)

keyboard.wait()
예제 #58
0
    def use_card(self, index, *args):
        hand_card = self.my_hand_cards[index]
        detail_card = hand_card.detail_card
        debug_print(f"将使用卡牌[{index}] {hand_card.name}")

        if detail_card is None:
            MinionNoPoint.use_with_arg(self, index, *args)
        else:
            detail_card.use_with_arg(self, index, *args)

        self.my_hand_cards.pop(index)
        return hand_card.current_cost


if __name__ == "__main__":
    keyboard.add_hotkey("ctrl+q", sys.exit)

    log_iter = log_iter_func(HEARTHSTONE_POWER_LOG_PATH)
    state = LogState()

    while True:
        log_container = next(log_iter)
        if log_container.length > 0:
            for x in log_container.message_list:
                update_state(state, x)
            strategy_state = StrategyState(state)
            strategy_state.debug_print_out()

            with open("game_state_snapshot.txt", "w", encoding="utf8") as f:
                f.write(str(state))
 def _set_hotkeys(self):
     keyboard.add_hotkey("ctrl+up", self._up_event)
     keyboard.add_hotkey("ctrl+down", self._down_event)
예제 #60
0
def all_off():
    global _red, _green, _blue, _blink, _modulation, _buzzer, _music
    if _red:
        toggle_red()
    if _green:
        toggle_green()
    if _blue:
        toggle_blue()
    _blink = False
    _modulation = False
    _buzzer = False
    _music = False
    print('all_off() 호출')


keyboard.add_hotkey('r', toggle_red)  # R 입력
keyboard.add_hotkey('g', toggle_green)  # G 입력
keyboard.add_hotkey('b', toggle_blue)  # B 입력
keyboard.add_hotkey('m', toggle_modulation)  # M 입력
keyboard.add_hotkey('x', toggle_blink)  # X 입력
keyboard.add_hotkey('s', toggle_music)  # S 입력
keyboard.add_hotkey('o', all_off)  # O 입력

try:
    while True:  # 메인 루프
        # PIR 감지
        if GPIO.input(24):  # 움직임을 감지했을 때
            toggle_pir()
            if _red:  # if RED on then Blink
                toggle_blink()
            else:  # RED on