Пример #1
0
class WindowInteraction:
    """ low level key pressing interface with xflr windows """
    def __init__(self, app_load_time: int = 2):
        self.ahk = AHK(
            executable_path=
            r'C:\Users\olive\Documents\GitHub\pyxfl\ahk\AutoHotkeyU64.exe')
        self.ahk.run_script('Run, xflr/xflr5.exe')
        time.sleep(app_load_time)
        self.win = self.ahk.find_window(title=b'xflr')

    def field_selector(self, index: int):
        self.win.activate()
        for _ in range(index):
            self.win.send("{Tab}")

    def get_window(self, title: str):
        return self.ahk.find_window(title=title)

    def ctrl_press(self, key: str):
        self.win.activate()
        self.win.send(f"^{key}")

    def press(self, key: str):
        self.win.activate()
        self.win.send(f"{key}")

    def check_window_exists(self, name: str):
        return True if name in [window.title
                                for window in self.ahk.windows()] else False
Пример #2
0
class WindowInteraction:
    """ low level key pressing interface with xflr windows """

    def __init__(self, app_load_time : int = 2):
        self.ahk = AHK(executable_path = r'ahk\AutoHotkeyU64.exe')
        self.ahk.run_script('Run, xflr/xflr5.exe')
        time.sleep(app_load_time)
        self.win = self.ahk.find_window(title=b'xflr')

    """
    Public methods
    """

    def reset_window(self):
        self.win = self.ahk.find_window(title=b'xflr')
    

    def field_selector(self, index : int, window = None):
        logging.info(f"selecting index: {index}")
        wing_edit = self.ahk.find_window_by_title(b'Wing Edition - xflr5 v6.47')
        if window == None:
            window = self.win
        for _ in range(index):
            time.sleep(0.01)
            #wing_edit.send("{Tab}")
            self.press(r'{Tab}', wing_edit)


    def get_window(self, title : str):
        return self.ahk.find_window_by_title(title)
    

    def list_windows(self):
        return [window.title for window in self.ahk.windows()]
    

    def ctrl_press(self, key : str):
        self.press(f"^{key}")


    def press(self, key : str, window = None):
        
        self.list_windows()

        if window == None:
            window = self.win
        window.activate()
        logging.info(key)
        window.send(f"{key}")
    

    def check_window_exists(self, name : str):
        return True if name in [window.title for window in self.ahk.windows()] else False
Пример #3
0
def api_init():
    """Grab both engine and console windows. Thanks to run for this code"""
    global CONSOLE
    global WINDOW

    if environ["DEVELOPMENT"]:
        CONSOLE = AHK.run_script("WinShow," + CONSOLEWINDOW + \
                   "\nControlGet, console, Hwnd ,, Edit1, " + CONSOLEWINDOW + \
                   "\nFileAppend, %console%, * ;", blocking=True)
    else:
        CONSOLE = AHK.run_script("WinShow," + CONSOLEWINDOW + \
                    "\nControlGet, console, Hwnd ,, Edit1, " + CONSOLEWINDOW + \
                    "\nWinHide," + CONSOLEWINDOW + \
                    "\nFileAppend, %console%, * ;", blocking=True)
    WINDOW = AHK.find_window(process=config.DF_EXE_PATH,
                             title=b"TwitchBot Engine")

    if CONSOLE is None or WINDOW is None:
        raise WindowNotFoundError
Пример #4
0
class Holder:
    def __init__(self, yaml):
        self.ahk = AHK()
        self.options = yaml
        self.delay = self.options['delay']
        self.get_window()

    def get_window(self):
        self.window = self.ahk.find_window(title=b'Minecraft',
                                           process='javaw.exe')
        # print(self.window.title)
        self.crossbow()

    def crossbow(self):
        while True:
            # print('Sending RButton down')
            self.ahk.run_script('ControlClick, , ' +
                                self.window.title.decode() + ', ,Right, , NAD')
            time.sleep(float(self.options['draw_time']))
            # print('Sending RButton up')
            self.ahk.run_script('ControlClick, , ' +
                                self.window.title.decode() + ', ,Right, , NAU')
            time.sleep(0.2)
            # print('Sending RButton')
            self.ahk.run_script('ControlClick, , ' +
                                self.window.title.decode() + ', ,Right, , NA')
            # print(f'Waiting for {self.delay}s')
            time.sleep(float(self.delay))
Пример #5
0
class BlobEnv:
    SIZE = 10
    RETURN_IMAGES = True
    MOVE_PENALTY = 1
    ENEMY_PENALTY = 300
    FOOD_REWARD = 25
    OBSERVATION_SPACE_VALUES = (SIZE, SIZE, 3)  # 4
    ACTION_SPACE_SIZE = 4
    PLAYER_N = 1  # player key in dict
    FOOD_N = 2  # food key in dict
    ENEMY_N = 3  # enemy key in dict
    # the dict! (colors)
    d = {1: (255, 175, 0),
         2: (0, 255, 0),
         3: (0, 0, 255)}

    def __init__(self):
        self.ahk = AHK()
        self.location_memory = set()
        self.episode_step = 0

    def reset(self):
        self.episode_step = 0
        self.location_memory = set()
        self.ahk.run_script(open('ahk_scripts/get_state.ahk').read())
        pos_x = open('states/AX.txt').read()
        pos_y = open('states/AY.txt').read()
        observation = (float(pos_x), float(pos_y))
        map = open('states/AMap.txt').read()
        print('Current map id:', map)
        self.location_memory.add(observation)
        self.ahk.run_script(open('ahk_scripts/reset.ahk').read())
        return observation

    def step(self, current_state, action):
        self.episode_step += 1
        self.ahk.run_script(f'action := {action}\n' + open('ahk_scripts/step.ahk').read())
        pos_x = open('states/BX.txt').read()
        pos_y = open('states/BY.txt').read()
        new_observation = (float(pos_x), float(pos_y))
        map_id = int(open('states/BMap.txt').read())
        print('Map id after action:', map_id)
        if map_id == 25 or self.episode_step >= 200:
            reward = 0
            done = True
        elif new_observation == current_state:
            reward = -1.0
            done = False
        elif new_observation not in self.location_memory:
            reward = 0.3
            self.location_memory.add(new_observation)
            done = False
        else:
            done = False
            reward = -0.2

        return new_observation, reward, done
Пример #6
0
            def test_buscar(self):
                driver = self.driver
                if sistemaEntrada == 1:
                    driver.get("https://pjes.jfpb.jus.br")
                else:
                    driver.get("https://pje.jfpb.jus.br/pje/login.seam")

                window_before = driver.window_handles[0]
                print(driver.title)
                ahk = AHK(executable_path=caminho_ahk)

                window_before_title = driver.title
                print(">>>>>>><<<<<<<<<")

                print(window_before_title)

                time.sleep(10)

                if sistemaEntrada == 1:
                    # 1ª PASSO: ABRIR PJE, SELECIONAR AUTENTICAÇÃO JAVA E FECHAR JANELA POSTERIOR
                    driver.find_elements_by_xpath(
                        '//*[@id="btnUtilizarApplet"]')[0].click()
                    time.sleep(5)

                    driver.find_elements_by_xpath(
                        '//*[@id="panelAmbienteContentDiv"]/div/img')[0].click(
                        )
                    # 2ª PASSO: FAZER O LOGIN E CLICAR NO BOTÃO ENTRAR
                    login = driver.find_elements_by_id('login:username')[0]
                    login.send_keys("RXC")

                    senha = driver.find_elements_by_id('login:password')[0]
                    senha.send_keys("RXC")

                    driver.find_elements_by_id('login:btnEntrar')[0].click()
                    time.sleep(20)
                else:
                    driver.find_elements_by_xpath(
                        '//*[@id="btnUtilizarApplet"]')[0].click()
                    time.sleep(3)
                    driver.find_elements_by_xpath(
                        '//*[@id="/html/body/div[2]/div[2]/div/div[2]/div/img"]'
                    )[0].click()
                    time.sleep(5)
                    driver.find_elements_by_xpath(
                        '//*[@id="loginAplicacaoButton"]').click()

                # 3ª PASSO: SELECIONAR A VARA DO SERVIDOR
                select = Select(
                    driver.find_element_by_xpath(
                        '//*[@id="papeisUsuarioForm:usuarioLocalizacaoDecoration:usuarioLocalizacao"]'
                    ))
                select.select_by_visible_text(usuario['usuario']['perfil'])

                time.sleep(2.5)

                # 4ª PASSO: SELECIONAR PAINEL DE USUARIO E CLICAR NO ELEMENTO
                # driver.find_elements_by_id('formMenuPainel:menuPainel_span')[0].click()
                # time.sleep(5)
                # driver.find_elements_by_id(
                #     'formMenuPainel:paginaPainelUsuario:anchor')[0].click()
                # time.sleep(10)
                data_e_hora_atuais = datetime.now()
                for i in range(5):
                    try:
                        driver.find_elements_by_id(
                            'formMenuPainel:menuPainel_span')[0].click()
                        time.sleep(1.0)
                        driver.find_elements_by_id(
                            'formMenuPainel:paginaPainelUsuario:anchor'
                        )[0].click()
                        time.sleep(2.5)
                        break
                    except:
                        descricao_erro = "Perfil não encontrado"
                        data_e_hora_em_texto = data_e_hora_atuais.strftime(
                            '%d/%m/%Y %H:%M')
                        relatorio = {
                            "descricao": descricao_erro,
                            "data_hora": data_e_hora_em_texto,
                        }
                        requests.post(url=url_relatorio_erro,
                                      json=relatorio,
                                      headers=headers)
                        pass

                # INTERAÇÃO PARA BUSCAR OS PROCESSOS NO PJE
                i = 0
                while i < len(listaProcesso):
                    # SALVA O ID DO PROCESSO PARA FAZER O UPDATE NA API
                    id_processo = listaProcesso[i]['id']

                    # SALVA O NUMERO DO PROCESSO
                    process = listaProcesso[i]['numProcesso']
                    print("Numero do Processo: " + process)
                    data_correspondencia = listaProcesso[i]['data']
                    print(data_correspondencia)

                    # UPDATE HOUVE TENTATIVA DE JUNTADA
                    status_bot = "Houve Tentativa"
                    correspondencia_data = {
                        "status_bot": status_bot,
                    }
                    url_update = (url_correspondencia + str(id_processo))
                    requests.put(url_update,
                                 json=correspondencia_data,
                                 headers=headers)

                    # CAMINHO DO DIRETORIO
                    caminho = (diretorio + process + '.pdf')

                    # SALVA O ARQUIVO NA PASTA DESIGNADA
                    salvar_processo = urllib.request.urlretrieve(
                        url_correspondencia + 'retrieve/' +
                        listaProcesso[i]['anexo'][0]['arquivo'] + '/' + token,
                        caminho)
                    # url_correspondencia
                    time.sleep(2.5)

                    # PESQUISA O NUMERO DO PROCESSO NO PJE
                    # numero_processo = driver.find_elements_by_id(
                    #     'localizarCaixaForm:idDecoratenumeroProcessoConsulta:numeroProcessoConsulta')[0]
                    # numero_processo.clear()
                    # time.sleep(2.5)
                    # numero_processo.send_keys(
                    #     listaProcesso[i]['numProcesso'])  # processos
                    # time.sleep(10)

                    # numero_processo.send_keys(Keys.ENTER)
                    # time.sleep(15)

                    try:
                        numero_processo = driver.find_elements_by_id(
                            'localizarCaixaForm:idDecoratenumeroProcessoConsulta:numeroProcessoConsulta'
                        )[0]
                        numero_processo.clear()
                        time.sleep(2.5)
                        numero_processo.send_keys(
                            listaProcesso[i]['numProcesso'])  # processos
                        time.sleep(10)

                        numero_processo.send_keys(Keys.ENTER)
                        time.sleep(15)
                    except:
                        descricao_erro = "Processo não encontrado"
                        data_e_hora_em_texto = data_e_hora_atuais.strftime(
                            '%d/%m/%Y %H:%M')
                        relatorio = {
                            "descricao": descricao_erro,
                            "data_hora": data_e_hora_em_texto,
                            "numero_processo": process,
                            "data_correspondencia": data_correspondencia
                        }
                        requests.post(url=url_relatorio_erro,
                                      json=relatorio,
                                      headers=headers)
                        time.sleep(2.5)
                        i += 1
                        pass

                    # DETALHES DO PROCESSO
                    detalhesdoProcesso = driver.find_element_by_id(
                        'listConsultaProcessoForm:consultaProcessoListPainelUsuario:0:j_id412:j_id423'
                    )
                    time.sleep(1.5)
                    detalhesdoProcesso.click()

                    window_after = driver.window_handles[1]
                    driver.switch_to.window(window_after)
                    time.sleep(5)
                    driver.maximize_window()
                    time.sleep(5.0)

                    # EVENTO CLICK EM EXPEDIENTES
                    expediente = driver.find_element_by_id(
                        'processoExpedienteTab_lbl')
                    expediente.click()
                    time.sleep(7)

                    # FAZ A INTERAÇÃO NA TABELA EXPEDIENTES E CLICA NO CHECKBOX
                    rows = len(
                        driver.find_elements_by_xpath(
                            '//*[@id="expedienteformExpediente:expedienteprocessosCadastradosDataTable:tb"]/tr'
                        ))
                    time.sleep(5)
                    print(rows)
                    j = 0
                    while j < rows:
                        tr = driver.find_element_by_xpath(
                            "/html/body/div[4]/div/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td/div/div/div[2]/div/div[2]/form/div[2]/div[2]/table/tbody/tr["
                            + str(j + 1) + "]").text

                        if listaProcesso[i]['destinatario'] and listaProcesso[
                                i]['data'] in tr:

                            print('-------------------')
                            # print('aqui')
                            indice = j

                        j += 1
                    print(indice)

                    # print(indice)
                    print(listaProcesso[i]['destinatario'])
                    print(listaProcesso[i]['data'])

                    # CHECKBOX EXPEDIENTES
                    # checkbox = driver.find_element_by_xpath("//*[@id='expedienteformExpediente:expedienteprocessosCadastradosDataTable:"+str(indice)+":j_id3659']")
                    # checkbox.click()
                    # time.sleep(5)
                    try:
                        checkbox = driver.find_element_by_xpath(
                            "//*[@id='expedienteformExpediente:expedienteprocessosCadastradosDataTable:"
                            + str(indice) + ":j_id3659']")
                        checkbox.click()
                        time.sleep(5)
                    except:
                        i += 1
                        driver.close()
                        driver.switch_to.window(window_before)
                        time.sleep(10)
                        continue

                    # ELABORAR CERTIDÃO
                    try:
                        eleb_certidao = driver.find_element_by_xpath(
                            "//*[@id='expedienteformExpediente:expedienteprocessosCadastradosDataTable:"
                            + str(indice) + ":j_id3895']")
                        eleb_certidao.click()
                    except:
                        descricao_erro = "Elaborar Certidão não encontrado"
                        # data_e_hora_atuais = datetime.now()
                        data_e_hora_em_texto = data_e_hora_atuais.strftime(
                            '%d/%m/%Y %H:%M')
                        print(data_e_hora_em_texto)
                        relatorio = {
                            "descricao": descricao_erro,
                            "data_hora": data_e_hora_em_texto,
                            "numero_processo": process,
                            "data_correspondencia": data_correspondencia
                        }
                        print(relatorio)
                        requests.post(url=url_relatorio_erro,
                                      json=relatorio,
                                      headers=headers)

                        i += 1
                        driver.close()
                        driver.switch_to.window(window_before)
                        time.sleep(10)
                        continue

                    window_after2 = driver.window_handles[2]
                    driver.switch_to.window(window_after2)
                    driver.maximize_window()
                    time.sleep(10)

                    # POP-UP WINDOWS 3, PROCESSO PARA FAZER O UPLOAD DO ARQUIVO
                    digite = driver.find_element_by_xpath(
                        "//*[@id='certidaoForm:inputProcessoDocumentoHtmlDecoration:inputProcessoDocumentoHtml']"
                    )
                    digite.send_keys("CERTIDÃO DE JUNTADA DE AR")
                    time.sleep(2.5)

                    selectModDocumento = Select(
                        driver.find_element_by_xpath(
                            "//*[@id='certidaoForm:modeloDocumentoComboDecoration:modeloDocumentoCombo']"
                        ))
                    selectModDocumento.select_by_visible_text('Juntada')
                    time.sleep(2.5)

                    # VERIFICA SE O EXPEDIENTE FOI CUMPRIDO
                    if listaProcesso[i]['anexo'][0]['cumprido'] == "1":
                        cumprido = driver.find_element_by_xpath(
                            "//*[@id='certidaoForm:cumpridoDecoration:cumprido:0']"
                        )
                        cumprido.click()
                    else:
                        cumprido = driver.find_element_by_xpath(
                            "//*[@id='certidaoForm:cumpridoDecoration:cumprido:1']"
                        )
                        cumprido.click()

                    # ABRE O ANEXO PARA O UPLOAD DO ARQUIVO
                    abriAnexo = driver.find_element_by_xpath(
                        "//*[@id='toggleAnexarPdfCertidao_header']")
                    abriAnexo.click()
                    time.sleep(5)
                    addAnexo = driver.find_element_by_xpath(
                        "//*[@id='commandLinkAdicionar']")
                    addAnexo.click()

                    # CAMINHO DO ARQUIVO, COM UM REPLACE PORQUE A POP-UP DO WINDOWS NÃO RECONHECE "/"
                    WORD_FILE_PATH = (diretorio_arquivo_upado + process)
                    caminhoAtual = WORD_FILE_PATH.replace("/", "\\")

                    # print(caminhoAtual)
                    anexo = driver.find_element_by_xpath(
                        '//*[@id="commandLinkAdicionar"]').click()

                    # CÓDIGO DO AUTOHOTKEY
                    nome_janela = "Enviar arquivo"
                    ahk_script = """
                        DetectHiddenWindows, On        
                        SetControlDelay -1
                
                        WinWait, {1}, , 10
                        WinHide {1}
                
                        ControlGet, CaixaTexto, Hwnd,, Edit1, {1}
                        ControlSetText, , {0}, ahk_id %CaixaTexto%        
                        ControlGet, BotaoOk, Hwnd,, Button1, {1}
                        ControlClick, , ahk_id %BotaoOk%        
                        """.format(caminhoAtual, nome_janela)

                    time.sleep(5)

                    ahk.run_script(ahk_script, blocking=True)
                    time.sleep(5)
                    tipo_de_documento = Select(
                        driver.find_element_by_xpath(
                            '//*[@id="j_id243:0:tipoDoc"]'))
                    tipo_de_documento.select_by_visible_text(
                        'Aviso de Recebimento - AR')
                    time.sleep(3)
                    # driver.save_screenshot("C:/Users/Victor/Desktop/processos/%s" % listaProcesso[i]['numProcesso']+'.png')
                    # time.sleep(3)

                    gravar = driver.find_element_by_xpath(
                        '//*[@id="j_id337:cadastrar"]')
                    print("Achou")
                    gravar.click()
                    time.sleep(10)
                    assinar_digitalmente = driver.find_element_by_xpath(
                        '//*[@id="formAssinatura:pjeOfficeForm-btn-pjeOfficecertificacao"]'
                    ).click()
                    time.sleep(5)

                    time.sleep(2.5)
                    # SE TUDO OCORRER COMO PREVISTO, ELE FAZ UM UPDATE NA API COM O SUCESSO DO UPLOAD DO ARQUIVO
                    status_bot = "Sucesso"
                    correspondencia_data = {
                        "status_bot": status_bot,
                    }

                    # print("TESTE:"+listaProcesso[i]['status_bot'])
                    url_update = (url_correspondencia + str(id_processo))
                    print("Update Concluido com Sucesso")
                    requests.put(url_update,
                                 json=correspondencia_data,
                                 headers=headers)

                    # ATUALIZACAO BOT
                    descricao = "Juntada ARs"
                    atividadeBot_data = {
                        "descricao": descricao,
                    }
                    atividade = requests.put(url=url_relatorio_bot +
                                             str(id_relatorio),
                                             json=atividadeBot_data,
                                             headers=headers)

                    driver.close()
                    driver.switch_to.window(window_after)
                    time.sleep(2.5)
                    driver.close()

                    driver.switch_to.window(window_before)
                    time.sleep(1.5)

                    # print(listaProcesso[i]['numProcesso'])

                    i += 1
while x:
    startPage = requests.get(url)
    soup = BeautifulSoup(startPage.content, "lxml")
    post = soup.find("h1", {"class": "entry-title"})
    if post.text != "This is somewhat embarrassing, isn’t it?":
        post_text = post.text.split(' ')[0]
        chapter = post.text.split(':')[1]
        chapter = chapter.strip()
        print(chapter)
        if post_text == "Protected:":
            print("Chapter is posted")
            x = False
            y = True
            link_url = post.find('a')['href']
            clipboard.copy(link_url + " Chapter created")
            ahk.run_script("WinActivate, ahk_exe discord.exe", blocking=False)
            time.sleep(0.2)
            win = ahk.active_window
            ahk.send_input("^t")
            time.sleep(0.2)
            ahk.send_input("patreon-spoilers")
            time.sleep(0.2)
            ahk.send_input("{enter}")
            time.sleep(0.2)
            ahk.send_input("{Esc}{Esc}")
            time.sleep(0.2)
            if win.title == b"#patreon-spoilers - Discord":
                ahk.send_input("^a^v")
                time.sleep(0.2)
                ahk.send_input("{enter}")
            else:
import time
from ahk import AHK
ahk = AHK(executable_path='C:\\Program Files\\AutoHotkey\\AutoHotkey.exe')
f = open("guinea-pig.ahk", "r")
if f.mode == "r":
    ahk_script = f.read()
print(ahk_script)
ahk.run_script(ahk_script, blocking=False)
Пример #9
0
class AHKHandeler:

    WINDOW_CLASSES = WindowClassEnum

    def __init__(self, stream_name: str, json_dict):
        """
            Stream name
        """
        self.decoder = json_dict
        self.stream_title = stream_name

        self.ahk = AHK()
        self.get_OBS()
        self.get_ProPresenter()
        #self.start_hotkeys()
        atexit.register(self.stop_hotkeys)

    def start_hotkeys(self):
        self.camera_scene_hotkey = Bindable_Hotkey(
            self.ahk, self.decoder[JSD.CAMERA_SCENE_HOTKEY])
        self.camera_scene_hotkey.bind(
            lambda: self.OBS_send(self.decoder[JSD.CAMERA_SCENE_OBS]))
        self.screen_scene_hotkey = Bindable_Hotkey(
            self.ahk, self.decoder[JSD.CENTER_SCREEN_HOTKEY])
        self.screen_scene_hotkey.bind(
            lambda: self.OBS_send(self.decoder[JSD.CENTER_SCREEN_OBS]))

        self.camera_scene_hotkey.start()
        self.screen_scene_hotkey.start()
        return

    def stop_hotkeys(self):
        self.camera_scene_hotkey.stop()
        self.screen_scene_hotkey.stop()

    def get_ProPresenter(self):
        self.ProPresenter = self.ahk.win_get(
            self.decoder[JSD.WINDOW_PROPRESENTER])
        return self.ProPresenter

    def propresenter_send(self, key, window=None):
        old_window = self.ahk.active_window
        if self.ahk.active_window == self.get_ProPresenter():
            self.ahk.send(key)
        if window == None:
            window = self.get_ProPresenter()
            window.activate()
            time.sleep(2)
            self.ahk.send(key)
            time.sleep(.5)
            old_window.activate()

    def bring_to_front(self, preset_classes, window_class=None):
        if window_class == None:
            if preset_classes == self.WINDOW_CLASSES.CHROME:
                window_class = "Chrome_WidgetWin_1"
        self.ahk.run_script(
            f"WinActivate, ahk_class {window_class} \n WinMaximize")
        return

    def get_OBS(self):
        self.OBS = self.ahk.win_get("OBS")
        if self.OBS.id == "":
            self.open_OBS()
            self.OBS = self.ahk.win_get("OBS")
        return self.OBS

    def open_OBS(self):
        self.ahk.run_script(
            "CoordMode, Mouse, Screen\n" +
            f"MouseMove, {self.decoder[JSD.TRAY_OBS_POS][0]}, " +
            f"{self.decoder[JSD.TRAY_OBS_POS][1]} \n Click\n" +
            "Sleep 500 \n MouseMove, 500, 500")
        time.sleep(1)
        return

    def OBS_send(self, key, window=None):
        old_window = self.ahk.active_window
        if window == None:
            window = self.get_OBS()
        logging.warning(f"sending {key} to obs")
        window.activate()
        time.sleep(.5)
        self.ahk.send(key)
        time.sleep(.5)
        window.to_bottom()
        old_window.activate()
        return

    def chrome_facebook_live_start(self):
        webbrowser.open("https://www.facebook.com/CenterEvents1/")

        # Upstairs deployment settings
        thread = Thread(target=self.setup_stream_facebook,
                        args=(8000, (430, 593), (719, 152), self.stream_title,
                              (1018, 518)))

        # Nick's Laptop
        # thread = Thread(target=self.setup_stream_facebook, args=(8000, (711, 741),
        # (1084, 190), "A really cool title", (1577, 649)))
        thread.start()

    def setup_stream_facebook(
            self,
            # Facebook related
            wait_time: int,
            live_position: tuple,
            connect_position: tuple,
            stream_title: str,
            stream_label_position: tuple,
            obs_window=None):

        if obs_window == None:
            obs_window = self.get_OBS()
        if self.stream_title == None:
            raise ValueError("No stream title was given")

        self.bring_to_front(self.WINDOW_CLASSES.CHROME)
        self.ahk.run_script(
            f"#NoEnv \n CoordMode, Mouse, Screen" +
            " \n Sleep {wait_time} \n " +
            # Click Live
            f"MouseMove, 500, 500 \n Sleep 500 \n" +
            f"MouseMove, {live_position[0]}, {live_position[1]} \n" +
            "Sleep 250 \n Click \n Sleep 5000 \n" +
            # Click connect
            f"MouseMove, {connect_position[0]}, {connect_position[1]} \n Sleep 250 \n"
            + "Click \n Sleep 1500 \n")

        # Start the OBS stream
        self.OBS_send(self.decoder[JSD.OBS_START_STREAM])
        time.sleep(2)

        # Click go live button on facebook
        self.ahk.run_script(
            f"#NoEnv \n" +
            # Click Title label
            f"MouseMove, {stream_label_position[0]}, {stream_label_position[1]},"
            + f"\n Sleep 250 \n Click \n Send {stream_title} \n")

        return

    def start_facebook_stream(self, stream_go_live_position=(1018, 518)):
        original_window = self.ahk.active_window
        self.bring_to_front(self.WINDOW_CLASSES.CHROME)
        time.sleep(1)
        self.ahk.run_script(f"MouseMove, {stream_go_live_position[0]}," +
                            f" {stream_go_live_position[1]}\n" +
                            "Sleep 250 \n Click",
                            blocking=False)
        original_window.activate()

    def stop_facebook_stream(self):

        self.OBS_send(self.decoder[JSD.OBS_STOP_STREAM])
        self.bring_to_front(self.WINDOW_CLASSES.CHROME)

        self.OBS_send("^!j")

        raise ReferenceError
Пример #10
0
"""

from ahk import AHK
import numpy as np
import random
import tensorflow as tf

from OutOfMyRoom.DQNAgent.DQNAgent import DQNAgent
from OutOfMyRoom.DQNAgent.DQNAgent import BlobEnv

#  Stats settings
AGGREGATE_STATS_EVERY = 1  # episodes
SHOW_PREVIEW = False

ahk = AHK()
ahk.run_script(open('ahk_scripts/setup.ahk').read())

agent = DQNAgent()
agent.load_model(
    "..\\models_saved\\OutOfMyRoom\\Yoyo____92.00max___92.00avg___92.00min__1604357490.model"
)

env = BlobEnv()

# For more repetitive results
random.seed(1)
np.random.seed(1)
tf.random.set_seed(1)

current_state = env.reset()
step = 0
Пример #11
0
class PerRoad44:
    def __init__(self):
        self.ahk = AHK()

    def runPerRoad44(self):
        self.ahk.run_script('Run ' + Config.SOFTWARE_PATH)
Пример #12
0
def exec_command(cmd, verbose=True):
    if verbose:
        logging.info(f"Execing command {cmd}")
    # send the text to the console window, escape commas (must be `, to show up in chat)
    AHK.run_script("ControlSetText, , " + cmd.replace(',', '`,') + ", ahk_id " + CONSOLE+ \
                "\nControlSend, , {Enter}, ahk_id " + CONSOLE, blocking=True)
Пример #13
0
from ahk import AHK

ahk = AHK()

# Test reset AHK script

#ahk.run_script(open('ahk_scripts/reset.ahk').read())

# Test step AHK script
action = 1
ahk.run_script(f'action := {action}\n' +
               open('OutOfMyRoom/ahk_scripts/step.ahk').read())

# Test get_state AHK script

#ahk.run_script(open('ahk_scripts/get_state.ahk').read())
Пример #14
0
from ahk import AHK
import time

ahk = AHK(executable_path = r'C:\Users\olive\Documents\GitHub\PyXFLR\ahk\AutoHotkeyU64.exe')
ahk.run_script('Run, xflr/xflr5.exe')

time.sleep(2)
win = ahk.find_window(title=b'xflr')

win.activate()
win.send('^W')

for window in ahk.windows():
    print(window.title)

wing_edit = ahk.find_window(title=b'Wing Edition')
for i in range(8):
    time.sleep(0.01)
    wing_edit = ahk.find_window(title=b'Wing Edition')
    wing_edit.send("{Tab}")

wing_edit.send("60")
wing_edit = ahk.find_window(title=b'Wing Edition')
wing_edit.send("{Tab}")
Пример #15
0
class InputAutomator(webdriver.Ie):

    options = webdriver.IeOptions()
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
    options.add_argument(f'user-agent={user_agent}')
    options.add_argument("IgnoreZoomLevel=true")

    def __init__(self, *args, **kwargs):
        kwargs['executable_path'] = 'IEDriverServer.exe'
        kwargs['ie_options'] = self.options
        super().__init__(*args, **kwargs)
        self.maximize_window()
        self.ahk = AHK(executable_path="AutoHotkeyU64.exe")

    def adjust_coordinates(self, x, y):
        """
        Adjusts document coordinates given by selenium to screen coordinates used by AHK.
        :param x: x coordinate (pixels) in document
        :param y: y coordinate (pixels) in document
        :return: (x_adj, y_adj)
        """
        window_pos = self.get_window_position()
        browser_navigation_panel_height = self.execute_script(
            'return window.outerHeight - window.innerHeight;')
        return x + window_pos['x'], y + window_pos[
            'y'] + browser_navigation_panel_height

    def move_rand(self, elem_type, elem_text, x_offset=0, y_offset=0):
        """
        Moves mouse to a given element using a random walk path. Does not seem to make a difference.
        :param elem_type: one of "class", "css" or "id"
        :param elem_text: value of "class", "css" or "id"
        :param x_offset: x offset from element coordinates for final mouse position
        :param y_offset: y offset from element coordinates for final mouse position
        """
        try:
            if elem_type == "class":
                out = self.find_element_by_class_name(elem_text).location
            elif elem_type == "css":
                out = self.find_element_by_css_selector(elem_text).location
            elif elem_type == "id":
                out = self.find_element_by_class_name(elem_text).location
            else:
                raise ValueError("Unknown elem_type: must be class, css or id")
        except (NoSuchElementException, TimeoutException, JavascriptException):
            return False
        x_final, y_final = self.adjust_coordinates(out['x'] + x_offset,
                                                   out['y'] + y_offset)
        x0, y0 = self.ahk.mouse_position
        x_path, y_path = constrained_walk_2d((x0, y0), (x_final, y_final))
        # Reduce points
        x_path = x_path[:1] + x_path[::max([len(x_path) //
                                            50, 1])] + x_path[-1:]
        y_path = y_path[:1] + y_path[::max([len(y_path) //
                                            50, 1])] + y_path[-1:]
        for x, y in zip(x_path, y_path):
            self.ahk.run_script(f"SetMouseDelay, -1\nMouseMove, {x}, {y} , 0")
            # self.ahk.mouse_move(x=x, y=y, blocking=True, speed=0)

    def move_to(self, elem_type, elem_text, x_offset=0, y_offset=0):
        self.maximize_window()
        """
        Moves mouse to a given element directly. Passes reCAPTCHA.
        :param elem_type: one of "class", "css" or "id"
        :param elem_text: value of "class", "css" or "id"
        :param x_offset: x offset from element coordinates for final mouse position
        :param y_offset: y offset from element coordinates for final mouse position
        """
        try:
            if elem_type == "class":
                out = self.find_element_by_class_name(elem_text).location
            elif elem_type == "css":
                out = self.find_element_by_css_selector(elem_text).location
            elif elem_type == "id":
                out = self.find_element_by_class_name(elem_text).location
            else:
                raise ValueError("Unknown elem_type: must be class, css or id")
            self.ahk.mouse_move(*self.adjust_coordinates(
                out['x'] + x_offset, out['y'] + y_offset),
                                speed=10,
                                blocking=True)
            return True
        except (NoSuchElementException, TimeoutException, JavascriptException):
            return False

    def click(self):
        self.ahk.click()

    def type(self, text):
        self.ahk.send_input(text)

    def scroll(self, direction, times):
        [self.ahk.mouse_wheel(direction) for i in range(times)]

    def wait_for(self, elem_type, elem_text, timeout=15):
        result = False
        start = time()
        while not result and time() - start < timeout:
            try:
                if elem_type == "class":
                    result = self.find_element_by_class_name(
                        elem_text).is_displayed()
                elif elem_type == "css":
                    result = self.find_element_by_css_selector(
                        elem_text).is_displayed()
                elif elem_type == "id":
                    result = self.find_element_by_class_name(
                        elem_text).is_displayed()
                return result
            except (NoSuchElementException, TimeoutException,
                    JavascriptException):
                result = False
            sleep(0.1)
        if not result:
            print(f"Warn: Element {elem_text} not found after {timeout} sec")
            return result