def qbittorrent_startup(): os.startfile(r"C:\Program Files\qBittorrent\qbittorrent.exe") while True: if pog.getWindowsWithTitle('qBittorrent'): pog.getWindowsWithTitle('qBittorrent')[0].close() break sleep(0.2)
def multify(img_file): target = pyautogui.locateAllOnScreen(img_file, confidence=0.7) if target: for i in target: pyautogui.click(i, duration=0.25) for x in range(0, 3): obs = pyautogui.getWindowsWithTitle("OBS")[0] pyautogui.sleep(2) obs.activate() pyautogui.sleep(2) my_click("recordstart.png", 10) pyautogui.sleep(2) obs.minimize() pyautogui.sleep(2) it = pyautogui.getWindowsWithTitle("아이티 버팀목")[0] pyautogui.sleep(1) it.maximize() pyautogui.sleep(2) class_max = pyautogui.locateOnScreen( "수업화면최대화.png", region=(881, 905, 908 - 881, 928 - 905), confidence=0.7) # 비디오 플랫폼 클릭 못하고 있음 pyautogui.click(class_max) break else: print("이미지 찾기 실패") sys.exit()
def run_mouse_click(click_point): # Move to window of concern pyautogui.getWindowsWithTitle(args.get_window_title())[0].activate() # Move mouse to point of click pyautogui.moveTo(click_point.x(), click_point.y()) # Click in coordinates location pyautogui.click()
def initialWindow(): pyautogui.FAILSAFE = True pyautogui.PAUSE = interval window = pyautogui.getWindowsWithTitle("KinApp") if window: window[0].moveTo(155, 54) window = pyautogui.getWindowsWithTitle("ScreenToGif") if window: window[0].moveTo(156, 23)
def qbittorrent_download(path): while True: if pog.getWindowsWithTitle( '[HorribleSubs]') or pog.getWindowsWithTitle('[Erai-Raws]'): break sleep(0.2) pog.press(['\t', '\t', '\t', '\t']) pog.typewrite( path) # enter path where you want to store the downloaded episode sleep(0.5) pog.press(['\t', '\t', '\t', '\t', '\t', '\t', '\t', 'space', 'enter']) sleep(1)
def is_exsist(n, img_file_nm): ''' 이미지에 해당하는 영역이 화면에 있는지 여부 :param n: :param img_file_nm: :return: ''' pg.getWindowsWithTitle("대항해시대 온라인")[n].activate() sleep(0.2) b_dep = pg.locateOnScreen(img_file_nm, grayscale=True, confidence=0.9) if b_dep != None: # print(b_dep) return True else: return False
def WindowMessageChanged(info=1, retry=20, showLater=True): window = pyautogui.getWindowsWithTitle("KinApp")[0] xl, yb = window.bottomleft xr, yb = window.bottomright xr = xr - xl # TODO get messagebar picture before convert and wait for change # but someother operation will show directly becall this function is called, which 'showLater'=False # if(showLater): # pyautogui.screenshot('test\\compareOnly.png', region=(xl, yb - 40, xr, 40)) for times in range(0, retry): if (info == 1): find = pyautogui.locateOnScreen(PathConvert('success.png'), region=(xl, yb - 40, xr, 40)) elif (info == 2): find = pyautogui.locateOnScreen(PathConvert('warn.png'), region=(xl, yb - 40, xr, 40)) elif (info == 3): find = pyautogui.locateOnScreen(PathConvert("error.png"), region=(xl, yb - 40, xr, 40)) else: return False if (find is None): time.sleep(0.4) else: return True return False
def sendwhatmsg_instantly(phone_no: str, message: str, wait_time: int = 20, browser: str = None, tab_close: bool = False) -> NoReturn: """Send WhatsApp Message Instantly""" if browser and browser.lower() not in [ "chrome", "firefox", "brave", "opera" ]: raise InvalidBrowserName( "Browser name can be firefox, chrome, brave, opera") if "+" not in phone_no: raise CountryCodeException("Country code missing from phone_no") parsed_message = quote(message) web.open('https://web.whatsapp.com/send?phone=' + phone_no + '&text=' + parsed_message) time.sleep(2) width, height = pg.size() if browser: whats = pg.getWindowsWithTitle(browser)[0] whats.maximize() whats.activate() pg.click(width / 2, height / 2) time.sleep(wait_time - 2) pg.press('enter') if tab_close: close_tab()
def text_ocr(profile): # print(pyautogui.getAllTitles()) win_list = pyautogui.getWindowsWithTitle(profile['title']) if len(win_list) != 1: print('window not unique') for win in win_list: print(win.title) return -1 for win in win_list: win.activate() time.sleep(0.1) for area in profile['sub_area']: print(f'----- {area} -----') pic = pyautogui.screenshot(region=(win.left, win.top, win.width, win.height)) pic = pic.crop(area) # threshold pic = pic.point(lambda p: p > profile['threshold'] and 255) # Tesseract works best on images which have a DPI of at least 300 dpi for resize in range(5): size = round(resize * 0.1 + profile['resize'], 2) print(f'----- {size} -----') new_width = int(pic.width * size) new_height = int(pic.height * size) temp = pic.resize((new_width, new_height), Image.ANTIALIAS) # temp.save(f'z:/tmp/ocr/{area}_{size}.jpg') # temp.save(f'z:/tmp/ocr/{size}.jpg') pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe' config = r'--psm 3' # config = r'--psm 6' text = pytesseract.image_to_string(temp, lang='jpn', config=config) print(f'{text}\n')
def train(epoch=1, batch=8, steps=1): rewards = [] losses = 0 total_wins = 0 for i in range(epoch): wind = pyautogui.getWindowsWithTitle("snes9x")[0] if i % 5 == 0: #activation of the computer every 5 iterations try: wind.activate() except: pass states, cum_rewards, next_states, dones, actions = make_batches( env, batch=batch, steps=1, gamma=0.95) rewards.append(cum_rewards.sum() / 8) if (cum_rewards.sum() / 8) > 30: print("i breaked in epoch: {}".format(i)) break print("total reward per episode : {}".format(rewards[i]), "\n epoch:", i) _, values = Net(states) values = values.numpy().squeeze() adva = cum_rewards - values combined = tf.stack((adva, actions), axis=1) Net.fit(states, [combined, cum_rewards], epochs=1, callbacks=model_checkpoint_callback)
def activate_window(mode, delay=0.05): """ Parameters ---------- mode : "tibia" delay : Delay between actions. The default is 0.5. Returns ------- None. """ logging.debug("Function activate_window() called with passed: %s.", mode) logging.info("Current active window: %s", GetWindowText(GetForegroundWindow())) if mode == "tibia": window = pyautogui.getWindowsWithTitle("Kasteria - Tibijka")[0] window_text = "Kasteria - Tibijka" if GetWindowText(GetForegroundWindow()) != window_text: logging.info( "active window != desired window, window activation goes on") window.minimize() time.sleep(delay) window.restore() window.activate() time.sleep(delay) logging.info("Current active window: %s", GetWindowText(GetForegroundWindow())) logging.debug("Function activate_window end.")
def _test_TC_PM_002(self): """ Update ava profile with IMG file """ self.driver.get("https://www.vietnamworks.com/my-profile") WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(( By.XPATH,"//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[1]/div/div"))).click() delay(0.5) window = pyautogui.getWindowsWithTitle(self.driver.title)[0] window.maximize window.center delay(1) ava_file1 = os.path.join(self.input_files_path, "image.jpg") pyautogui.write(ava_file1) delay(0.5) pyautogui.press('enter') delay(1) ava_update_warining = "ok" try: ava_update_warining = self.driver.find_element_by_xpath("//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[1]/div/div[3]") except: "" delay(1) actual = False if ava_update_warining == "ok": self.driver.find_element_by_xpath("/html/body/div[3]/div/div[3]/button[2]").click() actual = True else: "Failed" expect = True result = True if (actual == expect) else False self.assertTrue(TestUtil.checkTestcase(result,True,"TC-PM-002"))
def _resize_window_win11(self): windows = pyautogui.getWindowsWithTitle("RuneLite") SCREEN_WIDTH = 1920 SCREEN_HEIGHT = 1080 ''' -1920,0 -1,0 -1920,1079 -1,1079 ''' x_offset = -1920 screen_pos = [ (0+x_offset, 0), ((SCREEN_WIDTH//2)+x_offset, 0), (0+x_offset, SCREEN_HEIGHT//2), ((SCREEN_WIDTH//2)+x_offset, SCREEN_HEIGHT//2), ] for i in range(len(windows)): window = windows[i] window.resizeTo(SCREEN_WIDTH//2, SCREEN_HEIGHT//2) pos = screen_pos[i] window.moveTo(pos[0], pos[1]) print(f'giving window {i} pos:{pos}')
def run_screencapture_loop(): candidate_windows = pyautogui.getWindowsWithTitle("Among Us") if len(candidate_windows) == 0: exit("ERROR: no window with 'Among Us' title found") game_window = candidate_windows[0] # axis = pyplot.axes() # pyplot.ion() # pyplot.show(block=False) i = 0 while (True): if not game_window.isActive: game_window.activate() pyplot.pause(0.1) window_region = (game_window.left + 10, game_window.top + 32, game_window.width - 20, game_window.height - 42) print(window_region) image = pyautogui.screenshot(region=window_region, imageFilename="screenshot_" + str(i) + ".png") i = i + 1 print(image.size) # axis.imshow(image) # pyplot.draw() pyplot.pause(0.05)
def sendwhatmsg_instantly(phone_no, message, wait_time=20, browser=None) -> None: '''Sends whatsapp message to a particulal number instantly Phone number should be in string format not int ***This function will not work if the browser's window is minimised, first check it by calling 'check_window()' function''' if browser and browser.lower() not in [ "chrome", "firefox", "brave", "opera" ]: raise InvalidBrowserName( "Browser name can be firefox, chrome, brave, opera") if "+" not in phone_no: raise CountryCodeException("Country code missing from phone_no") parsedMessage = quote(message) web.open('https://web.whatsapp.com/send?phone=' + phone_no + '&text=' + parsedMessage) time.sleep(2) width, height = pg.size() if browser: whats = pg.getWindowsWithTitle(browser)[0] whats.maximize() whats.activate() pg.click(width / 2, height / 2) time.sleep(wait_time - 2) pg.press('enter')
def click_area(n, img_file_nm): sleep(1) pg.getWindowsWithTitle("대항해시대 온라인")[n].activate() sleep(0.5) b_dep = pg.locateOnScreen(img_file_nm, grayscale=True, confidence=0.8) if b_dep != None: print(n, img_file_nm, 'can search', b_dep, type(b_dep.left)) c = pg.center(b_dep) print('center:', c) sleep(0.5) click(int(c.x), int(c.y)) print(pg.position()) return 0 else: print(img_file_nm, 'cannot search') return 1
def _getPosteRazorWindow(): # Find the PosteRazor window. posterazorWindows = [ title for title in pyautogui.getAllTitles() if title.startswith('PosteRazor ') ] if len(posterazorWindows) == 0: logging.error( 'Could not find the window for PosteRazor. Please run PosteRazor.') raise PosteRazorAPIException( 'Could not find the window for PosteRazor. Please run PosteRazor.') elif len(posterazorWindows) > 1: logging.error( '%s instances of PosteRazor found. Please run only one instance of PosteRazor.' % (len(posterazorWindows))) raise PosteRazorAPIException( '%s instances of PosteRazor found. Please run only one instance of PosteRazor.' % (len(posterazorWindows))) postWin = pyautogui.getWindowsWithTitle(posterazorWindows[0])[0] # Resize and focus the window. postWin.resizeTo(1, 1) # Set the size of PosteRazor to its smallest size. postWin.activate() return postWin
def _new_mode(self): for transaction in gui.getAllTitles(): if transaction.startswith('ZLPC'): continue elif transaction.startswith(titles_tuple): temp_transaction = gui.getWindowsWithTitle(str(transaction))[0] temp_transaction.activate() print(temp_transaction) hotkey(transaction_names['new_mode'], (410, 30, 575, 60), 'ctrl', 'n') while gui.getActiveWindowTitle == temp_transaction: print(gui.getActiveWindowTitle) gui.sleep(0.25) print('test') if 'Information' in gui.getAllTitles(): dialog = gui.confirm(text='Много окошек. Закрываю одно', title='Limit of tabs', buttons=['OK', 'Cancel']) if dialog == 'OK': information = gw.getWindowsWithTitle('Information')[ 0] # ЗАКРЫВАЕТ ВСЕ ОКНА print(information) gui.press('esc') print(temp_transaction) temp_transaction.close() continue else: exit() elif gui.locateOnScreen(transaction_names['sap_easy_access'], region=names_region): break
def sendwhatmsg_to_group(group_id, message, time_hour, time_min, wait_time=20, print_waitTime=True): """Schedule message to be sent in a group Group ID is something that is in its invite linek, https://chat.whatsapp.com/AB123CDEFGHijklmn, here AB123CDEFGHijklmn is group ID""" if time_hour not in range(0, 25) or time_min not in range(0, 60): print("Invalid time format") timehr = time_hour if time_hour == 0: time_hour = 24 callsec = (time_hour * 3600) + (time_min * 60) curr = time.localtime() currhr = curr.tm_hour currmin = curr.tm_min currsec = curr.tm_sec if currhr == 0: currhr = 24 currtotsec = (currhr * 3600) + (currmin * 60) + (currsec) lefttm = callsec - currtotsec if lefttm <= 0: lefttm = 86400 + lefttm if lefttm < wait_time: raise CallTimeException( "Call time must be greater than wait_time as web.whatsapp.com takes some time to load" ) date = "%s:%s:%s" % (curr.tm_mday, curr.tm_mon, curr.tm_year) time_write = "%s:%s" % (timehr, time_min) file = open("pywhatkit_dbs.txt", "a", encoding='utf-8') file.write("Date: %s\nTime: %s\nGroup_id: %s\nMessage: %s" % (date, time_write, group_id, message)) file.write("\n--------------------\n") file.close() sleeptm = lefttm - wait_time if print_waitTime: print( f"In {sleeptm} seconds web.whatsapp.com will open and after {wait_time} seconds message will be delivered" ) time.sleep(sleeptm) web.open('https://web.whatsapp.com/accept?code=' + group_id) time.sleep(2) width, height = pg.size() whats = pg.getWindowsWithTitle("WhatsApp")[0] whats.maximize() whats.activate() time.sleep(wait_time - 2) pg.click(width / 2, height - height / 10) pg.typewrite(message + "\n")
def fucti(): subprocess.call('C:\\Users\\jainh\\AppData\\Roaming\\Zoom\\bin\\Zoom.exe') pyautogui.getWindowsWithTitle("Zoom")[0].maximize() clickjoin = pyautogui.locateCenterOnScreen('joinIMG.png', confidence=0.4) pyautogui.moveTo(clickjoin) pyautogui.click() pyautogui.press('enter', interval=5) pyautogui.write(str(Meet_id)) pyautogui.press('tab', presses=2) pyautogui.hotkey('ctrl', 'a') pyautogui.write(name) pyautogui.press('enter', interval=10) pyautogui.write(str(Meet_pass)) pyautogui.press('enter', interval=10)
def launch_zoom(path_home): zoom = get_zoom(pyautogui.getWindowsWithTitle("Zoom")) if (zoom): zoom.activate() return zoom else: zoom_path = path_home + r'\AppData\Roaming\Zoom\bin\Zoom.exe' return subprocess.Popen(zoom_path, stdout=subprocess.PIPE)
def individua_finestre(self): '''Trova e ritorna una lista contenente le finestre che ci interessa sistemare''' lista_finestre = [] for denominazione in ['CARB', 'BTRB']: lista_tmp = pyautogui.getWindowsWithTitle(denominazione) lista_finestre += lista_tmp return lista_finestre
def place_window(): """Find the window, raise it, size it and move it""" browser_window: pg.Window [browser_window] = pg.getWindowsWithTitle(WINDOW_TITLE) x, y = WINDOW_POS_OFFSET cx, cy = EXTRA_POS_OFFSET browser_window.moveTo(x + cx, y + cy) browser_window.resizeTo(newWidth=835, newHeight=820) browser_window.activate()
def fechar_visualizador_fotos(title: str): """Fecha a janela do visualizador de imagem do windows Arguments: title {str} -- Nome ou parte do nome do titulo da janela do visualizador de imagens """ visualizadores_fotos = pyautogui.getWindowsWithTitle(title) for v in visualizadores_fotos: v.close()
def capture_screen(): win = getWindowsWithTitle('dosbox 0.7')[0] try: win.activate() except: pass img = np.array(pyscreeze._screenshot_win32(region=win.box)) img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) return img
def activeWindow(self): if self.__win is None: wins = pyautogui.getWindowsWithTitle(self.window_title) if len(wins) > 0: self.__win = wins[0] if self.__win is not None: self.__win.restore() self.__win.activate()
def open_gwent(): if len(pyautogui.getWindowsWithTitle('Gwent')) == 0: press('winleft') typewrite('gwent') press('enter') sleep(OPEN_GWENT_WAIT_TIME) switch_windows() ingame_click(x=960, y=1020, clicks=OPEN_GWENT_ENTER_PRESS, intervals=0.7) ingame_click(x=900, y=600) return 'open'
def getText(): windows = pyautogui.getWindowsWithTitle('Notepad++') for window in windows: window.activate() pyautogui.click(window.left + 200, window.top + 200) pyautogui.hotkey('ctrl', 'a') pyautogui.hotkey('ctrl', 'c') time.sleep(5) text = pyperclip.paste() print(text)
def get_win_hwnd(title, funcNum=1): func = [startWith, equalStr, endsWith, findStr][funcNum] try: w = pyautogui.getWindowsWithTitle(title) for i in w: if func(i.title, title): return i return None except Exception as e: return None
def get_dev_tools_window(browserWindow): allDevToolWindows = [] while (len(allDevToolWindows) < 1): browserWindow.show() pag.press("f12") time.sleep(2 + PARAMETER_SLOWNESS_SECONDS) allDevToolWindows = pag.getWindowsWithTitle("DevTools - ") return allDevToolWindows[0]