Exemple #1
1
def buscar_test():
    msg = ''
    pyautogui.PAUSE = 0.5
    pyautogui.FAILSAFE = False
    pyperclip.copy('')
    
    findTest = pyautogui.locateOnScreen('buscar-tests.png')
    if findTest is None:
        msg = 'La opcion LOGIN TO CONSOLE no esta seleccionada'
        return (False, msg)
        #exit(0)
    else:
        testPos = list(findTest)
        #print testPos
         
    centroTest = pyautogui.center(testPos)     
    print centroTest
    pyautogui.moveTo(centroTest)
    pyautogui.click(None,None,1)
    pyautogui.moveRel(10, 30)
    pyautogui.click(None,None,1)
    #pyautogui.screenshot('menu-screen2.png')
    #pyautogui.click(None,None,1)
    #pyautogui.screenshot('menu-screen1.png')
    findLogin = pyautogui.locateOnScreen('imagenx.png')
    print findLogin
    
    return (True, msg)
def episode_get_mcn_and_ref():
    # get mcn
    mcn = pyperclip.copy('na')
    pya.moveTo(424, 474, duration=0.1)
    pya.dragTo(346, 474, duration=0.1)
    pya.hotkey('ctrl', 'c')
    mcn = pyperclip.paste()
    pya.moveTo(424, 474, duration=0.1)
    pya.click(button='right')
    pya.moveTo(481, 268, duration=0.1)
    pya.click()
    
    mcn = pyperclip.paste()
    mcn = mcn.replace(' ', '')
    # get ref
    ref = pyperclip.copy('na')
    pya.moveTo(500, 475, duration=0.1)
    pya.dragRel(-8, 0, duration=0.1)
    pya.hotkey('ctrl', 'c')
    ref = pyperclip.paste()
    pya.moveRel(8, 0, duration=0.1)
    pya.click(button='right')
    pya.moveTo(577, 274, duration=0.1)
    pya.click()
    
    ref = pyperclip.paste()
    return mcn, ref
Exemple #3
0
def main():

	while True:
        	position = pyautogui.position()
		time.sleep(60)
		if position == pyautogui.position():
			pyautogui.moveRel(0,-1)
			pyautogui.moveRel(0,1)
 def get_title():
     pya.hotkey('alt', 't')
     title = pyperclip.copy('na')
     pya.moveTo(190, 135, duration=0.1)
     pya.click(button='right')
     pya.moveRel(55, 65)
     pya.click()
     title = pyperclip.paste()
     return title
Exemple #5
0
def pass_search():
    pyautogui.PAUSE = 0.5
    pyautogui.FAILSAFE = False
    pyperclip.copy("")

    dondeEstaElBoton = pyautogui.locateOnScreen("go-button.png")
    if dondeEstaElBoton is None:
        print "El boton de GO no fue encontrado"

    else:
        botonPos = list(dondeEstaElBoton)
        print botonPos

    centroBoton = pyautogui.center(botonPos)
    print centroBoton

    contador = 0
    while True:
        contador += 1
        pyautogui.moveTo(centroBoton)
        pyautogui.moveRel(796, 0)  # Mover el raton a la barra de desplazamiento
        pyautogui.click(None, None, 2)
        # if contador == 1:
        #    time.sleep(0.3)
        #    pyautogui.typewrite('!reset')
        #    pyautogui.press('enter')

        pyautogui.click(None, None, 1)
        pyautogui.dragRel(0, -293, 1, button="left")
        # pyautogui.scroll(10)  #Hacer scroll para llegar a la parte superior del cuadro de texto
        # pyautogui.moveRel(0, -294)   #Mover el raton a la parte superior de la barra de desplazamiento
        pyautogui.moveRel(-390, 0)  # Mover el raton a la posicion en donde se encuentra la clave

        pyautogui.PAUSE = 0.05

        pyautogui.click(None, None, 2)
        # pyautogui.doubleClick()   #Hacer dobleclic en la palabra de la clave
        pyautogui.hotkey("ctrl", "c")

        # pyautogui.doubleClick()   #Hacer dobleclic en la palabra de la clave
        # pyautogui.hotkey('ctrl', 'c')

        # pyautogui.doubleClick()   #Hacer dobleclic en la palabra de la clave
        # pyautogui.hotkey('ctrl', 'c')
        pyautogui.PAUSE = 1

        r = pyperclip.paste()
        print r

        if len(r) == 10:
            print "clave encontrada"
            break
        if contador == 5:
            print "Se hizo el intento 5 veces para buscar la clave"
            break
        time.sleep(0.5)
Exemple #6
0
def test():
    time.sleep(1)
    pyautogui.moveRel(1,1)
    #time.sleep(1)
    #pyautogui.click()
    #time.sleep(1)
    #pyautogui.mouseDown()
    time.sleep(1)
    
    '''
def fileMenu():
    #!OS specific!
    #get the top left xy coords of the file menu
    try:
        x,y,bx,by = cntrl.locateOnScreen('File.png')
        cntrl.moveTo(x, y)
        cntrl.moveRel(9,35)
        cntrl.click()
       
    except:
        cntrl.alert("oops...something went wrong with File menu. See Andre")
 def go_standby(self):
   self.tv_shutdown = (Main.WAIT_TIME) #reset timer
   screensize = pyautogui.size()
   pyautogui.moveTo(screensize[0]-8, 8)
   time.sleep(1)
   pyautogui.click()
   time.sleep(1)
   pyautogui.moveRel(0, 215)
   time.sleep(1)
   pyautogui.click()
   time.sleep(10)
 def input_control(self, count_defects, img_src):
     # update position difference with previous frame (for move mouse)
     d_x, d_y = 0, 0
     if self.preCX is not None:
         d_x = self.ROIx - self.preCX
         d_y = self.ROIy - self.preCY
     
     # checking current command, and filter out unstable hand gesture
     cur_cmd = 0
     if self.cmd_switch:
         if self.last_cmds.count(count_defects) >= self.last_cmds.n_maj:
             cur_cmd = count_defects
             #print 'major command is ', cur_cmd
         else:
             cur_cmd = 0     # self.last_cmds.major()
     else:
         cur_cmd = count_defects
     
     # send mouse input event depend on hand gesture
     if cur_cmd == 1:
         str1 = '2, move mouse dx,dy = ' + str(d_x*3) + ', ' + str(d_y*3)
         cv2.putText(img_src, str1, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             pyautogui.moveRel(d_x*3, d_y*3)
             self.last_cmds.push(count_defects)
             #pyautogui.mouseDown(button='left')
             #pyautogui.moveRel(d_x, d_y)
         #else:
         #    pyautogui.mouseUp(button='left')
     elif cur_cmd == 2:
         cv2.putText(img_src, '3 Left (rotate)', (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             pyautogui.dragRel(d_x, d_y, button='left')
             self.last_cmds.push(count_defects)
             #pyautogui.scroll(d_y,pause=0.2) 
     elif cur_cmd == 3:
         cv2.putText(img_src, '4 middle (zoom)', (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             pyautogui.dragRel(d_x, d_y, button='middle')
             self.last_cmds.push(count_defects)
     elif cur_cmd == 4:
         cv2.putText(img_src, '5 right (pan)', (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             pyautogui.dragRel(d_x, d_y, button='right')
             self.last_cmds.push(count_defects)
     elif cur_cmd == 5:
         cv2.putText(img_src, '1 fingertip show up', (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             self.last_cmds.push(count_defects)
     else:
         cv2.putText(img_src, 'No finger detect!', (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 2, (0, 0, 255), 2)
         if self.cmd_switch:
             self.last_cmds.push(count_defects)  # no finger detect or wrong gesture
def episode_theatre(endoscopist, nurse, clips, varix_lot):
    pya.hotkey('alt', 'n')
    pya.typewrite(['left'] * 2)
#    if not pya.pixelMatchesColor(1100, 100, (240, 240, 240)):
#        pya.hotkey('ctrl', 'f1')
#        time.sleep(0.5)
    user = os.getenv('USERNAME')
    doc_coord = coords.get(user, ((100, 155), (100, 360)))[0]

    pya.moveTo(doc_coord)
    pya.click()
    pya.press('tab')
    doc_test = pyperclip.copy('empty')
    pya.hotkey('ctrl', 'c')
    doc_test = pyperclip.paste()
    if doc_test == 'Endoscopist':
        pya.press('tab')
        pya.typewrite(['enter'] * 2)
        pya.moveRel(400, 0)
        pya.click()
        pya.typewrite(['tab'] * 2)
        pya.typewrite(['enter'] * 2)

    pya.moveTo(doc_coord)
    pya.click()
    pya.typewrite(endoscopist)
    pya.typewrite(['enter', 'e', 'enter'])
    pya.moveRel(400, 0)
    pya.click()
    pya.typewrite(nurse)
    pya.typewrite(['enter', 'e', 'enter'])
    if clips != 0 or varix_lot:
        pros_coord = coords.get(user, ((100, 155), (100, 360)))[1]
        pya.moveTo(pros_coord)
        pya.click()
        if varix_lot:
            pyperclip.copy('Boston Scientific Speedband Superview Super 7')
            pya.hotkey('ctrl', 'v')
            pya.press('enter')
            time.sleep(0.5)
            pyperclip.copy(varix_lot)
            pya.hotkey('ctrl', 'v')
            pya.press('enter')
            pya.typewrite(['tab'] * 2)
        if clips != 0:
            pyperclip.copy('M00521230')
            for i in range(clips):
                pya.typewrite(['b', 'enter'])
                time.sleep(0.5)
                pya.hotkey('ctrl', 'v')
                pya.press('enter')
                pya.typewrite(['tab'] * 2)
    def test_pause(self):
        oldValue = pyautogui.PAUSE

        startTime = time.time()
        pyautogui.PAUSE = 0.35 # there should be a 0.35 second pause after each call
        pyautogui.moveTo(0, 0)
        pyautogui.moveRel(0,1)
        pyautogui.moveTo(0, 0)

        elapsed = time.time() - startTime
        self.assertTrue(1.0 < elapsed <  1.1, 'Took %s seconds, expected 1.0 < 1.1 seconds.' % (elapsed))

        pyautogui.PAUSE = oldValue # restore the old PAUSE value
Exemple #12
0
def reset_ui_field_on_android():
    # select all texts in the UI field
    pyautogui.mouseDown();
    time.sleep(2)
    pyautogui.mouseUp()
    # reset the UI field
    pyautogui.press("backspace")
    pyautogui.press("del")
    pyautogui.press("delete")
    # unfocus the UI field
    pyautogui.moveRel(-150, 0, duration)
    pyautogui.click()
    time.sleep(1)
def address_scrape():
    dob = pyperclip.copy('na')
    pya.moveTo(600, 175, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    dob = pyperclip.paste()
    
    street = pyperclip.copy('na')
    pya.moveTo(500, 240, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    street = pyperclip.paste()
    
    suburb = pyperclip.copy('na')
    pya.moveTo(330, 285, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    suburb = pyperclip.paste()
    
    postcode = pyperclip.copy('na')
    pya.moveTo(474, 285, duration=0.1)
    pya.dragTo(450, 285, duration=0.1)
    pya.moveTo(474, 285, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    postcode = pyperclip.paste()

    address = street + ' ' + suburb + ' ' + postcode

    return (address, dob)
Exemple #14
0
def auto_mouse():
	auto.moveTo(450,450)
	pos = auto.position()

	auto.moveRel(-200,-200)
	pos2  = auto.position()
	for i in range(100 ):
		try:
			auto.moveTo(pos, duration = 1, tween = auto.easeInCubic)
			auto.click()
			auto.moveTo(pos, duration = 1)
			auto.click()
			auto.moveTo(pos2,duration = 1, tween = auto.easeInQuad)
		except:
			sys.exit()
def example():
    screenWidth, screenHeight = pag.size()
    currentMouseX, currentMouseY = pag.position()
    pag.moveTo(500, 550)
    pag.click()
    pag.moveRel(None, 10)  # move mouse 10 pixels down
    pag.doubleClick()
    # pag.moveTo(500, 500, duration=2, tween=pyautogui.tweens.easeInOutQuad)  # use tweening/easing function to move mouse over 2 seconds.
    pag.typewrite('Hello world!', interval=0.25)  # type with quarter-second pause in between each key
    pag.press('esc')
    pag.keyDown('shift')
    pag.press(['left', 'left', 'left', 'left', 'left', 'left'])
    pag.keyUp('shift')
    pag.hotkey('ctrl', 'c')
    delta_y = 50
Exemple #16
0
    def test_moveRelWithTween(self):
        # NOTE - The user moving the mouse during this test will cause it to fail.
        DEST = 200, 200

        def resetMouse():
            # Set up mouse
            pyautogui.moveTo(100, 100)
            mousepos = pyautogui.position()
            self.assertTrue(mousepos == (100, 100), 'Mouse could not be reset to (1, 1). mousepos set to %s' % (mousepos,))

        for tweenName, tweenFunc in TestGeneral.TWEENS.items():
            resetMouse()
            pyautogui.moveRel(100, 100, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
            mousepos = pyautogui.position()
            self.assertTrue(mousepos == DEST, '%s tween move failed. mousepos set to %s instead of %s' % (tweenName, mousepos, DEST))
def episode_theatre(endoscopist, nurse, clips, varix_lot):
    pya.hotkey('alt', 'n')
    pya.typewrite(['left'] * 2, interval=0.1)

    doc_coord = (100, 155)

    pya.moveTo(doc_coord)
    pya.click()
    pya.press('tab')
    doc_test = pyperclip.copy('empty')
    pya.hotkey('ctrl', 'c')
    doc_test = pyperclip.paste()
    if doc_test == 'Endoscopist':
        pya.press('tab')
        pya.typewrite(['enter'] * 2, interval=0.1)
        pya.moveRel(400, 0)
        pya.click()
        pya.typewrite(['tab'] * 2, interval=0.1)
        pya.typewrite(['enter'] * 2, interval=0.1)

    pya.moveTo(doc_coord)
    pya.click()
    pya.typewrite(endoscopist)
    pya.typewrite(['enter', 'e', 'enter'], interval=0.1)
    pya.moveRel(400, 0)
    pya.click()
    pya.typewrite(nurse)
    pya.typewrite(['enter', 'e', 'enter'], interval=0.1)
    if clips != 0 or varix_lot:
        pya.moveTo(100, 360)
        pya.click()
        if varix_lot:
            pyperclip.copy('Boston Scientific Speedband Superview Super 7')
            pya.hotkey('ctrl', 'v')
            pya.press('enter')
            time.sleep(0.5)
            pyperclip.copy(varix_lot)
            pya.hotkey('ctrl', 'v')
            pya.press('enter')
            pya.typewrite(['tab'] * 2, interval=0.1)
        if clips != 0:
            pyperclip.copy('M00521230')
            for i in range(clips):
                pya.typewrite(['b', 'enter'], interval=0.2)
                time.sleep(0.5)
                pya.hotkey('ctrl', 'v')
                pya.press('enter')
                pya.typewrite(['tab'] * 2, interval=0.1)
Exemple #18
0
    def test_moveRelWithTween(self):
        origin = self.center - P(100, 100)
        delta = P(200, 200)
        destination = origin + delta

        def resetMouse():
            pyautogui.moveTo(*origin)
            mousepos = P(*pyautogui.position())
            self.assertEqual(mousepos, origin)

        for tweenName in self.TWEENS:
            tweenFunc = getattr(pyautogui, tweenName)
            resetMouse()
            pyautogui.moveRel(delta.x, delta.y, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
            mousepos = P(*pyautogui.position())
            self.assertEqual(mousepos, destination, '%s tween move failed. mousepos set to %s instead of %s' % (tweenName, mousepos, destination))
def moveInSquareRelative():
    while True:
        print("Moving mouse again")

        for i in range(10):
            pyautogui.moveRel(100, 0, duration=0.25)
            pyautogui.moveRel(0, 100, duration=0.25)
            pyautogui.moveRel(-100, 0, duration=0.25)
            pyautogui.moveRel(0, -100, duration=0.25)
Exemple #20
0
    def readAcc(self):
        self.wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
        wiiX = self.wii.state['acc'][cwiid.X] # '-' < 120, '+' > 120
        wiiY = self.wii.state['acc'][cwiid.Y]
        print(wiiX, wiiY)
        if wiiX+wiiY != 0:
            pyautogui.moveRel(wiiX - 120, wiiY - 120)

        try:
            check = (self.wii.state['buttons'] - cwiid.BTN_HOME)
            if check == 0: # home button still pressed
                self.after(20, self.readAcc)
            else:
                self.after(50, self.readWiiButtonsA)

        except:
            print("readAcc: Error") # probably caused by lost connection
Exemple #21
0
def moveMouseRelativeSample():
    print("Testing relative to (100,100) mouse positions")

    # Init position (100x100)
    pyautogui.moveTo(100, 100, duration=0.25)

    # Move relative
    pyautogui.moveRel(100, 0, duration=0.25)
    pyautogui.moveRel(0, 100, duration=0.25)
    pyautogui.moveRel(-100, 0, duration=0.25)
    pyautogui.moveRel(0, -100, duration=0.25)
def map_num_to_mouse(number):
    """
    move_dict = {
        "0":( 0, 0),
        "1":(INC, 0),
        "2":( 0, INC),
        "3":( 0, 0),
        "4":( -INC, 0),
        "5":( 0, -INC),
        "6":( 0, 0),
        "7":( 0, 0),}
    """
    if number == 7:
        print("CLICK!")
        pyautogui.click()
        return 2
    else:
        #TODO: crashes if I give it a number not in the dictionary
        pyautogui.moveRel(move_dict[str(number)])
        return 1
def inertia_mouse(x_speed, y_speed, button_state):
    print("STARTING x_speed is: " + str(x_speed) + ", y_speed is " + str(y_speed))
    #print("Hey! We got into intertia_mouse!")
    #RIGHT
    if button_state == 1 and x_speed < (MAXSPEED - INC):
        print("RIGHT")
    #if button_state == 1 and x_speed < (MAXSPEED - INC):
        x_speed += INC
        y_speed = slow_speed(y_speed)
    #LEFT
    elif button_state == 4 and x_speed > (-MAXSPEED + INC):
        print("LEFT")
    #else if button_state == 4 and x_speed > (-MAXSPEED + INC):
        x_speed -= INC
        y_speed = slow_speed(y_speed)
    #UP
    elif button_state == 2 and y_speed < (MAXSPEED - INC):
        print("UP")
        y_speed += INC
        x_speed = slow_speed(x_speed)
    #DOWN
    elif button_state == 5 and y_speed > (-MAXSPEED + INC):
        print("DOWN")
        y_speed -= INC
        x_speed = slow_speed(x_speed)
    #HOLD
    elif button_state == 7: 
        print("HOLD!")
    elif button_state == 3:
        print("CLICK")
        pyautogui.click()
        x_speed = slow_speed(x_speed)
        y_speed = slow_speed(y_speed)
        time.sleep(.25)
    else:
        x_speed = slow_speed(x_speed)
        y_speed = slow_speed(y_speed)
    print("ENDING x_speed is: " + str(x_speed) + ", y_speed is " + str(y_speed))
    if x_speed or y_speed:
        pyautogui.moveRel(x_speed, y_speed)
    return x_speed, y_speed
Exemple #24
0
    def execute(self):
        self.init()

        while (self.running):
	    acc_meas = imu.read_acc_data()
	    gyr_meas = imu.read_gyr_data()
	    mag_meas = imu.read_mag_data()

	    # Flip acceleration to match Raspberry Pi frame (rotate around Y_ACC)
	    acc_meas[2] = -acc_meas[2]
	    acc_meas[0] = -acc_meas[0]


            for event in pygame.event.get():
                self.handleEvent(event)
            self.loop()
            self.render()
      	    pyautogui.moveRel(mag_meas[1], 0)
            
            if(GPIO.input(buttonPin)):
                pyautogui.click()
        self.cleanup()
def address_scrape():
    """Scrape address and dob from blue chip.
    Used if billing anaesthetist.
    """
    dob = pyperclip.copy('na')
    pya.moveTo(600, 175, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    dob = pyperclip.paste()
    
    street = pyperclip.copy('na')
    pya.moveTo(500, 240, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    street = pyperclip.paste()
    
    suburb = pyperclip.copy('na')
    pya.moveTo(330, 285, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    suburb = pyperclip.paste()
    
    postcode = pyperclip.copy('na')
    pya.moveTo(474, 285, duration=0.1)
    pya.dragTo(450, 285, duration=0.1)
    pya.moveTo(474, 285, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    postcode = pyperclip.paste()

    address = street + ' ' + suburb + ' ' + postcode

    return (address, dob)
def exportPacketDissections(exportAs):
    #Warning! Only use this after calling fileMenu()
    fileMenu()
    #get mouse location
    x,y = cntrl.position()

    #scroll down and expand the "Export Packet Dissetions"
    xrel = 0
    yrel = 235
    cntrl.moveRel(xrel,yrel)
    cntrl.click()

    #dictionary map of export types in wireshark
    exportAsXYMap = {
        "Plain Text":(320,0),
        "PostScript":(320,16),
        "CSV":(320,36),
        "C Arrays":(320,54),
        "PSML":(320,66),
        "PDML":(320,87)        
        }

    xrel,yrel = exportAsXYMap[exportAs]
    cntrl.moveRel(xrel,yrel)
    cntrl.click()
    
    #!OS specific!
    #at this point the "save as" window appears.
    #go up levels until we get to the desktop.

    #need to put a delay in to allow the save window to open first
    time.sleep(0.25)

    #find the desktop location to make our way to the project folder
    x,y,bx,by = cntrl.locateOnScreen("save_as_window_leftIcons.png")
    cntrl.moveTo(x, y)
    cntrl.moveRel(0,143)
    cntrl.click()
    
    '''#find the pulldown menu
Exemple #27
0
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 15:19:03 2019

@author: everl
"""

import pyautogui
print(pyautogui.size())
tam, alt = pyautogui.size()

position = pyautogui.position()
print(position)

pyautogui.moveTo(100, 100, duration=1)
pyautogui.moveRel(200, 0, duration=3)
pyautogui.moveRel(0, -100, duration=3)
pyautogui.click(100, 100, duration=3)
def main():
    # 读取配置文件
    config = configparser.ConfigParser()
    config.read('config.ini', encoding='utf-8')
    startTime = StrT0List(config.get('Time', 'startTime'))
    finishTime = StrT0List(config.get('Time', 'finishTime'))
    path_DT = config.get('Path', 'DingTalk')
    path_OutDT = config.get('Path', 'OutDt')
    path_InDT = config.get('Path', 'InDT')

    #打开钉钉
    os.popen(path_DT)
    print('打开钉钉主程序......')
    time.sleep(3)

    #进入钉钉群
    while True:

        #如果已经进入钉钉群
        if pyautogui.locateOnScreen(path_InDT) != None:
            break

        #如果没有进入钉钉群
        else:
            pyautogui.moveTo(pyautogui.locateOnScreen(path_OutDT),
                             duration=0.5)
            pyautogui.click()
            pyautogui.moveRel(100, 100)

    while True:
        try:
            #如果正在直播
            if pyautogui.locateOnScreen(
                    'pic\\live.png') or pyautogui.locateOnScreen(
                        'pic\\LiveWindows.png'
                    ) or pyautogui.locateOnScreen('pic\\live2.png') != None:
                print('正在直播...')

                #如果已经进入直播间
                if pyautogui.locateOnScreen('pic\\LiveWindows.png') != None:
                    print('已进入直播间...')
                    time.sleep(15)

                #如果没有进入直播间
                else:
                    print('未进入直播间,正在加入...')
                    Enter_the_Live_Room()

            #如果没有直播
            else:
                #现在时间是否下课
                for i in range(len(startTime) - 1):
                    if get_second(finishTime[i]) < get_second(
                            now_time()) < get_second(startTime[i + 1]):
                        diff_time = int(
                            get_second(startTime[i + 1]) -
                            get_second(now_time()))
                        print('已下课!', diff_time, 'S后上课')
                        if diff_time >= 600:
                            time.sleep(diff_time - 600)
                            #Sign_in_QQ() # 个人需要,不需要请删除
                            time.sleep(600)
                        elif 30 < diff_time < 600:
                            #Sign_in_QQ() # 个人需要,不需要请删除
                            time.sleep(diff_time - 30)
                        else:
                            #Sign_in_QQ() # 个人需要,不需要请删除
                            time.sleep(diff_time)
                        break

                #现在时间是否上课
                for i in range(len(startTime)):
                    if get_second(startTime[i]) < get_second(
                            now_time()) < get_second(finishTime[i]):
                        print('上课时间未直播...')
                        time.sleep(5)
                        break

                #特殊情况
                if get_second(startTime[0]) > get_second(now_time()):
                    diff_time = get_second(startTime[0]) - get_second(
                        now_time())
                    print('已下课!', diff_time, 'S后上课')

                    #距离上课还有十分钟以上
                    if diff_time >= 600:
                        time.sleep(diff_time - 600)
                        #Sign_in_QQ() # 个人需要,不需要请删除
                        time.sleep(600)

                    #距离上课还有30秒以上但不足十分钟
                    elif 30 < diff_time < 600:
                        #Sign_in_QQ() # 个人需要,不需要请删除
                        time.sleep(diff_time - 30)

                    #距离上课不足30秒
                    else:
                        #Sign_in_QQ() # 个人需要,不需要请删除
                        time.sleep(diff_time)
                if get_second(now_time()) > get_second(finishTime[-1]):
                    print('今天没课了,你看尼玛呢')  # 嘤嘤嘤
        except:
            print('error')
            time.sleep(10)
Exemple #29
0
print(width)
print(height)

# 絶対座標で移動
pgui.moveTo(100, 100, duration=0.25)
pgui.moveTo(100, 100, duration=0.0)
pgui.moveTo(100, 100, duration=1.0)

for i in range(3):
    pgui.moveTo(100, 100, duration=0.25)
    pgui.moveTo(200, 100, duration=0.25)
    pgui.moveTo(200, 200, duration=0.25)
    pgui.moveTo(100, 200, duration=0.25)

# 相対座標で移動
pgui.moveRel(100, 0, duration=0.25)
pgui.moveRel(100, 0, duration=0.25)
pgui.moveRel(100, 0, duration=0.25)

# マウスの現在位置を取得
x, y = pgui.position()
print(x)
print(y)

# クリック
x = 100
y = 100
for ii in range(10):
    pgui.click(x, y)
    x += 1
    y += 1
Exemple #30
0
def relativeMove():
  for i in range(2):
    pyautogui.moveRel(100,0,duration=0.25)
    pyautogui.moveRel(0,100,duration=0.25)
    pyautogui.moveRel(-100,0,duration=0.25)
    pyautogui.moveRel(0,-100,duration=0.25)
Exemple #31
0
 def moveToStartPos(self):
     self.Start_Pos = pyautogui.locateCenterOnScreen('tinderLogo.png')
     pyautogui.moveTo(self.Start_Pos[0],self.Start_Pos[1])
     pyautogui.moveRel(self.X_Start_Offset,self.Y_Start_Offset)
     pyautogui.click (clicks=1)
Exemple #32
0
    def test_moveRel(self):
        # start at the center
        desired = self.center
        pyautogui.moveTo(*desired)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move down and right
        desired += P(42, 42)
        pyautogui.moveRel(42, 42)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move up and left
        desired -= P(42, 42)
        pyautogui.moveRel(-42, -42)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move right
        desired += P(42, 0)
        pyautogui.moveRel(42, 0)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move down
        desired += P(0, 42)
        pyautogui.moveRel(0, 42)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move left
        desired += P(-42, 0)
        pyautogui.moveRel(-42, 0)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # move up
        desired += P(0, -42)
        pyautogui.moveRel(0, -42)
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # Passing a list instead of separate x and y.
        desired += P(42, 42)
        pyautogui.moveRel([42, 42])
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # Passing a tuple instead of separate x and y.
        desired -= P(42, 42)
        pyautogui.moveRel((-42, -42))
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)

        # Passing a sequence-like object instead of separate x and y.
        desired += P(42, 42)
        pyautogui.moveRel(P(42, 42))
        mousepos = P(*pyautogui.position())
        self.assertEqual(mousepos, desired)
 def GUI_up():  # 'up'
     print('up')
     pyautogui.moveRel(0, -20 * GUI_speed_y, duration=0)
 def GUI_left():  # 'left'
     print('left')
     # move the mouse 40 pixles left relative to its current location instantly
     pyautogui.moveRel(-40 * GUI_speed_x, 0, duration=0)
Exemple #35
0
from selenium import webdriver
import pyautogui
import urllib

driver = webdriver.Chrome('E:\ChromeDriver/chromedriver')
driver.get("https://www.jain.software/")
pyautogui.rightClick()
pyautogui.moveRel(200, 250)
pyautogui.click()
pyautogui.hotkey('ctrl', 'a')
pyautogui.hotkey('ctrl', 'c')
pyautogui.hotkey('ctrl', 'shift', 'w')
Exemple #36
0
def main(prefix, vc, chat, server, playlist):
    """The main function"""
    try:
        """Validate if the file in image directory exist of not"""

        # Checking the file in .\images\server_img directory
        os.path.isfile(f"{server_image_dir}\\{server_img[server-1]}")

        # Checking file in .\images\voice_channel directory
        os.path.isfile(f"{vc_image_dir}\\{vc_img[vc-1]}")

        # Checking file in .\images\chat_channel directory
        os.path.isfile(f"{chat_image_dir}\\{chat_img[chat-1]}")

        # Checking the chatbox image
        os.path.isfile(".\\dmat\\images\\chatbox.png")

    except FileNotFoundError:
        click.secho(
            "ERROR: Playlist is empty. Use register -p[PATH] command to add playlist",
            fg='bright_red')

    except IndexError:
        click.secho(
            'ERROR: Image file not available. Use the view command to see the file available or --help command to see available commands',
            fg='bright_red')
    else:
        try:
            # Open discord app
            with open(".\\dmat\\discord_path.txt", "r") as file:
                discord_path = file.read()
                subprocess.Popen(discord_path)
            time.sleep(2.5)

            # Locate server logo location and click it
            logo_location = pyautogui.locateCenterOnScreen(
                f"{server_image_dir}\\{server_img[server-1]}", confidence=0.6)
            pyautogui.click(logo_location)

            # Locate voice channel and click it
            voice_channel_location = pyautogui.locateCenterOnScreen(
                f"{vc_image_dir}\\{vc_img[vc-1]}", confidence=0.8)
            if (voice_channel_location == None):
                # dc_channel = pyautogui.locateCenterOnScreen(
                #     ".\\images\\dc_channel.png", confidence=0.4)
                pyautogui.moveRel(100, 100)
                print(voice_channel_location)

                while (voice_channel_location == None):
                    pyautogui.PAUSE = 0.2
                    pyautogui.scroll(-120)
                    voice_channel_location = pyautogui.locateCenterOnScreen(
                        f"{vc_image_dir}\\{vc_img[vc-1]}", confidence=0.8)
                else:
                    pyautogui.click(voice_channel_location)
            else:
                pyautogui.click(voice_channel_location)
                pyautogui.PAUSE = 2
            time.sleep(1)

            # Locate chat channel and click it
            chat_channel_location = pyautogui.locateCenterOnScreen(
                f"{chat_image_dir}\\{chat_img[chat-1]}", confidence=0.7)
            while chat_channel_location == None:
                print(chat_channel_location)
                pyautogui.moveRel(0, -300)
                pyautogui.scroll(-50)
                chat_channel_location = pyautogui.locateCenterOnScreen(
                    f"{chat_image_dir}\\{chat_img[chat-1]}", confidence=0.7)
            else:
                pyautogui.click(chat_channel_location)

            # Locate the chatbox and click it
            chatbox_location = pyautogui.locateCenterOnScreen(
                ".\\dmat\\images\\chatbox.png", confidence=0.4)
            pyautogui.click(chatbox_location)

            # Open playlist.txt in read mode
            with open('.\\dmat\\playlist.txt', 'r') as file:
                file_content = file.read()
                stripped_content = file_content.strip(" ")
                playlists = stripped_content.split('\n')
                # Open the textfile path stored inside playlist.txt
                with open(playlists[playlist - 1],
                          'r',
                          encoding="cp437",
                          errors="ignore") as songs:
                    # Read and split the content into list based on line break
                    song_content = songs.read()
                    splitted_content = song_content.split('\n')

                    # Looping over the list and write the content.
                    for i in splitted_content:
                        # Check for empty string e.g.line break
                        if i != '':
                            pyautogui.write(f"{prefix}play {i}", interval=0.03)
                            pyautogui.press('enter')

                        # If exist, skip it and continue the loop
                        else:
                            continue
                    # If the loop has completed
                    else:
                        time.sleep(1)
                        if prefix == "-":
                            # Write loop queue command
                            pyautogui.write(f"{prefix}loop queue",
                                            interval=0.03)
                        else:
                            pyautogui.write(f"{prefix}loopqueue",
                                            interval=0.03)

                        pyautogui.press('enter')
                        click.secho('done!', fg='green')
                        sys.exit()
        except pyautogui.FailSafeException:
            click.secho('Execution has been stopped', fg='yellow')
        except OSError:
            click.secho(
                "ERROR: Discord.exe path couldn't be found or missing. Use register -d[PATH] command to add discord path",
                fg='bright_red')
Exemple #37
0
import pyautogui, time
time.sleep(3)
distance = 800

while True:
    pyautogui.moveRel(distance, 0, duration=0.5)
    pyautogui.click()
    time.sleep(4)
    pyautogui.typewrite("D")
    time.sleep(14)
    pyautogui.moveRel(-distance, 0, duration=0.5)
    pyautogui.click()
    time.sleep(4)
    pyautogui.typewrite("D")
    time.sleep(14)
Exemple #38
0
zap_main.activate()
# What is hotkey to minimize window?
# pyautogui.hotkey('alt', 'f9')
# https://bitbucket.org/antocuni/wmctrl/src/
# firefox = Window.get_active()
# firefox.set_properties("remove,maximized_horz,maximized_vert")
# call(['xdotool', 'getactivewindow', 'windowminimize'])

# Click options
pyautogui.moveTo(250, 94, duration=0.8)
pyautogui.click()
for i in range(0, 23):
    pyautogui.hotkey('down')

pyautogui.moveRel(100, 468)
pyautogui.click()

pyautogui.press('esc')
time.sleep(1)

# Flaky image identification
# https://docs.opencv.org/3.4.0/d4/dc6/tutorial_py_template_matching.html
if os.path.exists('assets/gear.png'):
    coords = pyautogui.locateOnScreen('assets/gear.png')
    print(coords)

# Expand sites
# @todo

# Hotkey for alerts
		
		if len(contours)!=0: 
			cnt = contours[0]
			M = cv2.moments(cnt)
			if int(M['m00'])!= 0:
				cx = int(M['m10']/M['m00'])
				cy = int(M['m01']/M['m00'])
				dcx = cx - cx_prev
				dcy = cy - cy_prev
				#print "centeroid: %s, %s"%(dcx, dcy)
				cx_prev = cx
				cy_prev = cy
				a=dcy*3
				b=-(dcx*3)
				
				pyautogui.moveRel(b, a)

			
	img1 = cv2.drawContours(img1, contours, -1, (0,255,0), 3)
	#ret,thresh1 = cv2.threshold(hsv,220,255,cv2.THRESH_BINARY)#thresh to light. can try laser 
	#ret,thresh1 = cv2.threshold(hsv,127,255,cv2.THRESH_TRUNC)
	#ret,thresh2 = cv2.threshold(hsv,127,255,cv2.THRESH_TRIANGLE)
	#ret,thresh3 = cv2.threshold(hsv,127,255,cv2.THRESH_OTSU)
	#thresh2 = cv2.adaptiveThreshold(hsv2,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
	#thresh3 = cv2.adaptiveThreshold(hsv2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
	#cv2.imshow('img',img1)
	#cv2.imshow('hsv',hsv)
	#cv2.imshow('mask',mask)
	#cv2.imshow('res',res)	
	#cv2.imshow('blur',median)
	#cv2.imshow('thresh1',thresh1)
 def GUI_down():  # 'down'
     print('down')
     pyautogui.moveRel(0, 20 * GUI_speed_y, duration=0)
#!/usr/bin/python3

import time
import pyautogui

if __name__ == "__main__":
    count = 0
    xoffset = 1
    yoffset = 1
    sleeptime = 60

    max_x, max_y = pyautogui.size()
    max_x -= 1
    max_y -= 1
    print('Display size: x=' + str(max_x) + ', y=' + str(max_y))

    while True:
        pyautogui.moveRel(xoffset, yoffset)
        x, y = pyautogui.position()
        if x == max_x or x == 0:
            xoffset *= -1
        if y == max_y or y == 0:
            yoffset *= -1
        print('Insomnia: ' + time.ctime())
        time.sleep(sleeptime)
def front_scrape():
    def get_title():
        pya.hotkey('alt', 't')
        title = pyperclip.copy('na')
        pya.moveTo(190, 135, duration=0.1)
        pya.click(button='right')
        pya.moveRel(55, 65)
        pya.click()
        title = pyperclip.paste()
        return title

    pya.click(50, 450)
    title = get_title()
    
    if title == 'na':
        pya.press('alt')
        pya.press('b')
        pya.press('c')
#        pya.press('down')
#        pya.press('enter')
        title = get_title()
    
    if title == 'na':
        pya.alert('Error reading Blue Chip.')
        raise BillingException

    for i in range(4):
        first_name = pyperclip.copy('na')
        pya.moveTo(290, 135, duration=0.1)
        pya.click(button='right')
        pya.moveRel(55, 65)
        pya.click()
        first_name = pyperclip.paste()
        if first_name != 'na':
            break
        if first_name == 'na':
            first_name = pya.prompt(text='Please enter patient first name',
                              title='First Name',
                              default='')

    for i in range(4):
        last_name = pyperclip.copy('na')
        pya.moveTo(450, 135, duration=0.1)
        pya.click(button='right')
        pya.moveRel(55, 65)
        pya.click()
        last_name = pyperclip.paste()
        if last_name != 'na':
            break
        if last_name == 'na':
            last_name = pya.prompt(text='Please enter patient surname',
                              title='Surame',
                              default='')
 
    print_name = title + ' ' + first_name + ' ' + last_name

    mrn = pyperclip.copy('na')
    pya.moveTo(570, 250, duration=0.1)
    pya.dragTo(535, 250, duration=0.1)
    pya.moveTo(570, 250, duration=0.1)
    pya.click(button='right')
    pya.moveRel(55, 65)
    pya.click()
    mrn = pyperclip.paste()
    if not mrn.isdigit():
        mrn = pya.prompt("Please enter this patient's MRN")
    
    return (mrn, print_name)
import pyautogui

print(pyautogui.size())
print(pyautogui.position())
pyautogui.moveTo(10, 10, duration=1.5)
pyautogui.moveRel(200, 0, duration=1.5)
pyautogui.moveRel(0, 200, duration=1.5)
Exemple #44
0
 def action(self):
     # py.press('down', presses=2)
     py.moveRel(-5, 0, 0.1)
     py.moveRel(5, 0, 0.1)
     py.press('space', presses=3)
import pyautogui
import keyboard

i=0
while True: 
    pyautogui.dragRel(200, 0,duration=0.2)
    pyautogui.moveRel(-200, 0)
    i+=1
    try:
        if keyboard.is_pressed('q'):
            break
        else:
            pass
    finally:
        pass
 def GUI_right():  # 'right'
     print('right')
     pyautogui.moveRel(40 * GUI_speed_x, 0, duration=0)
def assistant(command, lastCommand):
    "if statements for executing commands"

    if 'repeat once' in command:
        command = lastCommand
        print(lastCommand)

#    if 'repeat 5' in command:
#        assistant(lastCommand,lastCommand)
#        assistant(lastCommand,lastCommand)
#        assistant(lastCommand,lastCommand)
#        print('kikiriki')
#        print ('mjau mjau')
#
    elif 'repeat' in command:
        reg_ex = re.search('repeat (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            counter = 0
            try:
                counter = +int(domain)
            except ValueError:
                pass
            while counter > 0:
                assistant(lastCommand, lastCommand)
                counter = counter - 1
#            lastCommand=command
        else:
            pass

    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        lastCommand = command
        print('Done!')

    elif 'open website' in command:
        reg_ex = re.search('open website (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://www.' + domain
            webbrowser.open(url)
            print('Done!')
            lastCommand = command
        else:
            pass

    elif 'google' in command:
        reg_ex = re.search('google (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://www.google.com/search?q=' + domain
            webbrowser.open(url)
            print('Done!')
            lastCommand = command
        else:
            pass

    elif 'duck' in command:
        reg_ex = re.search('duck (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://duckduckgo.com/?q=' + domain
            webbrowser.open(url)
            lastCommand = command
            print('Done!')
        else:
            pass

    elif 'wikipedia search' in command:
        reg_ex = re.search('wikipedia search (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            mylist = wikipedia.search(domain)
            #            print(*mylist,sep='\n')
            for number, letter in enumerate(mylist):
                #                print(number, letter)
                listOut = str(str(number) + letter)
                talkToMeV2(listOut)

            print('\n' + 'Chose number representing page.')
            print('\n' + 'Say /wikipedia exit/ to exit selection.')

            while (True):
                if wikipediaChosePage(myCommand(), mylist) == True:
                    break
            print('Wikipedia Done!')
#           lastCommand=command

        else:
            pass

    elif 'write' in command:
        reg_ex = re.search('write (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.typewrite('' + domain, 0.1)
            print('Written!')
            lastCommand = command
        else:
            pass
    elif 'custom script' in command:
        reg_ex = re.search('custom script (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            #            print(domain)
            #            customScript1.main()
            if domain == 'first':
                customScript1.main()
            elif domain == 'second':
                customScript2.main()
            else:
                #                print('No such script')
                talkToMeV2('No such script')
        else:
            pass

    elif 'window change' in command:
        pyautogui.keyDown('alt')
        time.sleep(3)
        #        print('timer over')
        pyautogui.typewrite(['tab'], 0.2)
        #        time.sleep(3)
        selected = False
        while selected != True:
            selected = windowChanging(myCommand(), selected)
#            print('in while loop')
        print('Window Changed!')
        lastCommand = command

    elif 'keyboard' in command:
        reg_ex = re.search('keyboard (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.typewrite(['' + domain], 1)
            print('Pressed!')
            lastCommand = command
        else:
            pass

    elif 'hotkey control alternative shift' in command:
        reg_ex = re.search('hotkey control alternative shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'alt', 'shift', '' + domain)
            print('Ctrl-Alt-Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey ctrl alternative shift' in command:
        reg_ex = re.search('hotkey ctrl alternative shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'alt', 'shift', '' + domain)
            print('Ctrl-Alt-Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey control alternative' in command:
        reg_ex = re.search('hotkey control alternative (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'alt', 'shift', '' + domain)
            print('Ctrl-Alt hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey ctrl alternative' in command:
        reg_ex = re.search('hotkey ctrl alternative (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'alt', '' + domain)
            print('Ctrl-Alt hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey control shift' in command:
        reg_ex = re.search('hotkey control shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'shift', '' + domain)
            print('Ctrl-Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey ctrl shift' in command:
        reg_ex = re.search('hotkey ctrl shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', 'shift', '' + domain)
            print('Ctrl-Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey alternative shift' in command:
        reg_ex = re.search('hotkey alternative shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('alt', 'shift', '' + domain)
            print('Alt-Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey shift' in command:
        reg_ex = re.search('hotkey shift (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('shift', '' + domain)
            print('Shift hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey control' in command:
        reg_ex = re.search('hotkey control (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('ctrl', '' + domain)
            print('Ctrl hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'hotkey alternative' in command:
        reg_ex = re.search('hotkey alternative (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            pyautogui.hotkey('alt', '' + domain)
            print('Alt hotkey Pressed!' + domain)
            lastCommand = command
        else:
            pass

    elif 'blender light rotate' in command:
        pyautogui.hotkey('ctrl', 'shift', 'q')
        print('Ctrl-Shift-Q hotkey Pressed!')
        lastCommand = command

    elif 'pause toggle' in command:
        pyautogui.typewrite(['space'], 1)
        lastCommand = command
        talkToMe('space Pressed!')

    elif 'keyboard next' in command:
        pyautogui.typewrite(['tab'], 1)
        lastCommand = command
        talkToMe('tab Pressed!')

    elif 'keyboard previous' in command:
        pyautogui.typewrite(['shift', 'tab'], 1)
        lastCommand = command
        talkToMe('Shift-tab Pressed!')

    elif 'pause youtube' in command:
        pyautogui.typewrite(['k'], 1)
        lastCommand = command
        talkToMe('K Pressed!')

    elif 'youtube' in command:
        reg_ex = re.search('youtube (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://www.youtube.com/results?search_query=' + domain
            webbrowser.open(url)
            lastCommand = command
            print('Done!')
        else:
            pass

    elif 'close window' in command:
        pyautogui.hotkey('alt', 'f4')
        lastCommand = command
        talkToMe('Alt-F4 Pressed!')

    elif 'assistant stop' in command:
        talkToMe('Asistant paused')
        while True:
            if assistantPause(myCommand()) == True:
                break
        talkToMe('Asistant continued')

    elif 'assistant exit' in command:
        talkToMe('Asistant exiting')
        lastCommand = command

    elif 'cursor small move right' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(maxX / 200, 0, duration=0.2)
        lastCommand = command
    elif 'cursor medium move right' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(maxX / 50, 0, duration=0.2)
        lastCommand = command
    elif 'cursor large move right' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(maxX / 10, 0, duration=0.2)
        lastCommand = command

    elif 'cursor small move left' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(-maxX / 200, 0, duration=0.2)
        lastCommand = command
    elif 'cursor medium move left' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(-maxX / 50, 0, duration=0.2)
        lastCommand = command
    elif 'cursor large move left' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(-maxX / 10, 0, duration=0.2)
        lastCommand = command

    elif 'cursor small move sky' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, -maxY / 200, duration=0.2)
        lastCommand = command
    elif 'cursor medium move sky' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, -maxY / 50, duration=0.2)
        lastCommand = command
    elif 'cursor large move sky' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, -maxY / 10, duration=0.2)
        lastCommand = command
    elif 'cursor small move down' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, maxY / 200, duration=0.2)
        lastCommand = command
    elif 'cursor medium move down' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, maxY / 50, duration=0.2)
        lastCommand = command
    elif 'cursor large move down' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveRel(0, maxY / 10, duration=0.2)
        lastCommand = command

    elif 'screen centre' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveTo(maxX / 2, maxY / 2)
        lastCommand = command
    elif 'screen origin' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.moveTo(maxX / 200, maxY / 200)
        lastCommand = command

    elif 'cursor click' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.click(pyautogui.position())
        lastCommand = command
    elif 'cursor double click' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.doubleClick(pyautogui.position())
        lastCommand = command
    elif 'cursor triple click' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.tripleClick(pyautogui.position())
        lastCommand = command
    elif 'cursor right click' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.rightClick(pyautogui.position())
        lastCommand = command
    elif 'cursor middle click' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.middleClick(pyautogui.position())
        lastCommand = command

    elif 'cursor down' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.mouseDown(pyautogui.position(), button='left')
#        lastCommand=command
    elif 'cursor lift' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.mouseUp(pyautogui.position(), button='left')
#        lastCommand=command

    elif 'cursor middle down' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.mouseDown(pyautogui.position(), button='middle')
#        lastCommand=command
    elif 'cursor middle lift' in command:
        maxX, maxY = pyautogui.size()
        print(maxX, maxY)
        pyautogui.mouseUp(pyautogui.position(), button='middle')


#        lastCommand=command

    elif 'read copied' in command:
        pasted = pyperclip.paste()
        str(pasted)
        talkToMeV2(pasted)
        lastCommand = command

    elif 'what\'s up' in command:
        lastCommand = command
        talkToMe('Just doing my thing')
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            talkToMe(str(res.json()['joke']))
            lastCommand = command
        else:
            talkToMe('oops!I ran out of jokes')

    elif 'current weather in' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            weather = Weather()
            location = weather.lookup_by_location(city)
            condition = location.condition()
            lastCommand = command
            talkToMe(
                'The Current weather in %s is %s The tempeture is %.1f degree'
                % (city, condition.text(), (int(condition.temp()) - 32) / 1.8))

    elif 'weather forecast in' in command:
        reg_ex = re.search('weather forecast in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            weather = Weather()
            location = weather.lookup_by_location(city)
            forecasts = location.forecast()
            for i in range(0, 3):
                talkToMe(
                    'On %s will it %s. The maximum temperture will be %.1f degree.'
                    'The lowest temperature will be %.1f degrees.' %
                    (forecasts[i].date(), forecasts[i].text(),
                     (int(forecasts[i].high()) - 32) / 1.8,
                     (int(forecasts[i].low()) - 32) / 1.8))
            lastCommand = command

    elif 'email' in command:
        talkToMe('Who is the recipient?')
        recipient = myCommand()

        if 'John' in recipient:
            talkToMe('What should I say?')
            content = myCommand()

            #init gmail SMTP
            mail = smtplib.SMTP('smtp.gmail.com', 587)

            #identify to server
            mail.ehlo()

            #encrypt session
            mail.starttls()

            #login
            mail.login('username', 'password')

            #send message
            mail.sendmail('John Fisher', '*****@*****.**', content)

            #end mail connection
            mail.close()

            talkToMe('Email sent.')

        else:
            talkToMe('I don\'t know what you mean!')
    return lastCommand
Exemple #48
0
import pyautogui

size = pyautogui.size()

print(size)  #Size(width=1366, height=768)

# 移动鼠标
for i in range(10):

    pyautogui.moveTo(100, 100, duration=0.25)
    pyautogui.moveTo(100, 200, duration=0.25)
    pyautogui.moveTo(200, 200, duration=0.25)
    pyautogui.moveTo(100, 200, duration=0.25)

# pyautogui.moveRel() 函数 使用相对位置移动
print('开始使用相对位置移动')
for i in range(10):
    pyautogui.moveRel(100, 0, duration=0.25)
    pyautogui.moveRel(0, 100, duration=0.25)
    pyautogui.moveRel(-100, 0, duration=0.25)
    pyautogui.moveRel(0, -100, duration=0.25)
Exemple #49
0
        best = used_defect
        if count_defects == 2:
            x = best['x']
            y = best['y']
            display_x = x
            display_y = y

            if MOVEMENT_START is not None:
                M_START = (x, y)
                x = x - MOVEMENT_START[0]
                y = y - MOVEMENT_START[1]
                x = x * (SCREEN_X / CAMERA_X)
                y = y * (SCREEN_Y / CAMERA_Y)
                MOVEMENT_START = M_START
                print("X: " + str(x) + " Y: " + str(y))
                pyautogui.moveRel(x, y)
            else:
                MOVEMENT_START = (x, y)

            cv2.circle(crop_img, (display_x, display_y), 5, [255, 255, 255],
                       20)
        elif count_defects == 5 and CLICK is None:
            CLICK = time.time()
            pyautogui.click()
            CLICK_MESSAGE = "LEFT CLICK"
        elif count_defects == 4 and CLICK is None:
            CLICK = time.time()
            pyautogui.rightClick()
            CLICK_MESSAGE = "RIGHT CLICK"
    else:
        MOVEMENT_START = None
Exemple #50
0
import pyautogui

# move mouse to XY coordinates over num_second seconds
# 将鼠标移到XY坐标,花费x秒
pyautogui.moveTo(x, y, duration=num_seconds)

# move mouse relative to its current position
# 相对于当前位置移动鼠标,花费x秒
pyautogui.moveRel(xOffset, yOffset, duration=num_seconds)

# 将鼠标拖动到XY
pyautogui.dragTo(x, y, duration=num_seconds)

# 相对于当前位置拖动鼠标
pyautogui.dragRel(xOffset, yOffset, duration=num_seconds)

# Calling click() just clicks the mouse once with the left button at the mouse’s current location, but the keyword arguments can change that:
# 调用click()只需在鼠标的当前位置用左键单击鼠标一次,但关键字参数可以更改:
# The button keyword argument can be 'left', 'middle', or 'right'.
pyautogui.click(x=moveToX,
                y=moveToY,
                clicks=num_of_clicks,
                interval=secs_between_clicks,
                button='left')

# All clicks can be done with click(), but these functions exist for readability. Keyword args are optional:
# 所有点击都可以用Clice()完成,但是这些函数存在可读性。关键字参数是可选的:
pyautogui.rightClick(x=moveToX, y=moveToY)
pyautogui.middleClick(x=moveToX, y=moveToY)
pyautogui.doubleClick(x=moveToX, y=moveToY)
pyautogui.tripleClick(x=moveToX, y=moveToY)
Exemple #51
0
def play(pl):
    for i, f in enumerate(pl):
        print(i, f)
        pyautogui.moveRel(-1 if i % 2 else 1, 0)
        os.system("mpg123 " + full_path(f[0]))
        time.sleep(f[1])
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

            # compute the convex hull for the left and right eye, then
            # visualize each of the eyes
            leftEyeHull = cv2.convexHull(leftEye)
            rightEyeHull = cv2.convexHull(rightEye)
            leftBrowHull = cv2.convexHull(leftBrow)
            rightBrowHull = cv2.convexHull(rightBrow)
            cv2.drawContours(frame, [leftBrowHull], -1, (0, 255, 0), 1)
            cv2.drawContours(frame, [rightBrowHull], -1, (0, 255, 0), 1)
            cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
            cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

            mousex = int((mtx - mx) * 3)
            mousey = int((mty - my) * 1.5)
            pyautogui.moveRel(mousex, mousey, duration=.05)

            # check to see if the eye aspect ratio is below the blink
            # threshold, and if so, increment the blink frame counter
            if ear < EYE_CLOSE_THRESH:
                LCOUNTER += 1

            else:
                if LCOUNTER >= EYE_CLOSE_CONSEC_FRAMES:
                    LTOTAL += 1
                    pyautogui.click(pyautogui.position(), button="left")
                LCOUNTER = 0

            if avgdist > EYE_OPEN_THRESH:
                RCOUNTER += 1
            else:
    def test_moveRel(self):
        # NOTE - The user moving the mouse during this test will cause it to fail.

        # start at 1,1
        pyautogui.moveTo(1, 1)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (1, 1), 'mousepos set to %s' % (mousepos,))

        # move down and right
        pyautogui.moveRel(4, 4)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (5, 5), 'mousepos set to %s' % (mousepos,))

        # move up and left
        pyautogui.moveRel(-4, -4)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (1, 1), 'mousepos set to %s' % (mousepos,))

        # move right
        pyautogui.moveRel(4, None)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (5, 1), 'mousepos set to %s' % (mousepos,))

        # move down
        pyautogui.moveRel(None, 4)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (5, 5), 'mousepos set to %s' % (mousepos,))

        # move left
        pyautogui.moveRel(-4, None)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (1, 5), 'mousepos set to %s' % (mousepos,))

        # move up
        pyautogui.moveRel(None, -4)
        mousepos = pyautogui.position()
        self.assertTrue(mousepos == (1, 1), 'mousepos set to %s' % (mousepos,))
Exemple #54
0
    into = findel("Настройки базы данных")
    into.send_keys(Keys.CONTROL + '192.168.0.3')
    pyautogui.keyDown(key='tab')
    into.send_keys(Keys.CONTROL + '3306')
    pyautogui.keyDown(key='tab')
    into.send_keys(Keys.CONTROL + 'p17_testspb')
    findel_click('ОК')

    # Подключение
    driver.find_element_by_name('Сессия').click()
    driver.find_element_by_name('Подключиться к базе данных').click()

    # Вход
    registration = driver.find_element_by_name('Регистрация')
    registration.find_element_by_name('Имя').click()
    pyautogui.moveRel(None, -5)
    pyautogui.click()
    registration.send_keys(Keys.CONTROL + 'Виста')
    registration.find_element_by_name('ОК').click()

    # Установка умолчаний
    driver.find_element_by_name("Настройки").click()
    driver.find_element_by_name('Умолчания').click()

    driver.find_element_by_name("...").click()

    driver.find_element_by_name('Код ИНФИС').click()
    organization_choice = driver.find_element_by_name('Выбор организации ')
    pyautogui.moveRel(100, None)
    pyautogui.click()
    organization_choice.send_keys('о25')
Exemple #55
0
 def move_cursor_click(x, y):
     pyautogui.moveRel(x, y)
     pyautogui.click()
Exemple #56
0
def startClient():
    mouseSensitivity = 1.2  # tolerance for magnetic field fluctuation
    scrollSensitivity = 10.0  # number of clicks to scroll
    isOn = 0

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((HOST, PORT))
    print("Starting client...")

    while True:
        data, addr = s.recvfrom(1024)
        command = int(data[0])

        # move the mouse
        if command == 0:
            coords = struct.unpack('<3d', data[1:])
            azimuthZ = coords[0]
            pitchX = coords[1]
            rollY = coords[2]
            if azimuthZ > 180:
                azimuthZ -= 360
            if abs(azimuthZ) > 5 or abs(pitchX) > 5:
                pyautogui.moveRel(azimuthZ * mouseSensitivity,
                                  pitchX * (mouseSensitivity - 0.5))

        # click
        elif command == 1:
            numClicks = int(data[1])
            isRight = (data[2])
            if isRight == 0:
                button = 'left'
            elif isRight == 1:
                button = 'right'
            pyautogui.click(button=button, clicks=numClicks)

        # scroll
        elif command == 2:
            upDown = int(data[1])
            isHor = int(data[2])  # default 0
            if isHor == 0:
                pyautogui.scroll(direction * scrollSensitivity)
            else:
                pyautogui.hscroll(direction * scrollSensitivity)

        # hold/select
        elif command == 3:
            if isOn == 0:
                isOn = 1
                pyautogui.mouseDown()
            else:
                isOn = 0
                pyautogui.mouseUp()

        # calibrate cursor
        elif command == 4:
            centerX = pyautogui.size()[0] / 2
            centerY = pyautogui.size()[1] / 2
            pyautogui.moveTo(centerX, centerY, 0.05)

        # change sensitivity; Should we include possibility for double/half etc.?
        elif command == 5:
            isScroll = int(data[1])  # default 0 set by andriod service
            isMult = int(data[2])
            isDec = int(data[3])
            number = int(data[4])
            if isMult == 0:
                if isScroll == 0:
                    mouseSensitivity = mouseSensitivity + number
                else:
                    scrollSensitivity = scrollSensitivity + number
            else:
                if isDec == 0:
                    if isScroll == 0:
                        mouseSensitivity = mouseSensitivity * number
                    else:
                        scrollSensitivity = scrollSensitivity * number
                else:
                    if isScroll == 0:
                        mouseSensitivity = mouseSensitivity / number
                    else:
                        scrollSensitivity = scrollSensitivity / number

        # write stuff
        elif command == 6:
            string = data[1:].decode("utf-8")
            pyautogui.typewrite(string)

        # hotkeys
        # ['accept', 'add', 'alt', 'altleft', 'altright', 'apps', 'backspace', 'browserback', 'browserfavorites', 'browserforward', 'browserhome', 'browserrefresh', 'browsersearch', 'browserstop', 'capslock', 'clear', 'convert', 'ctrl', 'ctrlleft', 'ctrlright', 'decimal', 'del', 'delete', 'divide', 'down', 'end', 'enter', 'esc', 'escape', 'execute', 'f1', 'f10', 'f11', 'f12', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'final', 'fn', 'hanguel', 'hangul', 'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack', 'nonconvert', 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6','num7', 'num8', 'num9', 'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select', 'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'space', 'stop', 'subtract', 'tab', 'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command', 'option', 'optionleft', 'optionright']
        elif command == 7:
            operation = data[1:].decode("utf-8")
            pyautogui.keyDown(operation)

        # keyboard shortcuts
        # ['copy', 'paste', 'cut', 'undo', 'redo', 'tabs', 'desktopright', 'desktopleft', 'desktopnew', 'gohome']
        elif command == 8:
            operation = data[1:].decode("utf-8")
            if operation == 'copy':
                pyautogui.hotkey('ctrl', 'c')
            elif operation == 'find':
                pyautogui.hotkey('ctrl', 'f')
            elif operation == 'switchtab':
                pyautogui.hotkey('ctrl', 'tab')
            elif operation == 'paste':
                pyautogui.hotkey('ctrl', 'v')
            elif operation == 'cut':
                pyautogui.hotkey('ctrl', 'x')
            elif operation == 'undo':
                pyautogui.hotkey('ctrl', 'z')
            elif operation == 'redo':
                pyautogui.hotkey('ctrl', 'y')
            elif operation == 'tabs':
                pyautogui.hotkey('win', 'tab')
            elif operation == 'desktopright':
                pyautogui.hotkey('win', 'shift', 'right')
            elif operation == 'desktopleft':
                pyautogui.hotkey('win', 'shift', 'left')
            elif operation == 'desktopnew':
                pyautogui.hotkey('win', 'ctrl', 'd')
            elif operation == 'gohome':
                pyautogui.hotkey('win', 'd')
            elif operation == 'close':
                pyautogui.hotkey('alt', 'f4')
            elif operation == 'fullscreen':
                pyautogui.hotkey('alt', 'enter')

        # open application
        # eg. ['chrome', 'chromium']
        elif command == 9:
            operation = data[1:].decode("utf-8")
            #if os.name == 'nt': #Windows
            #    operation = "start " + operation
            #    os.system(operation)
            #elif os.name == 'posix': #Linux/macOS
            #    os.system(operation)
            if (operation == 'browser.open'):
                webbrowser.open('https://google.com')
            elif (operation == 'browser.drive'):
                webbrowser.open('https://drive.google.com')
            elif (operation == 'browser.gmail'):
                webbrowser.open('https://gmail.com')
            elif (operation == 'browser.newtab'):
                webbrowser.open_new_tab('https://google.com')

        # run commands in terminal
        elif command == 10:
            operation = data[1:].decode("utf-8")
            os.system(operation)

    s.close()
Exemple #57
0
def automate_waypoints():
    """
    This is the main automating script of the MSS waypoints tutorial which will be recorded and saved
    to a file having dateframe nomenclature with a .mp4 extension(codec).
    """
    # Giving time for loading of the MSS GUI.
    pag.sleep(15)

    # Maximizing the window
    try:
        if platform == 'linux' or platform == 'linux2':
            pag.hotkey('winleft', 'up')
        elif platform == 'darwin':
            pag.hotkey('ctrl', 'command', 'f')
        elif platform == 'win32':
            pag.hotkey('win', 'up')
    except Exception:
        print("\nException : Enable Shortcuts for your system or try again!")
    pag.sleep(2)
    pag.hotkey('ctrl', 'h')
    pag.sleep(5)

    # Adding waypoints
    try:
        x, y = pag.locateCenterOnScreen('pictures/add_waypoint.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\nException : Clickable button/option not found on the screen.")
    pag.move(-50, 150, duration=1)
    pag.click(interval=2)
    pag.sleep(1)
    pag.move(65, 65, duration=1)
    pag.click(interval=2)
    pag.sleep(1)

    pag.move(-150, 30, duration=1)
    x1, y1 = pag.position()
    pag.click(interval=2)
    pag.sleep(1)
    pag.move(200, 150, duration=1)
    pag.click(interval=2)
    x2, y2 = pag.position()
    pag.sleep(3)

    # Moving waypoints
    try:
        x, y = pag.locateCenterOnScreen('pictures/move_waypoint.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print(
            "\n Exception : Move Waypoint button could not be located on the screen"
        )

    pag.moveTo(x2, y2, duration=1)
    pag.click(interval=2)
    pag.dragRel(100, 150, duration=1)
    pag.moveTo(x1, y1, duration=1)
    pag.dragRel(35, -50, duration=1)
    x1, y1 = pag.position()

    # Deleting waypoints
    try:
        x, y = pag.locateCenterOnScreen('pictures/remove_waypoint.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print(
            "\n Exception : Remove Waypoint button could not be located on the screen"
        )
    pag.moveTo(x1, y1, duration=1)
    pag.click(duration=1)
    pag.press('left')
    pag.sleep(3)
    if platform == 'linux' or platform == 'linux2' or platform == 'win32':
        pag.press('enter', interval=1)
    elif platform == 'darwin':
        pag.press('return', interval=1)
    pag.sleep(2)

    # Changing map to Global
    try:
        if platform == 'linux' or platform == 'linux2' or platform == 'darwin':
            x, y = pag.locateCenterOnScreen('pictures/europe(cyl).PNG')
            pag.click(x, y, interval=2)
        elif platform == 'win32':
            x, y = pag.locateCenterOnScreen('pictures/europe(cyl)win.PNG')
            pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print(
            "\n Exception : Map change dropdown could not be located on the screen"
        )
    pag.press('down', presses=2, interval=0.5)
    if platform == 'linux' or platform == 'linux2' or platform == 'win32':
        pag.press('enter', interval=1)
    elif platform == 'darwin':
        pag.press('return', interval=1)
    pag.sleep(5)

    # Zooming into the map
    try:
        x, y = pag.locateCenterOnScreen('pictures/zoom.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\n Exception : Zoom button could not be located on the screen")
    pag.move(150, 200, duration=1)
    pag.dragRel(400, 250, duration=2)
    pag.sleep(5)

    # Panning into the map
    try:
        x, y = pag.locateCenterOnScreen('pictures/pan.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\n Exception : Pan button could not be located on the screen")
    pag.moveRel(400, 400, duration=1)
    pag.dragRel(-100, -50, duration=2)
    pag.sleep(5)

    pag.move(-20, -25, duration=1)
    pag.dragRel(90, 50, duration=2)
    pag.sleep(5)

    # Switching to the previous appearance of the map
    try:
        x, y = pag.locateCenterOnScreen('pictures/previous.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print(
            "\n Exception : Previous button could not be located on the screen"
        )
    pag.sleep(5)

    # Switching to the next appearance of the map
    try:
        x, y = pag.locateCenterOnScreen('pictures/next.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\n Exception : Next button could not be located on the screen")
    pag.sleep(5)

    # Resetting the map to the original size
    try:
        x, y = pag.locateCenterOnScreen('pictures/home.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\n Exception : Home button could not be located on the screen")
    pag.sleep(5)

    # Saving the figure
    try:
        x, y = pag.locateCenterOnScreen('pictures/save.PNG')
        pag.click(x, y, interval=2)
    except ImageNotFoundException:
        print("\n Exception : Save button could not be located on the screen")
    current_time = datetime.datetime.now().strftime('%d-%m-%Y %H-%M-%S')
    fig_filename = f'Fig_{current_time}.PNG'
    pag.sleep(3)
    if platform == 'win32':
        pag.write(fig_filename, interval=0.25)
        pag.press('enter', interval=1)
    if platform == 'linux' or platform == 'linux2':
        pag.hotkey(
            'altleft', 'tab'
        )  # if the save file system window is not in the forefront, use this statement.
        # This can happen sometimes. At that time, you just need to uncomment it.
        pag.write(fig_filename, interval=0.25)
        pag.press('enter', interval=1)
    elif platform == 'darwin':
        pag.write(fig_filename, interval=0.25)
        pag.press('return', interval=1)

    print(
        "\nAutomation is over for this tutorial. Watch next tutorial for other functions."
    )

    # Close Everything!
    try:
        if platform == 'linux' or platform == 'linux2':
            for _ in range(2):
                pag.hotkey('altleft', 'f4')
                pag.sleep(3)
                pag.press('left')
                pag.sleep(3)
                pag.press('enter')
                pag.sleep(2)
            pag.keyDown('altleft')
            pag.press('tab')
            pag.press('left')
            pag.keyUp('altleft')
            pag.press('q')
        if platform == 'win32':
            for _ in range(2):
                pag.hotkey('alt', 'f4')
                pag.sleep(3)
                pag.press('left')
                pag.sleep(3)
                pag.press('enter')
                pag.sleep(2)
            pag.hotkey('alt', 'tab')
            pag.press('q')
        elif platform == 'darwin':
            for _ in range(2):
                pag.hotkey('command', 'w')
                pag.sleep(3)
                pag.press('left')
                pag.sleep(3)
                pag.press('return')
                pag.sleep(2)
            pag.hotkey('command', 'tab')
            pag.press('q')
    except Exception:
        print(
            "Cannot automate : Enable Shortcuts for your system or try again")
    pag.press('q')
Exemple #58
0
def MoveRelative(x=None, y=None):
    '''
    Moves the mouse an x- and y- distance relative to its current pixel position.
    '''
    return pyautogui.moveRel(x, y)
Exemple #59
0
if __name__ == '__main__':
    region = {}
    units = ('tanneur', 'chevrier_1', 'chevrier_2', 'forgeron', 'fruitier')
    prod = { 'tanneur' : 'peau de chèvre', 'chevrier_1' : '1/6 fromage',
             'chevrier_2' : '1/6 fromage', 'forgeron' : 'fer à cheval',
             'fruitier' : 'choux'
           }

    while True:
        for unit in units:
            detect_state(unit, region)

        for key in region:
            if region[key] is not None:
                pyautogui.moveTo(pyautogui.center(region[key]))
                pyautogui.moveRel(None, 10)
                clickAndForget()
                region[key] = None
                if key.endswith('_ready'):
                    unit = key.split('_ready')[0]
                    print('[{} / {}] Récupération ressources'.format(time.strftime('%H:%M:%S'),
                                                                     unit))
                elif key.endswith('_wait'):
                    unit = key.split('_wait')[0]
                    print('[{} / {}] Ordre de fabrication'.format(time.strftime('%H:%M:%S'),
                                                                  unit))
                    region_2 = None
                    while region_2 is None:
                        unitType = unit.split('_')[0]
                        region_2 = pyautogui.locateOnScreen('images/' + unitType +'_prod.png')
                        if region_2 is not None:
 def move(self, x, y):
     pyautogui.moveRel(x * self.precision,
                       -1 * y * self.precision,
                       duration=self.speed)