def temp(): pyautogui.alert('This displays some text with an OK button.') pyautogui.position() # current mouse x and y pyautogui.onScreen(x, y) # True if x & y are within the screen. pyautogui.PAUSE = 2.5 # Pause 2.5 s pyautogui.dragTo(x, y, duration=num_seconds) # drag mouse to XY pyautogui.dragRel(xOffset, yOffset, duration=num_seconds) # drag mouse relative to its current position pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left') # The button keyword argument can be 'left', 'middle', or 'right'. pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY) pyautogui.mouseDown(x=moveToX, y=moveToY, button='left') pyautogui.mouseUp(x=moveToX, y=moveToY, button='left') pyautogui.typewrite('Hello world!\n', interval=secs_between_keys) # useful for entering text, newline is Enter pyautogui.typewrite(['a', 'b', 'c', 'left', 'backspace', 'enter', 'f1'], interval=secs_between_keys) pyautogui.hotkey('ctrl', 'c') # ctrl-c to copy pyautogui.hotkey('ctrl', 'v') # ctrl-v to paste pyautogui.alert('This displays some text with an OK button.') pyautogui.confirm('This displays text and has an OK and Cancel button.') pyautogui.prompt('This lets the user type in a string and press OK.') pyautogui.screenshot('foo.png') # returns a Pillow/PIL Image object, and saves it to a file pyautogui.locateOnScreen('looksLikeThis.png') pyautogui.locateCenterOnScreen('looksLikeThis.png') # returns center x and y
def pytube_action(): # input url url_youtube = gui.prompt("Masukan URL Youtube") # jika inputan url dicancel if not url_youtube: exit(0) direktori = select_directory() # jika ada, setuju mengunduh ? setuju = gui.confirm("Yakin ingin mengunduh ?") if setuju.upper() == "OK": # jika setuju if direktori: if not direktori.endswith("/") : direktori += "/" unduh_video(url_youtube, direktori) #print(direktori) else: print("Terjadi Kesalan pada direktori") exit(0) else: exit(0)
def fti(): ti = pg.prompt('Enter interval time(in seconds):', 'AutoSS', '180') if ti == None: qu = pg.confirm('You want to exit?"', 'AutoSS', buttons=('Yes', 'No')) if qu == 'Yes': sys.exit(0) else: ti = pg.prompt('Enter interval time(in seconds):', 'AutoSS', '180') if ti == None: sys.exit(0) try: ti = int(ti) except: pg.alert('Input not recognized', 'AutoSS') sys.exit(0) return ti
def votacao_automatica(): webbrowser.open(pyautogui.prompt('Qual site vamos?')) time.sleep(6) if (pyautogui.confirm('Shall I proceed?').lower() != "ok"): return pyautogui.alert('Deixe o mouse no campo de comentarios') time.sleep(5) currentMouseX, currentMouseY = pyautogui.position() f = open("palavras", "r") for x in f: pyautogui.moveTo(currentMouseX, currentMouseY) pyautogui.click() pyautogui.typewrite(x) time.sleep(2) pyautogui.press('enter') time.sleep(5)
def atualizar_imagem(nome_img: str) -> bool: """Ulizado quando o RPA esta no modo manutenção para efetuar a troca das imagen que não foi encontrada Arguments: nome_img {str} -- [path absoluto do nome imagem para ser trocada] Raises: ImageNotFoundError: [Exception lançada quando a troca da img for cancelada] Returns: [bool] -- [retorna True se a imagem foi trocada, senão False] """ # Recupera apenas o nome da imagem sem dados da região para utilizar na capitura da nova imagem nome_without_path = nome_img.split('/')[-1].split('-')[0] # Abre a imagem a ser trocada para ser exibida pelo visualizador de imagens im = Image.open(nome_img) im.show() # Apresenta aviso de confirmação com nome do path absoluto da imagem que será trocada, option = pyautogui.confirm( title='RPAPY', text=f'A imagem "{nome_without_path}" será alterada!', buttons=['OK', 'CANCEL']) # Fecha janela do visualizador de imagem após confirmacao de troca fechar_visualizador_fotos('fotos') # Lança a exception caso a troca seja cancelada na caixa de confirmação if option is None or option == 'CANCEL': raise ImageNotFoundError( f'A imagem "{nome_without_path}", não foi encontrada!') # executa o método de capitura de imagem e verifica se a troca foi concluida # Se concluida, efetua a exclusão da antiga pelo nome original e retorna True # Se cancelada retorna False if capiturar_imagem(nome_without_path, trocar_img=True): # Recupera o objeto path com o nome original da imagem que foi trocada para ser apagado path = Path(nome_img) try: path.unlink() except FileNotFoundError: pass # Fecha o visualizador da nova imagem capiturada. fechar_visualizador_fotos('fotos') return True return False
def additional_homework_4(): """The points are bad and if the driver get 12 points, they get their driver's license suspended""" points = 0 while True: if points == 12: print("FBI OPEN UP!!!") break print("\nOver 70 MPH is over the speed limit") user_input = int(input("What speed are you driving at right now? ")) if user_input == 0: joke = pyautogui.confirm('Have you made it home?', buttons=["Yes", "No"]) if joke == "Yes": print("\nYou're safe...at least for now") if joke == "No": print( "\nJust stay there, I bet you that the police will come XD" ) break if user_input <= 70: print("Good, you are not over the speed limit") elif 80 >= user_input > 70: print("You're speeding! Plus 2 points!!!") points += 2 points_left = 12 - points print( f"Now you have {points} points!!!\nAnd you still have {points_left} points left!!!" ) elif 100 >= user_input > 80: print("Oh boi, the police is chasing you! plus 4 points!!!") points += 4 points_left = 12 - points print( f"You have {points} points now!!!\nAnd you still have {points_left} points left!!!" ) elif user_input > 100: print( "Bro, what are you playing?GTA 10 million? Why do you have to that fast???" ) print( "FBI OPEN UP!!!\nLOL that's just the police, plus 6 points LMAO" ) points += 6 points_left = 12 - points print( f"You have {points} points now!!!\nAnd you still have {points_left} points left!!!" )
def rename_code(path,path2): # path is image_sorce,path2 is wait label files= os.listdir(path) imgs = os.listdir(path2) files.sort(key=lambda x:int(x[:-4])) imgs.sort(key=lambda x:int(eval(x[:-4]))) start = 0 counter = 0 for a,j in enumerate(imgs): number = j.split('.') if len(number)==2: print(number) counter = eval(number[0]) start = a print(start) break imgs = imgs[start:] print(imgs[0]) for name in imgs: image = cv.imread(path2+'/'+name,0) source = cv.imread(path+'/'+files[int(counter/4)],0) cv.namedWindow(name, 0) cv.resizeWindow(name, image.shape[1]*4, image.shape[0]*4) cv.moveWindow(name,500,600) cv.imshow(name, image) cv.namedWindow('source', 0) cv.resizeWindow('source', source.shape[1]*6, source.shape[0]*6) cv.moveWindow('source',800,600) cv.imshow('source', source) text = pyautogui.confirm(text = 'confirm {}\nremain{}'.format(counter,1200-counter),title = 'number confirm',buttons=['0','1','2','3','4','5','6','7','8','9','Delete']) if text == 'Delete': os.remove(path2+'/'+name) elif text == None: break else: os.rename(path2+'/'+name,path2+'/'+'{}.{}.png'.format(counter,text)) cv.destroyAllWindows() counter +=1
def analyse(b): #分析 import re game = [ '4399小游戏', '4399.com', '游侠网', 'ali213.net', '3DMGAME', '3dmgame.com', '游民星空', 'gamersky.com' ] novel = ['起点中文网', 'qidian.com', '简书', 'jianshu.com', '笔趣阁', 'biquge.info'] video = [ '爱奇艺', 'iqiyi.com', '腾讯视频', 'v.qq.com', '哔哩哔哩', 'bilibili.com', '优酷网', 'youku.com' ] game0 = 0 novel0 = 0 video0 = 0 # 越多越智能,速度。。 for i in b: for j in game: if re.search(j, i) != None: game0 += 1 for j in novel: if re.search(j, i) != None: novel0 += 1 for j in video: if re.search(j, i) != None: video0 += 1 sz = [game0, novel0, video0] sz.sort(reverse=True) print(sz) zd = {'游戏': game0, '小说': novel0, '视频': video0} # todo key不能为同值 i = 0 while True: for k, v in sorted(zd.items()): if sz[i] == v: print(i) import pyautogui as ag b = ag.confirm('你想要找《' + k + '》,对吗?') key = k break if b == 'OK': break else: i += 1 del zd[key] return key #你的搜索类型
def start_scan_prompt(timeout_after: 'Timeout for prompt in sec' = 120, delay: 'Delay between next prompt in sec' = 3600): '''Prompt to start the scan''' delay_m = int(delay / 60) button = pyautogui.confirm( text='Do you want to start the auction house scan?', title='Auction House Scanner', buttons=['Start!', 'Delay ({}m)'.format(delay_m), 'Cancel'], timeout=(timeout_after * 1000)) if button == 'Delay ({}m)'.format(delay_m): time.sleep(delay) if start_scan_prompt(timeout_after, delay) == True: return True elif button == 'Cancel': sys.exit(0) elif button == 'Start!' or button == 'Timeout': return True
def store(date): dloc = "H:/AutoSS data/" loc = pg.confirm('{}\n\nConfirm saving location.'.format(dloc), 'AutoSS', buttons=('OK', 'NO')) if loc == 'OK': loc = dloc else: while loc in ['NO', None]: loc = pg.prompt('Enter new path:', 'Auto SS', "H:/AutoSS data/") try: path = loc + date os.mkdir(path) loc = path except: loc = loc + date return loc
def login(): """ Performs a login attempt. If successful, it returns an encryption key """ # Performs login inside a loop while True: inPassword = py.password(title="Input password", text="Please re-input your master password", mask="*") # Checks for exit if inPassword == None: return 0 # Reads in master hash and checks if inPassword is correct f = open(directory + "master.peapass", "r") masterHash = f.read() f.close() # Attempts to verify hash try: PasswordHasher().verify(masterHash, inPassword) break except: usrChoice = py.confirm(text='Could not verify password', title='Access denied', buttons=['Try again', 'Exit']) if usrChoice == 'Exit' or usrChoice == None: return 0 # Checks to see if rehash is needed if PasswordHasher().check_needs_rehash(masterHash): # Rehashes newHash = PasswordHasher().hash(inPassword) # Saves new hash f = open(directory + "master.peapass", "w+") f.write(newHash) f.close() key = passToKey(inPassword) return key
def main(): #{ # try the following try: #{ ## ASK USER THEIR DESIRED OPTION confirmStr = pyautogui.confirm( text='Yo whats good:', title='SQLite-Navigator', buttons=['In-Memory .db', 'Open Old .db', 'Create New .db']) if confirmStr == 'In-Memory .db': #{ ## Call in-memory launcher function in_memory_launcher() #} elif confirmStr == 'Open Old .db': #{ open_db_launcher() #} elif confirmStr == "Create New .db": #{ create_db_launcher() #} ############################################### ## LAUNCHER ## ## """ To use a SQLite :memory: database, specify an empty URL: engine = create_engine('sqlite://') """ ################################################ #} except: #{ errorMessage = str(sys.exc_info()[0]) + "\n" errorMessage = errorMessage + str(sys.exc_info()[1]) + "\n\t\t" errorMessage = errorMessage + str(sys.exc_info()[2]) + "\n" exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] typeE = str("TYPE : " + str(exc_type)) fileE = str("FILE : " + str(fname)) lineE = str("LINE : " + str(exc_tb.tb_lineno)) messageE = str("MESG : " + "\n\n" + str(errorMessage) + "\n") print("\n" + typeE + "\n" + fileE + "\n" + lineE + "\n" + messageE) #} else: #{ print("FIN...") #} return
def getMainScreen(): '''Trying to find game main screen and get to root game windows from where all actions is possible: ''' logging.info('Trying to recognize game screen...') star = locateOnScreen('star') if star: logging.info('found "star" icon - we are on the root screen') setGlobalXY(star) return else: shaded_star = locateOnScreen('shaded_star') if shaded_star: logging.info( 'found shaded star, main screen is shaded... some vk notify?') setGlobalXY(shaded_star) click('shaded_star') # we need to click some empty place, otherwise, there will appear popup # on 'star' and bot will not recognize 'star' image click('left_bottom_corner') if locateOnScreen('star'): logging.info('found "star" icon - we are on the root screen') return # if screen is shaded becouse of ingame window - this part will handle it for element in ['close_button', 'back_button']: if locateOnScreen(element): click(element) # sometimes there is two ingame windows, because of some achivements # so let's check twice getMainScreen() # if globalXY was set, maybe there is fight going? if WINDOW_X != 0: click('skip_fight') click('close_button') if locateOnScreen('star'): return logging.info('Could not find any game images :( \n asking user to help me') ask_user = pyautogui.confirm(''' Бот не может найти игру. Запустите пожалуйста окно с игрой. Попробовать еще раз?''') if ask_user == 'OK': getMainScreen() # running recursively else: raise Exception('Could not find game on screen. User aborted process.')
def removerMusica(): global listaNomes, lista, musica_e, z, fundo, cor_fundo_escolhida if musica_e == texto_inicial: pyautogui.alert(text='Não existe músicas na lista!', title='Aviso', button='OK') else: botao = pyautogui.confirm(text='Deseja remover \"' + musica_e + '\" da lista de músicas?', title='Remover', buttons=['SIM', 'NÃO']) if botao == 'SIM': s = 0 removida = 0 for i in range(len(lista)): if musica_e == lista[i]: s = i removida = musica_e lista.remove(musica_e) break listaNomes.remove(listaNomes[s]) fundo.fill(cor_fundo_escolhida) if len(lista) == 0: pygame.mixer.music.stop() salvarLista() pyautogui.alert(text='A música \"' + removida + '\" foi removida da lista!', title='', button='OK') musica_e = texto_inicial else: pygame.mixer.music.stop() pyautogui.alert(text='A música \"' + removida + '\" foi removida da lista!', title='', button='OK') musica_e = 'Música removida!' salvarLista() pyautogui.alert(text='Sua lista de músicas foi atualizada!', title='', button='OK') else: lista = lista listaNomes = listaNomes salvarLista()
def getMain(): pyautogui.hotkey('ctrl', 'c') sentence = pyperclip.paste() sentence = sentence.replace('\n', ' ') print(sentence) #这个是调用翻译接口 dataResult = translate.getOriginalResult(sentence) result = pyautogui.confirm(text=dataResult, title='变量翻译', buttons=['ok', '下划线', "首字母", "下划大写", "全小写"]) # print(result) if str(result).find("下划线") > -1: dataResult = spatial_variable_underline(dataResult) if str(result).find("首字母") > -1: dataResult = turn_the_space_into_capital_letters(dataResult) if str(result).find("下划大写") > -1: dataResult = spatial_variable_underline(dataResult, 1) pyperclip.copy(dataResult)
def expression_pack_query(objL): # strd = [] url = baseUrl + "emoticon" flag = True for infile in glob.glob(url + "\\*" + objL.strip() + "*"): flag = False os.system(infile) result = pyautogui.confirm(text="", title='快捷功能大全', buttons=['还要继续', "找到了"]) if result.find("找到了") > -1: flag = False break else: flag = True if flag: url = "http://www.dbbqb.com/s?w=" + objL.strip() os.startfile(url)
def handle_critical_errors(error_count, check_at_count=2): # Two or more critical errors may indicate a severe malfunctioning in the # program. This function displays a confirmation box asking the user if # they want to continue or stop the program after check_at_count critical # errors occurred. # # Arguments: # error_count - string - count of the critical errors. # check_at_count - int - check after check_at_count critical errors occurred. # # Returns: void # if error_count >= check_at_count: value = pgui.confirm("""2 or more critical errors have occurred. Would you like to continue (click "ok") or cancel?""") if value == 'Cancel': sys.exit()
def select_industy_one(self): """業種⓵を選択する関数""" industy_one = pg.confirm(text = "操作を終了したい場合は×を押してください", title = "業種欄①", buttons =[ "水産・農林業", "建設業", "食料品", "繊維製品", "パルプ・紙", "化学", "医薬品", "石油・石炭製品", "ゴム製品", "ガラス・土石製品", "業種欄②へ" ] ) return industy_one
def form(): form1 = confirm(text='Seleciona a Opção Abaixo', title='Camera RTSP VIEW', buttons=['Gravação Imagens', 'Apenas Visualizar']) if form1 == 'Gravação Imagens': ip = prompt(text='Digite o numero IP com porta EX: 192.168.0.13:554', title='Configuracoes de IP', default='192.168.0.13:554') acessos = prompt(text='Digite o Login e senha EX: login_admin:123456', title='Configuracoes de camera', default='admin:123123') login, senha = acessos.split(":") return [ip, login, senha] if form1 == 'Apenas Visualizar': ip = prompt(text='Digite o numero IP com porta EX: 192.168.0.13:5554', title='Configuracoes de IP', default='192.168.0.13:5554') return [ip]
def select_industy_two(self): """業種⓶を選択する関数""" industy_two = pg.confirm(text = "操作を終了したい場合は×を押してください", title = "業種欄②", buttons = [ "鉄鋼", "非鉄金属", "金属製品", "機械", "電気機器", "輸送用機器", "精密機器", "その他製品", "電気・ガス業", "陸運業", "業種欄③へ" ] ) return industy_two
def select_industy_three(self): """業種➂を選択する関数""" industy_three = pg.confirm(text = "操作を終了したい場合は×を押してください", title = "業種欄③", buttons = [ "海運業", "倉庫・運輸関連業", "卸売業", "小売業", "銀行業", "証券、商品先物取引業", "保険業", "その他金融業", "不動産業", "サービス業", "情報・通信業" ] ) return industy_three
def start(): try: print('请在倒计时内选中需要保持活动的窗口') for i in range(settings.COUNTDOWN): print(settings.COUNTDOWN - i) time.sleep(1) print('移动鼠标到屏幕边角以退出程序') while True: try: key = random.choice(['up', 'down']) print('Press', key) pyautogui.press(key) except FailSafeException: print('Show confirm box') if pyautogui.confirm(text='Are you sure you want to exit?', title='Confirm Exit', buttons=['Keep Working!', 'Exit']) == 'Exit': print('Quit by FailSafeCheck') break except KeyboardInterrupt: print('Quit by KeyboardInterrupt')
def additional_homework_3(): user_input = int(input("Enter any number: ")) if user_input == 0: print("Hello, you aren't suppose to see this so get our right now or else I'm calling in the FBI") joke = pyautogui.confirm('Should I call the FBI on you?', buttons=["Yes", "No"]) if joke == "Yes": print("FBI! Open up!!!") else: print("LOL, did you think that I'm going to call the FBI on you?") else: """This is the part where we tell if its divisible by 3 or 5 or nothing or both""" if user_input % 5 == 0 and user_input % 3 == 0: print(f"The number {user_input} is divisible by 3 and 5!!!") if user_input % 3 == 0 or user_input % 5 == 0: if user_input % 3 == 0: print(f"The number that you entered ({user_input}) is divisible by 3!!!") if user_input % 5 == 0: print(f"The number that you entered ({user_input}) is divisible by 5!!!") else: print(f"The number that you entered ({user_input}) isn't divisible by 3 or 5!!!")
def reload(self): ans = pyautogui.confirm("Delete current template HTML files and reload original template HTML files from TEMPLATE_BACKUP_ZIP?") if ans == "OK": for file in self.var.TEMPLATE_FILES: filename, ext = os.path.splitext(file) if ext == ".html": try: os.remove(file) except Exception, e: print e else: print "There are no html files in your templates folder!" with zipfile.ZipFile(self.var.TEMPLATE_BACKUP_ZIP, "r") as z: z.extractall(self.var.TEMPLATE_FOLDER) try: shutil.rmtree(os.path.join(self.var.TEMPLATE_FOLDER,"__MACOSX")) except: pass
def upload_robot(): from rpapy.core.utils.example import paint_robot text = f'***ATENÇÃO***\n\nAlguns arquivos poderão ser substituidos!\nVocê deseja carregar a implementação de exemplo do robo-rpapy?' opcao = pyautogui.confirm(text=text, title='RPA-PY', buttons=['OK', 'CANCEL']) if opcao is None or opcao == 'CANCEL': return pyautogui.alert( title='ATENÇÃO!', text= 'Após terminar de carregar os arquivos, execute\no seguinte comando no terminal:\n\nrobot -d log tasks' ) create_example_default_dirs() create_robot_default_dirs() # The directory containing this file HERE = os.path.abspath(os.path.dirname(__file__)) path_desenho_robotframework = Path( Config.BASE_DIR, 'resources/desenhos/robotframework.txt') create_file_confirm(path_desenho_robotframework, paint_robot.ROBOTFRAMEWORK) path_desenho_borboleta = Path(Config.BASE_DIR, 'resources/desenhos/borboleta.txt') create_file_confirm(path_desenho_borboleta, paint_robot.BORBOLETA) path_custom_keywords = Path(Config.BASE_DIR, 'resources/custom_keywords.py') create_file_confirm(path_custom_keywords, paint_robot.CUSTOM_KEYWORDS) path_keywords = Path(Config.BASE_DIR, 'resources/keywords.robot') create_file_confirm(path_keywords, paint_robot.KEYWORDS_ROBOT) path_main_robot = Path(Config.BASE_DIR, 'tasks/main.robot') create_file_confirm(path_main_robot, paint_robot.MAIN_ROBOT)
def test_calibration(self, width_height=None, show_switch_prompt=False): """ A method to non invasively test whether the app calibrations are correct on the current platform and if it is safe to use ``spammer`` with these calibrations or not. Usage: The mouse cursor hovers over the area which is expected to be a textbox for inputing text. User needs to validate the calibrations and accept them for saving OR user may opt to abort and recalibrate later. """ # Check if the message file exists for the web-app file_ = Path.joinpath(self.base_path, '..', 'messages', self.msg_file) assert os.path.exists(file_) and os.path.isfile(file_), ( f'Message file {self.msg_file}, does not exist.') # Check if text-box is calibrated properly width, height = width_height or self.get_caliberation_config() prompt_message = ( 'Hello, %sOnce you press \'OK\' the mouse cursor will automatically ' 'hover over the screen where a textbox is expected to be.') if show_switch_prompt: prompt_message = prompt_message % ( f'before you press \'OK\', switch to {self.app_name.title()} and ' 'make sure a contact is selected.\n\n') else: prompt_message = prompt_message % ('') gui.alert(prompt_message) time.sleep(1) # Hover over expected area for _ in range(4): gui.moveTo(width + 10, height, 0.3) gui.moveTo(width, height, 0.3) accept = gui.confirm( 'Press \'OK\' if the cursor was correctly positioned over textbox, ' 'or press \'Cancel\' to exit') assert 'Cancel' not in accept, ( 'Caliberation Test Failed ! Please re-calibrate the web app.') click.echo('Caliberation test complete.')
def UBQask(self): self.UBQtodo = 0 test = True while test: ubqs = pyautogui.prompt(text='How many UBQs?') if ubqs is None: test = False break try: self.UBQtodo = int(ubqs) test = False except ValueError: pyautogui.alert(text="Not a number") self.UBQgivers = int( pyautogui.confirm(text='How many quest givers?', buttons=['1', '2', '3'])) if self.UBQgivers == 2: pyautogui.alert(test='2 givers not actually supported...yet...')
def start(self): try: answer = pyautogui.confirm('Server will start on :: ' + self.ip, "FTP Server", ("Start", "Stop")) if answer == "Start": self.log_generator() try: self.changes_cheker.start() except Exception as e: print(e, ":: Starting Thread") authorizer = DummyAuthorizer() authorizer.add_user('EWTSS_FTP_USER', 'EWTSS', '.') handler = FTPHandler handler.authorizer = authorizer self.server = ThreadedFTPServer((self.ip, self.port), handler) self.server.serve_forever() except Exception as e: pyautogui.alert(text=str(e), title=str(type(e).__name__), button='Exit')
def run(self): self.compare_log_file() answer = 'Later' file_count = len(self.diff_list) if file_count > 0: answer = pyautogui.confirm('Some Updates found. Do you want to update now?', "System Update", ("Now", "Later")) if answer == 'Now': file_no = 1 self.bar(1) for url in self.diff_list: print(url) bar_value = (file_no / file_count) * 100 self.mssg_val.set(str(file_no) + " / " + str(file_count)) try: self.download_from_ftp(self.return_ulr_from_log(url)) file_no = file_no+1 self.bar(bar_value) except Exception as e: print(e, url) pass
def databaseOptions(): """ Starts database options branch """ # Gets mode from user mode = py.confirm(text='What would you like to do?', title='PeaPass', buttons=['Delete database', 'Cancel']) exitCode = 1 # Calls respective modes if mode == 'Delete database': exitCode = deleteDatabase() if mode == 'Export database': #exitCode = exportDatabase() pass return exitCode
def initcalib(colourt): Qx, Qy = pgui.position() check = calibrate(colourt) duf = '' if 10 <= check < 20: if check == 10: pgui.alert(text='Unkown reference!\nCheck settings.', title='ERROR') return 0 elif check == 11: duf = ( "No GUI found! Use normal sized base menu bar and status bar graphics.\n" "Use the resolutions given in the settings.\n" "640x480 and 720x480 higher supported.") elif check == 12: pgui.alert(text='No marker found!\nMove map or mouse.', title='ERROR') return 0 elif check == 13: duf = 'Mouse in marker not found!' elif 20 <= check < 30: if check == 20: return 1 else: pgui.alert( text= 'WHAT DID YOU DO TO MAKE THIS HAPPEN? DO YOU KNOW HOW LONG I SPENT DEBUGGING THIS AND CATCHING ALL THE DIFFERENT ERRORS.\n' 'Well done you found a bug. Are you happy now?', title='Do you feel proud? Calibrator unkown ERROR', button='Collect my prize') return 0 if pgui.confirm(text=('Error calibrating: ' + duf + '\nRetry?'), title='ERROR') == 'OK': pgui.moveTo(Qx, Qy) return 2 else: return 0
def main() -> int: print('pesmaster.yaml read - start') yamlutils.load("resource/pesmaster.yaml", yaml_load_success) # if not stringutils.is_not_blank([CHROME_REMOTE_DEBUGGING_PORT, CHEAT_ENGINE_KEY_DELAY, CHEAT_ENGINE_WINDOW_TITLE, # CHEAT_ENGINE_WINDOW_INDEX]): if not stringutils.is_not_blank([CHROME_REMOTE_DEBUGGING_PORT]): print('pesmaster.yaml read - error') return 1 print("pesmaster.yaml read - CHROME_REMOTE_DEBUGGING_PORT: " + str(CHROME_REMOTE_DEBUGGING_PORT)) # print("pesmaster.yaml read - CHEAT_ENGINE_KEY_DELAY: " + str(CHEAT_ENGINE_KEY_DELAY)) # print("pesmaster.yaml read - CHEAT_ENGINE_WINDOW_TITLE: " + CHEAT_ENGINE_WINDOW_TITLE) # print("pesmaster.yaml read - CHEAT_ENGINE_WINDOW_INDEX: " + str(CHEAT_ENGINE_WINDOW_INDEX)) print('pesmaster.yaml read - end') while 'OK' == pyautogui.confirm(text="확인 선택시 crawling; 취소 선택시 종료", title="알림"): requestutils.do(CHROME_REMOTE_DEBUGGING_PORT, "resource/chromedriver", request_success, (lambda exception: print( 'pesmaster 2021 player crawl - error: ' + exception .__name__ + ' / ' + str(sys.exc_info())))) return 0