Esempio n. 1
0
def main():

    session = asyncio.run(get_media_session())
    keyboard = Controller()

    if sys.argv[2] in ['play', 'pause', 'next', 'previous']:
        if session:
            info = asyncio.run(get_media_info(session))
            title = info.__getattribute__('title')
            artist = info.__getattribute__('artist')
            status = session.get_playback_info().playback_status
            if sys.argv[2] == 'play' and status != 4:
                print("Started: ->", title if title != "" else "Unknown",
                      "<- by ->", artist if artist != "" else "Unknown", "<-")
                session.try_play_async()
            elif sys.argv[2] == 'pause' and status != 5:
                print("Paused: ->", title if title != "" else "Unknown",
                      "<- by ->", artist if artist != "" else "Unknown", "<-")
                session.try_pause_async()
            elif sys.argv[2] == 'next':
                print("Skipping: ->", title if title != "" else "Unknown",
                      "<- by ->", artist if artist != "" else "Unknown", "<-")
                session.try_skip_next_async()
            elif sys.argv[2] == 'previous':
                print("Playing previous song:")
                session.try_skip_previous_async()
        else:
            print(int(sys.argv[1]))
            keyboard.tap(KeyCode.from_vk(int(sys.argv[1])))
    else:
        print(int(sys.argv[1]))
        keyboard.tap(KeyCode.from_vk(int(sys.argv[1])))
Esempio n. 2
0
def volume(up):
	if up:
		keyboard.press(KeyCode.from_vk(VK_VOLUME_UP))
		keyboard.release(KeyCode.from_vk(VK_VOLUME_UP))
	else:
		keyboard.press(KeyCode.from_vk(VK_VOLUME_DOWN))
		keyboard.release(KeyCode.from_vk(VK_VOLUME_DOWN))
Esempio n. 3
0
def play(stop = False):
	if stop:
		keyboard.press(KeyCode.from_vk(VK_MEDIA_STOP))
		keyboard.release(KeyCode.from_vk(VK_MEDIA_STOP))
	else:
		keyboard.press(KeyCode.from_vk(VK_MEDIA_PLAY_PAUSE))
		keyboard.release(KeyCode.from_vk(VK_MEDIA_PLAY_PAUSE))
Esempio n. 4
0
def changeTrack(previous):
	if previous:
		keyboard.press(KeyCode.from_vk(VK_MEDIA_PREV_TRACK))
		keyboard.release(KeyCode.from_vk(VK_MEDIA_PREV_TRACK))
	else:
		keyboard.press(KeyCode.from_vk(VK_MEDIA_NEXT_TRACK))
		keyboard.release(KeyCode.from_vk(VK_MEDIA_NEXT_TRACK))
Esempio n. 5
0
    def _darwin_key_press_event(self, event_type, event, keycode, flags):
        is_key_down = event_type == Quartz.kCGEventKeyDown
        is_ctrl_down = flags & Quartz.kCGEventFlagMaskControl == Quartz.kCGEventFlagMaskControl
        is_alt_down = flags & Quartz.kCGEventFlagMaskAlternate == Quartz.kCGEventFlagMaskAlternate
        is_cmd_down = flags & Quartz.kCGEventFlagMaskCommand == Quartz.kCGEventFlagMaskCommand
        is_shift_down = flags & Quartz.kCGEventFlagMaskShift == Quartz.kCGEventFlagMaskShift
        key_with_modifiers_tuple = (is_ctrl_down, is_alt_down, is_cmd_down,
                                    is_shift_down, keycode)

        # logger.debug('{} {} ctrl: {} alt: {} cmd: {} shift: {}'.format(keycode, 'down' if is_key_down else 'up', is_ctrl_down, is_alt_down, is_cmd_down, is_shift_down))

        # If the key is in the passthrough hotkey list, bypass our modifiers filtering.
        if key_with_modifiers_tuple in self._passthrough_hotkeys:
            logger.debug(
                'Passthrough hotkey: {}'.format(key_with_modifiers_tuple))

            # Unpress injected keys
            for injected_key in self._injected_keys:
                self._kb_controller.touch(KeyCode.from_vk(injected_key), False)
            self._injected_keys.clear()

            # Simulate modifiers.
            if key_with_modifiers_tuple[0]:
                self._kb_controller.touch(Key.ctrl, is_key_down)
            if key_with_modifiers_tuple[1]:
                self._kb_controller.touch(Key.alt, is_key_down)
            if key_with_modifiers_tuple[2]:
                self._kb_controller.touch(Key.cmd, is_key_down)
            if key_with_modifiers_tuple[3]:
                self._kb_controller.touch(Key.shift, is_key_down)
            self._kb_controller.touch(
                KeyCode.from_vk(key_with_modifiers_tuple[4]), is_key_down)
            return None

        return event
def on_press(key):
    print('{0} pressed'.format(key))

    if key == KeyCode.from_vk(269025047):
        print("hello")

    if key == KeyCode.from_vk(269025046):
        print("")
Esempio n. 7
0
 def __init__(self, token):
     super().__init__()
     self.token = token
     self.keyboard = Controller()
     self.pause_key = KeyCode.from_vk(0xB3)
     self.space_key = KeyCode.from_vk(0x20)
     self.selector = False  # True for space command, False for pause
     self.pause_strings = ['!pause', '!play']
     self.start_bot()
Esempio n. 8
0
def flasks():
    # listener = Listener()
    # listener.listen()
    keyboard = Keyboard(sleep=1)
    keyboard.key(KeyCode.from_vk(18))  # Flask 1
    keyboard.key(KeyCode.from_vk(19))  # Flask 2
    keyboard.key(KeyCode.from_vk(20))  # Flask 3
    keyboard.key(KeyCode.from_vk(21))  # Flask 4
    keyboard.key(KeyCode.from_vk(23))  # Flask 5
Esempio n. 9
0
def sayInChat(message):
    keyboard.press('t')
    time.sleep(0.1)
    keyboard.release('t')
    keyboard.type(message)
    time.sleep(0.2)
    keyboard.press(KeyCode.from_vk(VK.RETURN))
    time.sleep(0.1)
    keyboard.release(KeyCode.from_vk(VK.RETURN))
Esempio n. 10
0
 def quickSay(self, message):
     self.controller.press('t')
     time.sleep(0.05)
     self.controller.release('t')
     self.controller.type(message)
     time.sleep(0.1)
     self.controller.press(KeyCode.from_vk(VK.RETURN))
     time.sleep(0.05)
     self.controller.release(KeyCode.from_vk(VK.RETURN))
Esempio n. 11
0
def quickSay(message):
    output(message)
    keyboard.press('t')
    time.sleep(0.1)
    keyboard.release('t')
    keyboard.type(message)
    time.sleep(0.2)
    keyboard.press(KeyCode.from_vk(VK.RETURN))
    time.sleep(0.1)
    keyboard.release(KeyCode.from_vk(VK.RETURN))
Esempio n. 12
0
def on_press(key):
    print('{0} pressed'.format(key))
    #next track key
    if key == KeyCode.from_vk(269025047):
        sp.next_track()

    if key == KeyCode.from_vk(269025046):
        sp.previous_track()

    if key == KeyCode.from_vk(269025044):
        sp.start_playback()
Esempio n. 13
0
 def sayInChat(self, message):
     self.controller.press('t')
     time.sleep(0.1)
     self.controller.release('t')
     self.controller.type(message)
     time.sleep(0.2)
     self.controller.press(KeyCode.from_vk(VK.RETURN))
     time.sleep(0.1)
     self.controller.release(KeyCode.from_vk(VK.RETURN))
     if self.slowchat:
         time.sleep(3.05)
     else:
         time.sleep(1.05)
Esempio n. 14
0
def sayInChat(message):
    global SLOWCHAT
    output(message)
    keyboard.press('t')
    time.sleep(0.1)
    keyboard.release('t')
    keyboard.type(message)
    time.sleep(0.2)
    keyboard.press(KeyCode.from_vk(VK.RETURN))
    time.sleep(0.1)
    keyboard.release(KeyCode.from_vk(VK.RETURN))
    if SLOWCHAT:
        time.sleep(3.05)
    else:
        time.sleep(1.05)
Esempio n. 15
0
def start(com):
    global auto_mode
    com[0] = auto_mode
    global master
    #master = tkinter.Tk()
    #is_on = tkinter.Label(text="MACROS PAUSED", fg='black')
    global s_key, delay, stop_key
    db = sqlite3.connect("./config.db")
    cursor = db.cursor()
    cursor.execute('''SELECT id FROM conf WHERE name = ?''', ("pause", ))
    x = cursor.fetchone()[0]
    s_key = KeyCode.from_vk(x)
    """cursor.execute('''SELECT id FROM conf WHERE name = ?''', ("stop",))
    x = cursor.fetchone()[0]
    stop_key = KeyCode.from_vk(x)"""
    cursor.execute('''SELECT cnt FROM nums WHERE name = ?''', ("cps", ))
    x = cursor.fetchone()[0]
    delay = 1 / max(x, 1)
    #delay = delay / 1000
    keyboard_listener.start()
    mouse_listener.start()
    click(com)
    #master.mainloop()
    keyboard_listener.join()
    mouse_listener.join()
Esempio n. 16
0
 def test_parse_valid(self):
     self.assertSequenceEqual(
         HotKey.parse('a'),
         [
             kc.from_char('a')])
     self.assertSequenceEqual(
         HotKey.parse('A'),
         [
             kc.from_char('a')])
     self.assertSequenceEqual(
         HotKey.parse('<ctrl>+a'),
         [
             k.ctrl,
             kc.from_char('a')])
     self.assertSequenceEqual(
         HotKey.parse('<ctrl>+<alt>+a'),
         [
             k.ctrl,
             k.alt,
             kc.from_char('a')])
     self.assertSequenceEqual(
         HotKey.parse('<ctrl>+<123456>'),
         [
             k.ctrl,
             kc.from_vk(123456)])
Esempio n. 17
0
    def canonical(self, key):
        """Performs normalisation of a key.

        This method attempts to convert key events to their canonical form, so
        that events will equal regardless of modifier state.

        This method will convert upper case keys to lower case keys, convert
        any modifiers with a right and left version to the same value, and may
        slow perform additional platform dependent normalisation.

        :param key: The key to normalise.
        :type key: Key or KeyCode

        :return: a key
        :rtype: Key or KeyCode
        """
        from pynput.keyboard import Key, KeyCode, _NORMAL_MODIFIERS
        if isinstance(key, KeyCode) and key.char is not None:
            return KeyCode.from_char(key.char.lower())
        elif isinstance(key, Key) and key.value in _NORMAL_MODIFIERS:
            return _NORMAL_MODIFIERS[key.value]
        elif isinstance(key, Key) and key.value.vk is not None:
            return KeyCode.from_vk(key.value.vk)
        else:
            return key
Esempio n. 18
0
    def _darwin_key_flags_changed_event(self, event, keycode, flags):
        is_ctrl_key = keycode == Key.ctrl.value.vk or keycode == Key.ctrl_l.value.vk or keycode == Key.ctrl_r.value.vk
        is_alt_key = keycode == Key.alt.value.vk or keycode == Key.alt_l.value.vk or keycode == Key.alt_r.value.vk
        is_cmd_key = keycode == Key.alt.value.vk or keycode == Key.cmd_l.value.vk or keycode == Key.cmd_r.value.vk

        is_key_down = None
        if is_ctrl_key:
            is_key_down = flags & Quartz.kCGEventFlagMaskControl == Quartz.kCGEventFlagMaskControl
        elif is_alt_key:
            is_key_down = flags & Quartz.kCGEventFlagMaskAlternate == Quartz.kCGEventFlagMaskAlternate
        elif is_cmd_key:
            is_key_down = flags & Quartz.kCGEventFlagMaskCommand == Quartz.kCGEventFlagMaskCommand

        # Translate the key
        if is_key_down is not None and keycode in self._remap_keys:
            to = self._remap_keys.get(keycode)
            logger.debug('Remapping {}->{}'.format(keycode, to))
            # Simulate target key.
            self._kb_controller.touch(KeyCode.from_vk(to), is_key_down)
            if is_key_down:
                self._injected_keys.add(to)
            else:
                self._injected_keys.discard(to)
            return None
        return event
Esempio n. 19
0
def to_KeyCode(x:list):
    ans = KeyCode.from_vk(x[0])
    if len(x[1]) == 1:
        ans.char = x[1]
    else:
        ans.char = None
    return ans
Esempio n. 20
0
    def drink_life_potions(self):
        print("Starting drink_life_potions")
        while self.RUN:

            if not self.TOGGLE:
                sleep(0.1)
                continue

            self.vision.capture_window(self.potions_box)

            life_10 = self.vision.pcat(x=105, y=15, channel="red", threshold=70)
            life_20 = self.vision.pcat(x=105, y=25, channel="red", threshold=80)
            life_30 = self.vision.pcat(x=105, y=35, channel="red", threshold=80)
            life_40 = self.vision.pcat(x=105, y=45, channel="red", threshold=80)
            life_50 = self.vision.pcat(x=102, y=55, channel="red", threshold=80)
            life_60 = self.vision.pcat(x=102, y=65, channel="red", threshold=80)
            life_70 = self.vision.pcat(x=105, y=75, channel="red", threshold=80)
            life_80 = self.vision.pcat(x=105, y=85, channel="red", threshold=80)
            life_90 = self.vision.pcat(x=105, y=95, channel="red", threshold=80)
            life_100 = self.vision.pcat(x=105, y=105, channel="red", threshold=80)
            life_110 = self.vision.pcat(x=105, y=115, channel="red", threshold=80)
            life_120 = self.vision.pcat(x=105, y=125, channel="red", threshold=80)
            life_130 = self.vision.pcat(x=105, y=135, channel="red", threshold=80)
            life_140 = self.vision.pcat(x=105, y=145, channel="red", threshold=70)
            life_150 = self.vision.pcat(x=105, y=155, channel="red", threshold=70)
            life_160 = self.vision.pcat(x=105, y=165, channel="red", threshold=60)
            life_170 = self.vision.pcat(x=105, y=175, channel="red", threshold=60)
            life_1 = self.vision.pcat(x=298, y=175, channel="red", threshold=60)
            life_2 = self.vision.pcat(x=338, y=175, channel="red", threshold=60)
            in_game = self.vision.pcat(238, 126, channel="green", threshold=70)

            if not life_120 and in_game:
                self.keyboard.quit()
                print("Emergency exit (life too low)")

            if not life_30:
                if life_1:
                    self.keyboard.key(KeyCode.from_vk(self.KEYCODES[1]))
                    print("Drinking from LP1")
                    sleep(0.1)
                elif life_2:
                    self.keyboard.key(KeyCode.from_vk(self.KEYCODES[2]))
                    print("Drinking from LP2")
                    sleep(0.1)
                elif in_game:
                    self.keyboard.quit()
                    print("Emergency exit (No more potions)")
Esempio n. 21
0
 def _populate_tools(self):
     tools = {
         "brush": 'b',
         "bucket": 'f',
         "crop": 'c',
         "geo": [Key.ctrl, Key.alt, '.'],
         "select": [Key.ctrl, 'r'],
         "eraser": ['b', 'e'],
         "move": 't',
         "brush1": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(97)],
         "brush2": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(98)],
         "brush3": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(99)],
         "brush4": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(100)],
         "brush5": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(101)],
         "brush6": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(102)],
         "brush7": [Key.ctrl, Key.alt,
                    KeyCode.from_vk(103)],
         "geo1": [Key.ctrl, Key.alt, '.'],
         "geo2": [Key.ctrl, Key.alt, ';'],
         "geo3": [Key.ctrl, '='],
         "geo4": [Key.ctrl, Key.alt, '~'],
         "geo5": [Key.ctrl, Key.alt, "'"],
         "selection1": [Key.ctrl, 'r'],
         "selection2": 'j',
         "selection3": [Key.ctrl, Key.alt, '\\'],
         "selection4": [Key.ctrl, Key.alt, ']']
     }
     return tools
Esempio n. 22
0
    def __init__(self, key):
        """Initialize ARKey class."""
        self.isctrl = False
        self.ischar = False

        if isinstance(key, (Key, KeyCode)):
            self.isctrl = (key == Key.ctrl_l) or (key == Key.ctrl_r)
            self.key = key

        elif isinstance(key, int):
            try:
                self.key = Key(KeyCode.from_vk(key))

            except ValueError:
                self.key = KeyCode.from_vk(key)

        elif isinstance(key, str):
            self.key = KeyCode.from_char(key)
Esempio n. 23
0
    def run(self):
        with open(self.file_name, 'r', encoding='utf-8') as file:
            keyboard_exec = Controller()
            line = file.readline()
            time.sleep(3)
            while line:
                obj = json.loads(line)
                if obj['name'] == 'keyboard':
                    if obj['event'] == 'press':
                        keyboard_exec.press(KeyCode.from_vk(obj['vk']))
                        time.sleep(0.01)

                    elif obj['event'] == 'release':
                        keyboard_exec.release(KeyCode.from_vk(obj['vk']))
                        time.sleep(0.01)
                line = file.readline()
            startExecuteBtn['text'] = '回放'
            startExecuteBtn['state'] = 'normal'
Esempio n. 24
0
    def run(self):
        if not os.path.exists(self.file_name):
            os.mkdir(self.file_name)
        with open(self.file_name, 'r', encoding='utf-8') as file:
            keyboard_exec = KeyBoardController()
            line = file.readline()
            # if not line:
            #     print('no key')
            #     return
            while line:
                if len(line) == 1:
                    line = file.readline()
                    continue
                obj = json.loads(line)
                # print(obj)
                if obj['name'] == 'keyboard':
                    delay = obj['time'] / self.speed
                    if delay > 1:
                        self.listening_sleep(delay)
                    else:
                        time.sleep(delay)

                    if obj['event'] == 'press':

                        keyboard_exec.press(KeyCode.from_vk(obj['vk']))

                    elif obj['event'] == 'release':

                        keyboard_exec.release(KeyCode.from_vk(obj['vk']))
                if self.stoper:
                    print('keystoper')
                    # self.stoper = False
                    break
                line = file.readline()
            keyboard_exec.release(keyboard.Key.ctrl)
            keyboard_exec.release(keyboard.Key.shift)
            keyboard_exec.release(keyboard.Key.alt)

        while self.parent.mouseActionrunner.isRunning():
            time.sleep(0.1)
            # print('waiting mouse stop')
        print('动作播放完一次')
        if not self.stoper:
            self.end_run_a_round_signal.emit()
Esempio n. 25
0
def combo_press(vk):
    global combo_vk
    global quit

    combo_vk = vk

    # Press `ESC` to quit
    if vk == 27:
        quit = True
        return

    print('---- start combo -----', vk)
    while vk == combo_vk:
        keyboard_ctl.press(KeyCode.from_vk(vk))
        time.sleep(0.002)
        assert vk == combo_vk
        keyboard_ctl.release(KeyCode.from_vk(vk))
        time.sleep(0.1)
    print('--------------------------')
Esempio n. 26
0
    def run(self):
        while self.execute_count > 0:
            print("第", self.execute_count, '次回放')
            with open(self.file_name, 'r', encoding='utf-8') as file:
                keyboard_exec = KeyBoardController()
                line = file.readline()
                while line:
                    obj = json.loads(line)
                    if obj['name'] == 'keyboard':
                        if obj['event'] == 'press':
                            keyboard_exec.press(KeyCode.from_vk(obj['vk']))
                            time.sleep(moveTime)

                        elif obj['event'] == 'release':
                            keyboard_exec.release(KeyCode.from_vk(obj['vk']))
                            time.sleep(moveTime)
                    line = file.readline()
                startExecuteBtn['text'] = '开始回放'
                startExecuteBtn['state'] = 'normal'
            self.execute_count = self.execute_count - 1
Esempio n. 27
0
 def post(self):
     current_time = time.strftime("%d.%m.%Y %H:%M:%S", time.localtime())
     ip = self.request.remote_ip
     username = self.get_argument('username')
     action = self.get_argument('action')
     # self.redirect('/ws')
     print("{}: {}: POST: {} {}".format(current_time, ip, username, action))
     keyboard = Controller()
     if action == 'next':
         keyboard.press(KeyCode.from_vk(0xB0))
     elif action == 'prev':
         keyboard.press(KeyCode.from_vk(0xB1))  #0xB1 pause media
     elif action == 'hide':
         keyboard.press(Key.ctrl)
         keyboard.press(Key.space)
         keyboard.release(Key.ctrl)
         keyboard.release(Key.space)
     elif action == "log":
         keyboard.type('Hello World')
     self.write("{}: Wow {} {}".format(ip, username, action))
Esempio n. 28
0
    def onClick(self, x, y, button, pressed):
        if button != Button.right or not pressed:
            return True

        time.sleep(0.05)
        slot = random.choices(
            population=range(1, 10), weights=self.slotWeights
        )[0]
        key = KeyCode.from_vk(0x30 + slot)
        self.keyboard.press(key)
        time.sleep(0.05)
        self.keyboard.release(key)
    def _win32_key_event_listener(self, msg, data):
        is_key_down = msg == WM_KEYDOWN or msg == WM_SYSKEYDOWN
        keycode = data.vkCode
        # logger.debug('vkCode {} {}'.format(data.vkCode, hex(data.vkCode)))

        if keycode in self._remap_keys:
            to = self._remap_keys.get(keycode)
            logger.debug('Remapping {}->{}'.format(keycode, to))
            # Simulate target key.
            self._kb_controller.touch(KeyCode.from_vk(to), is_key_down)
            self._listener.suppress_event()
            return True
        return True
Esempio n. 30
0
def search():
    scr = Wnck.Screen.get_default()
    scr.force_update()
    windows = scr.get_windows()
    for window in windows:
        if window.get_icon_name() in adsnames:
            """if ads is recognised, reboot spotify """
            print(
                window.get_icon_name() + " ad detected -> close spotify ",
                end='')
            p = psutil.Process(window.get_pid())
            p.kill()
            print(colored('OK', 'green'))

            run_spotify()
            time.sleep(5)

            """Press Next button in media commands to launch next music """
            print("play music")
            keyboard.press(KeyCode.from_vk(269025047))
            keyboard.release(KeyCode.from_vk(269025047))
    time.sleep(1)