def make_selection(select_mode, num_arrows=None): def shift_home_select(): keyboard = Controller() with keyboard.pressed(Key.shift): keyboard.press(Key.home) keyboard.release(Key.shift) if select_mode == 'all': k.press_and_release('Ctrl+a') elif select_mode == 'shift_home': shift_home_select() elif select_mode == 'end_shift_home': k.press_and_release('end') shift_home_select() elif select_mode == 'end_shift_left_arrow': k.press_and_release('end') keyboard = Controller() keyboard.press(Key.shift) for x in range(num_arrows): keyboard.press(Key.left) keyboard.release(Key.left) keyboard.release(Key.shift)
def run_browser(): config = configparser.ConfigParser() try: config.read('conf.ini') exe = config['browser']['exe'] except Exception as e: exe = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' if debug: print(f'Opening browser {exe}') subprocess.Popen(exe + " http://play.alienworlds.io") time.sleep(2) subprocess.Popen(exe + " https://wallet.wax.io/dashboard") time.sleep(5) #БАГ! На расширении 800х600 нужен костыль для скролла сайта вниз. Допилил ниже #Не тестил. Может уйти в вечный цикл. Надеюсь, что нет. Завтра будем тестить весь код # + на ночь 5 серверов поставил subprocess.Popen(exe + " https://wax.alcor.exchange/swap?output=WAX-eosio.token&input=TLM-alien.worlds-eosio.token") time.sleep(5) while True: if see("tlm"): click(785,793,543,556) break # Простой способ переключить вкладку with keyboard.pressed(Key.ctrl): keyboard.press('1')
def kr(): keyboard = Controller() # keyboards=keyboard.Controller() # keyboards.press(keyboards.key.cmd) # keyboards.release(keyboards.key.cmd) keyboard.press(Key.cmd) keyboard.release(Key.cmd)
def play_old(): try: while True: c.play_picture( "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/" ) file = "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/" + str( c.counter_play - 1) + ".png" img = image.load_img(file, target_size=(250, 75)) img_tensor = image.img_to_array(img) img_tensor = np.expand_dims(img_tensor, axis=0) img_tensor /= 255. res = model.predict(img_tensor)[0, 0] if res < 0.5: keyboard.press(Key.up) time.sleep(0.01) keyboard.release(Key.up) print(str(c.counter_play - 1) + ": " + str(res)) sys.stdout.flush() except KeyboardInterrupt: pass
def alkor_swap(stack): """ Функция автоматически меняет 3 тлм на вакс для покупки ресурсов. """ ''' Идея по коду( добавить сюда так же проверку по изображениям, как и везде в коде) Для перестраховки на случай долгой загрузки ''' time.sleep(1) #Клик по области ввода количества токенов time.sleep(1) #нужны чёткие координаты. Поэтому, не подойдёт функция. Случай единичный. hc.move((67,258), 1) hc.click() #Ввод цифры 3 в область ввода time.sleep(0.5) keyboard.press('1') keyboard.release('1') time.sleep(2) # Клик на кнопку swap tlm click(40, 745, 455, 490) #Вызов функции решения капчи captcha() #Вызов функции buy_resourses changeTab(tab=2, stack = stack)
def walk_UD(buffer=0): """ Simulates walking once up and then once down whlie checking if the player is in abttle. The function starts by pressing 'w' and then waits 'buffer' amount of seconds before pressing 's'. In between pressing and releasing a 'w' or 's', the program also checks if the player is in battle. The time it takes to check depends on how fast your computer is. :param buffer: the number of seconds for which the player will walk in each direction return: Returns True if in battle, returns False if not in battle """ # Start walking left keyboard.press('w') # Detect if there is a battle on Screen dif = BattleDetect.Bat() 'Adjust for # of steps' time.sleep(buffer) if dif < .1: print("In battle") return True keyboard.release('w') # Start walking right keyboard.press('s') # Detect Battle on Screen dif = BattleDetect.Bat() 'Adjust for # of steps' time.sleep(buffer) if dif < .1: print("In battle") return True keyboard.release('s') #No battle is detected return False
async def play(self, song_config: SongConfig): keyboard = pynput.keyboard.Controller() # load mid file and get key map print(f"loading {os.path.basename(song_config.file_path)}") mid = mido.MidiFile(song_config.file_path) if song_config.use_auto_root: note_key_map = self.auto_root_key_map( mid, song_config.auto_root_channels, song_config.auto_root_tracks, song_config.auto_root_lowest, song_config.auto_root_highest, song_config.auto_root_use_count) else: note_key_map = NoteKeyMap(song_config.root_note) # filter tracks if song_config.track_filter: cur_del = 0 for i in range(len(mid.tracks)): if i not in song_config.track_filter: del mid.tracks[i - cur_del] cur_del += 1 # play print('start playing') fast_forward_time = song_config.skip_start_time for msg in mid: # check for stop if not self.play_task_active: print("stop playing") for key in self.cur_pressed_keys.copy(): keyboard.release(key) break # skip if fast forward if fast_forward_time > 0: fast_forward_time -= msg.time continue else: await asyncio.sleep(msg.time) # press keys if msg.type == "note_on" \ and (len(song_config.channel_filter) == 0 or msg.channel in song_config.channel_filter): try: key = note_key_map.get_key(msg.note) keyboard.press(key) except: pass elif msg.type == "note_off" \ and (len(song_config.channel_filter) == 0 or msg.channel in song_config.channel_filter): try: key = note_key_map.get_key(msg.note) keyboard.release(key) except: pass self.play_task_active = False print("finished playing")
def play_character_presses(self, press_character_string, chat_window=True): if chat_window: # bring up chat window keyboard.press(Key.enter) keyboard.release(Key.enter) # loop through and send each keypress separately for single_character in press_character_string: keyboard.press(single_character) keyboard.release(single_character)
def press_w(): keyboard.press('w') keyboard.release('w') # press_a() # press_d() # press_s() # press_w()
def press_keys(keys): keyboard = Controller() for key in pressed_keys: keyboard.release(key) for key in keys: pressed_keys.add(key) keyboard.press(key)
def cmd_tab(kbd, kbk): press_delay = 0.07 standard_delay = 0.25 kbd.press(kbk.cmd) time.sleep(press_delay) kbd.press(kbk.tab) time.sleep(press_delay) kbd.release(kbk.tab) time.sleep(press_delay) kbd.release(kbk.cmd) time.sleep(standard_delay)
def attackFirstMove(): """ Presses 1, waits for move selection menu to appear, then press 1 again to select the first move """ print("Attack") # Select Attack keyboard.press('1') keyboard.release('1') # Select First Ability time.sleep(.3) keyboard.press('1') keyboard.release('1')
def keyboard_controller(self, content): flag = content.split("|")[1].strip() try: button = ast.literal_eval(content.split("|")[0].strip()) except: button = content.split("|")[0].strip() try: keyboard = pynput.keyboard.Controller() if "press" in flag: keyboard.press(button) elif "release" in flag: keyboard.release(button) except: pass
def myMainEvent(): from pynput.keyboard import Controller, Key import time keyboard = Controller() if Status.my_current_loop == 0: with keyboard.pressed(Key.alt): keyboard.press(Key.tab) keyboard.release(Key.tab) time.sleep(0.2) # Delays for 5 seconds. You can also use a float value. ''' This is infinite loop. The index of loop will start from 0. It means the Status.my_current_loop == 0 as above code. ''' if Status.my_current_loop < 16: keyboard.type(",\"") keyboard.press(Key.end) keyboard.release(Key.end) keyboard.type("\"") keyboard.press(Key.down) keyboard.release(Key.down) keyboard.press(Key.home) keyboard.release(Key.home) ''' with keyboard .pressed(Key.ctrl): keyboard.press('v') keyboard.release('v') ''' Status.my_current_loop = Status.my_current_loop + 1
def setText(aString): # 写入剪切板 s = transString(aString) print(s) try: for aString in s: aString = aString.encode('utf-8') w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(win32con.CF_TEXT, aString) w.CloseClipboard() keyboard = Controller() # keyboard.press(Key.alt_l) keyboard.press(Key.enter) time.sleep(0.3) # keyboard.release(Key.alt_l) keyboard.release(Key.enter) time.sleep(0.3) keyboard.press(Key.ctrl_l) keyboard.press('v') time.sleep(0.3) keyboard.release('v') keyboard.release(Key.ctrl_l) time.sleep(0.3) # keyboard.press(Key.alt_l) keyboard.press(Key.enter) time.sleep(0.3) # keyboard.release(Key.alt_l) keyboard.release(Key.enter) print(1) except: pass
def le_advertise_packet_handler(mac, data, rssi): global prev_data global prev_rot_val print() print("packet len is", len(data)) data_str = raw_packet_to_str(data) data_wo_rssi = (mac, data_str) print("BLE packet: %s %s %d" % (mac, data_str, rssi)) if prev_data is not None: if data_wo_rssi != prev_data: # color differences with previous packet data sys.stdout.write(' ' * 20 + 'data_diff=') for c1, c2 in zip(data_str, prev_data[1]): if c1 != c2: sys.stdout.write('\033[0;33m' + c1 + '\033[m') else: sys.stdout.write(c1) sys.stdout.write('\n') # Advertisement are split into: # <sub-packet length byte> <sub-packet type byte> <sub-packet data (length-1)>" # (types are listed here: https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile) pkt_start = 4 pkt_data_start = pkt_start + 2 pkt_data_len = data[pkt_start] - 1 assert data[pkt_start + 1] == 0x09 # Type should be "Complete Local Name" print("name is %r" % data[pkt_data_start:pkt_data_start + pkt_data_len].decode('utf-8')) pkt_start = pkt_data_start + pkt_data_len pkt_data_start = pkt_start + 2 pkt_data_len = data[pkt_start] - 1 assert data[pkt_start + 1] == 0xFF # Type should be "Manufacturer Specific Data" print("manufacturer data len is", pkt_data_len) my_data = data[pkt_data_start:pkt_data_start + pkt_data_len] my_data = struct.unpack('B' * pkt_data_len, my_data) print("manufacturer data is", my_data) if my_data[2] == 1: key = pynput.keyboard.Key.right key = KEY_VOLUME_UP keyboard.press(key); keyboard.release(key) elif my_data[2] == 2: key = pynput.keyboard.Key.left key = KEY_VOLUME_DOWN keyboard.press(key); keyboard.release(key) prev_rot_val = my_data[1] prev_data = data_wo_rssi
def on_press(key): try: if key.char == ATTACK_HOTKEY: keyboard.press('a') keyboard.release('a') time.sleep(0.15) mouse.press(Button.left) time.sleep(0.05) mouse.release(Button.left) if key.char == MOVE_HOTKEY: time.sleep(0.15) mouse.press(Button.right) time.sleep(0.05) mouse.release(Button.right) except AttributeError: return True
def select_text(x0=R.x0_select_text, y0=R.y0_select_text, x1=R.x0_select_text + 1000, y1=R.y0_select_text): if x0 == R.x0_select_text and y0 == R.y0_select_text and x1 == R.x0_select_text + 1000 and y1 == R.y0_select_text: log("Using default configuration you might have errors !") else: pass text_pointeur.position = (x0, y0) text_pointeur.press(Button.left) text_pointeur.position = (x1, y1) text_pointeur.release(Button.left) sleep(.01) with keyboard.pressed(Key.ctrl): keyboard.press('c') keyboard.release('c') return clipboard.paste()
def buy_resourses(stack, pereklik = False): ''' Покупает в кошельке вакс два вида ресурсов в зависимости от переменной stack stack = 1 , то будет куплен ресурс cpu stack = 2 , то будет куплен ресурс ram Картинки с ошибкой ram нету, т.к. ошибка редкая , но всё равно рано или поздно выскочит Как только будет картинка - скину ''' while True: time.sleep(1) # Если pereklik = False - вызов функции alcor_swap ''' Идея по коду - убрать этот велосипед вызыванием функции alcor_swap сразу же, а не через функцию buy_resources ''' if not pereklik: changeTab(tab=3, stack= stack) # Кликает на картинку вакса, для вызова меню, где можно купить ресурсы if see("wax_ava_v_nft"): click(758, 776, 90, 104) # Кликает на кнопку ресурсов. Поиск проводится по скриншоту немного выше сделанному, # т.к. слетает винда, но не на всех акках, из-за этого не находит скрин if see("resources"): click(588, 747, 448, 477) #Кликает по пустому месту в новом окне, чтобы сделать его активным click(46, 536, 275, 505) time.sleep(1) # Нажимает page_down для скролла сайта вниз if see("network_resources"): keyboard.press(Key.page_down) time.sleep(1) if stack == 2: # Если нужно купить ресурс рам - выбирает его. click(132, 199, 446, 475) click(123, 211, 538, 551) # покупает ресурс if see("stake") or see("buy"): click(239, 409, 449, 475) time.sleep(0.5) keyboard.press('1') keyboard.release('1') click(439, 503, 441, 477) captcha() # Перезагружает вкладку с перекликом в основную фукцию игры. reload(tab=1) time.sleep(1)
def play_dual(): try: while True: c.play_picture( "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/dual/pics/" ) c_score.play_picture( "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/dual/score/" ) file_pic = "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/dual/pics/" + str( c.counter_play - 1) + ".png" score_pic = "C:/Users/bened/OneDrive/Arbeit/Lernen/python_training/play_pics/dual/score/" + str( c_score.counter_play - 1) + ".png" img_pic = image.load_img(file_pic, target_size=(75, 250)) img_pic_tensor = image.img_to_array(img_pic) img_pic_tensor = np.expand_dims(img_pic_tensor, axis=0) img_pic_tensor /= 255 score_pic = image.load_img(score_pic, target_size=(50, 160)) img_score_tensor = image.img_to_array(score_pic) img_score_tensor = (img_score_tensor - 128) / 128 img_score_tensor = img_score_tensor[:, :, 0] img_score_tensor = np.expand_dims(img_score_tensor, axis=0) img_score_tensor = np.expand_dims(img_score_tensor, axis=3) score = model_score.predict(img_score_tensor) score = get_result(score) score = int(score) score = np.expand_dims(score, axis=0) res = model.predict([img_pic_tensor, score]) if res > 0.5: keyboard.press(Key.up) time.sleep(0.015) keyboard.release(Key.up) print(str(c.counter_play - 1) + ": " + str(res)) sys.stdout.flush() except KeyboardInterrupt: pass
def on_click(x, y, button, pressed): keyboard.press(Key.shift) keyboard.press(Key.cmd) keyboard.press('3') keyboard.release(Key.shift) keyboard.release(Key.cmd) keyboard.release('3')
def get_ci(): a=[1,2] with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() keyboard = Controller() #检测剪切版里原有的东西 try: data_first=pyperclip.paste() except pyperclip.PyperclipException: data_first='' with keyboard.pressed(Key.ctrl): keyboard.press('c') time.sleep(0.2) keyboard.release('c') try: data_later=pyperclip.paste() except pyperclip.PyperclipException: data_later='null' if data_later!='null' and data_later!='': pyperclip.copy(data_first) return data_later else: pass
def run_tutorial(): park_names = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '999' ] park = 0 while park <= 21: g = open("coords") for line in g: f = line if f == 'name\n': delay_ = g.readline() time.sleep(float(delay_)) keyboard.press('a') f = g.readline() if f == 'id\n': delay_ = g.readline() time.sleep(float(delay_)) for key in ['3', '1', '3', '0', '7', '9', '4']: keyboard.press(key) f = g.readline() if f == 'parkname\n': delay_ = g.readline() time.sleep(float(delay_)) if len(park_names[0]) > 1: keyboard.press(park_names[park][0]) keyboard.press(park_names[park][1]) else: keyboard.press(park_names[park]) park += 1 f = g.readline() pos = f.replace("(", "").replace(")", "").split(',') delay_ = g.readline() time.sleep(float(delay_)) mouse.position = (float(pos[0]), float(pos[1])) time.sleep(.1) mouse.click(button) print(mouse.position) click_thread.exit()
def press(self, key='shift'): """not implemented from pseudolanguage""" if key == 'ctrl': keyboard.press(key.ctrl) elif key == 'alt': keyboard.press(key.alt) elif key == 'shift': keyboard.press(key.shift)
def handle(self, client): while True: try: message = client.recv(1024) key = message.decode("utf-8") key = key.replace("'", "") print(key) if key in self.keyslist: keyboard.press(key) keyboard.release(key) except: index = self.clients.index(client) self.clients.remove(client) client.close() print("Client closed the connection.") break
async def play(self): keyboard = pynput.keyboard.Controller() print("start Playing") playTime = time.time() for msg in mid: #check for stop if not self.playTaskActive: print("stop playing") for key in self.curPressedKey.copy(): keyboard.release(key) return if msg.time > 0: await asyncio.sleep(msg.time - (time.time() - playTime)) playTime += msg.time #press key if msg.type == "note_on" and msg.velocity != 0: if key := keyDict.get(msg.note): keyboard.press(key) await asyncio.sleep(0.01) keyboard.release(key)
def produc_press(): keyboard = Controller() # 按键盘和释放键盘 keyboard.press(Key.space) keyboard.release(Key.space) # 按小写的a keyboard.press('a') keyboard.release('a') # 按大写的A keyboard.press('A') keyboard.release('A')
def press(typekey, distance=0.1): keyboard.press(typekey) time.sleep(distance) keyboard.release(typekey)
def write(self, text): if text == "%{TAB}": with keyboard.pressed(key.alt): keyboard.press(key.tab) keyboard.release(key.tab) elif text == "%{TAB 2}": with keyboard.pressed(key.alt): keyboard.press(key.tab) keyboard.release(key.tab) time.sleep(0.1) keyboard.press(key.tab) keyboard.release(key.tab) elif text == "%{TAB 3}": with keyboard.pressed(key.alt): keyboard.press(key.tab) keyboard.release(key.tab) time.sleep(0.1) keyboard.press(key.tab) keyboard.release(key.tab) time.sleep(0.1) keyboard.press(key.tab) keyboard.release(key.tab) elif text == "%T": with keyboard.pressed(key.alt): keyboard.type("T") elif text == "{DOWN}": keyboard.press(key.down) keyboard.release(key.down) elif text == "{ESC}": keyboard.press(key.esc) keyboard.release(key.esc) elif text == "{F5}": #with keyboard.pressed(key.alt): keyboard.press(key.f5) keyboard.release(key.f5) elif text == "{ENTER}": #with keyboard.pressed(key.alt): keyboard.press(key.enter) keyboard.release(key.enter) else: keyboard.type(text)
from pynput import keyboard, mouse from pynput.keyboard import Key import time keyboard = keyboard.Controller() mouseC = mouse.Controller() wait = 0.1 mouseC.click(mouse.Button.left) for i in range(100): keyboard.type(str(i)) time.sleep(0.01) keyboard.press(Key.enter)