コード例 #1
0
def layout_switch(switch_combination, attempts=5):
    logging.info('Switching layout...')
    user32 = windll.user32
    cur_hwnd = GetForegroundWindow()
    cur_pid = user32.GetWindowThreadProcessId(cur_hwnd, None)  # Получаем pid процесса
    current_lang = GetKeyboardLayout(cur_pid)  # Получаем раскладку по pid
    for i in range(attempts):
        keyboard.send(switch_combination)
        sleep(0.25)
        if current_lang != GetKeyboardLayout(cur_pid):
            logging.info('Layout switching successfull...')
            return
    logging.info('Layout switching NOT switched. Check your settings.')
コード例 #2
0
def main():
    comb = options['switch_combination']
    keyboard.send('ctrl+c')
    sleep(0.05)
    data = copy()
    if data == None:
        logging.error('Nothing to convert')
        return
    logging.debug('String to convert:\t{}'.format(data))
    result = paste(data)
    # sleep(0.05)
    logging.debug('Converted string:\t{}'.format(result))
    if comb: layout_switch(comb)
    sleep(0.05)
    keyboard.send('ctrl+v')
    sleep(0.05)
    clean_clipboard()
    return
コード例 #3
0
def combination_definition():
    logging.info('Defining switch combination...')
    user32 = windll.user32
    cur_hwnd = GetForegroundWindow()
    cur_pid = user32.GetWindowThreadProcessId(cur_hwnd, None)  # Получаем pid процесса
    current_lang = GetKeyboardLayout(cur_pid)  # Получаем раскладку по pid
    combinations = (('ctrl+shift'), ('alt+shift'), ('alt+shift+ctrl'))
    #    logging.debug('\nUser32: {}\nhwnd: {}\nPID: {}\nLang: {}'.format(user32, cur_hwnd, cur_pid, current_lang))
    for comb in combinations:
        keyboard.send(comb)
        sleep(0.1)
        if 'alt' in comb: keyboard.send('alt')  # Нажимаем Alt снова, если он есть в комбинации
        if current_lang != GetKeyboardLayout(cur_pid):
            logging.debug('Switch combination found: {}'.format(comb))
            keyboard.send(comb)
            return comb
    return None
コード例 #4
0
def comb_check(comb):
    logging.info('Checking switch combination...')
    try:
        if not comb:
            return False
        user32 = windll.user32
        cur_hwnd = GetForegroundWindow()
        cur_pid = user32.GetWindowThreadProcessId(cur_hwnd, None)  # Получаем pid процесса для текущего юзера
        current_lang = GetKeyboardLayout(cur_pid)  # Получаем раскладку по pid
        keyboard.send(comb)
        sleep(0.1)
        if 'alt' in comb: keyboard.send('alt')  # Нажимаем Alt снова, если он есть в комбинации
        if current_lang != GetKeyboardLayout(cur_pid):
            keyboard.send(comb)
            return True
        else:
            return False
    except ValueError:
        logging.error('An error occured while checking switch combination', exc_info=True)
        return False
コード例 #5
0
 def test_send_modifier_press_release(self):
     keyboard.send('ctrl+a', do_press=True, do_release=True)
     self.do([], d_ctrl + d_a + u_a + u_ctrl)
コード例 #6
0
 def test_send_single_release(self):
     keyboard.send('a', do_press=False, do_release=True)
     self.do([], u_a)
def main():
    global posts, url, load_time, version_no
    reddit_flag = 0
    detail_flag = 0
    print ("\t\t\t\t\t\t\t  CODE BY @outcastdreamer on Github. \n\t\t\t\t\t\t\t\t   Version_No :",version_no)
    print ("\t\t\t\t\t\t+++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    print ("\n\n\t\tPLEASE MAKE SURE YOU ARE LOGGED IN TO \"web.whatsapp.com\" & HAVE SCANNED THE QR CODE!!\n\n")
    while True:
        pin = input("\nPlease enter the country code (Eg: +91, +1, etc) :\n\n\tKindly make sure Plus (+) symbol is there in the beginning of pincode : ")
        
        num = input("\tEnter the Mobile No. to send message to : ")
        opp_count = int(input("\tEnter the No. of messages to send : "))
        final = opp_count
        if pin[0] != "+":
            pin = "+" + pin
        if pin == "+91":
            if len(num) != 10:
                print ("\n\n\t\tERROR!! WRONG NUMBER!! THERE ARE LESS THAN 10 DIGITS!! TRY AGAIN!\n\n")
                detail_flag = 1
            else:
                detail_flag = 0
        if detail_flag != 1:
            f_num = pin+num
            print ("\n\n")
            print ("\t\t\t\t\tDETAILS : ")
            print ("\t\t\tPhone Number : ",f_num)
            print ("\t\t\tNo. of Messages to send : ",opp_count,"\n")
            choice = input("\nAre the following details correct? Please check & enter 'Y' for yes, 'N' for no : ")
            if choice.lower()=="y":
                break
        else:
            pass

    ##################

    reddit_checker = input("\n\n  Do you want to use the Reddit API (in case Reddit API details have not been set)? Type 'Y' to include Reddit API or 'N'for no : ")
    if reddit_checker.lower() == "y":
        reddit_flag = 1
        red()
    else:
        string = input("\n\tEnter the string you want to send to the user : "******"%H:%M")

    ##################

    while keyboard.is_pressed("q")==False:

        if count >= final:
            print ("\t\t\t\t\t\t\t--x--------------END OF EXECUTION--------------x--\n\n\n\n")
            break

        while count < final:
            now = datetime.now()
            current_time = now.strftime("%H:%M")
            m = int(current_time[-2:])+2

            ##################
            if reddit_flag == 1:
                s = r.choice(posts)
                index = posts.index(s)
                posts.pop(index)
                url_index = url[index]
                url.pop(index)
            ##################

            browser()

            print ("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
            print ("\n\nThe Current time is : ",current_time)
            hr = current_time[0:2]
            mn = int(current_time[-2:])+6

            if len(str(mn))==1:
                mn = "0"+str(mn)
                flag = 1

            if flag == 1:
                pass
            else:
                if int(mn) == 60:
                    mn = "00"
                    hr = int(hr)+1
                    if hr>23:
                        hr = "00"
                    if len(str(hr))==1:
                        hr = "0"+str(hr)
                    hr = str(hr)
                    flag = 2

            if flag == 2:
                pass
            else:
                if int(mn) > 60:
                    mn = "0"+str(mn%60)
                    hr = int(hr)+1
                    if hr>23:
                        hr = "00"
                    if len(str(hr))==1:
                        hr = "0"+str(hr)
                    hr = str(hr)

            t = str(hr)+":"+str(mn)
            flag = 0

            ################
            if reddit_flag == 1:
                if final == 1:
                    
                    string = """*----*%0aHi!!%0a%0aThis is an Automated Horror bot!!%0aI am currently sharing a randomly retrieved Short Horror Story from r/TwoSentenceHorror on Reddit.%0aHere's the story I have randomly retrieved : %0a%0a*----------------------------------------*%0a%0a_{0}_%0a%0a*---------------------------------------*%0a%0aTo view the whole post on reddit, click on : %0a{1}%0a%0aI hope you like it!!%0a%0aFeel free to checkout this project on github at : %0a{2}%0a%0aI hope you have a good day.%0aByeeee!!!%0a*--x----x--x----x--*""".format(s,url_index,"http://bit.ly/Automated_Whatsapp_Reddit")
                    post_flag = 1

                if count == 0 and final != 1:
                    
                    opp_count-=1
                    string = """*----*%0aHi!!%0a%0aThis is an Automated Horror bot!! %0aI am currently sharing a randomly retrieved Short Horror Story from r/TwoSentenceHorror on Reddit.%0aHere's the story I have randomly retrieved : %0a%0a*----------------------------------------*%0a%0a_{0}_%0a%0a*---------------------------------------*%0a%0aTo view the whole post on reddit, click on : %0a{1}%0a%0aI hope you like it!!%0a%0aMy next message will reach by {2} Hrs approx.!%0aThis bot will run for {3} more times!!%0a%0a""".format(s,url_index,t,opp_count)

                else:
                    if opp_count!=1:
                     
                        opp_count-=1
                        if opp_count == 1:
                            string = """*----*%0aAutomated Horror Bot Here!!%0a%0aTime for the story I have randomly retrieved : %0a%0a*----------------------------------------*%0a%0a_{0}_%0a%0a*---------------------------------------*%0a%0aTo view the whole post on reddit, click on : %0a{1}%0a%0aI hope you like it!!%0a%0aMy next message will reach by {2} Hrs approx.!%0aThis bot will run for {3} more time!!""".format(s,url_index,t,opp_count)
                            
                        else:
                            string = """*----*%0aAutomated Horror Bot Here!!%0a%0aTime for the story I have randomly retrieved : %0a%0a*----------------------------------------*%0a%0a_{0}_%0a%0a*---------------------------------------*%0a%0aTo view the whole post on reddit, click on : %0a{1}%0a%0aI hope you like it!!%0a%0aMy next message will reach by {2} Hrs approx.!%0aThis bot will run for {3} more times!!""".format(s,url_index,t,opp_count)
                    
                    elif opp_count==1 and post_flag != 1:
                        string = """*----*%0aAutomated Horror Bot Here for the last time :(%0a%0aTime for the story I have randomly retrieved : %0a%0a*----------------------------------------*%0a%0a_{0}_%0a%0a*---------------------------------------*%0a%0aTo view the whole post on reddit, click on : %0a{1}%0a%0aI hope you like it!!%0a%0aFeel free to checkout this project on github at : %0a{2}%0a%0aSorry for all the spam. I hope you have a good day.%0aByeeee!!!%0a*--x----x--x----x--*""".format(s,url_index,"http://bit.ly/Automated_Whatsapp_Reddit")                 
         
            try:
                count += 1
                time.sleep(2)

                ####################################################
                sendwhatmsg(f_num,string,int(current_time[:2]),m)
                ####################################################

                time.sleep(load_time)
                #click(1274,685)
                keyboard.send("enter")
                time.sleep(3)
                keyboard.send("enter")
                print("\n\t--Message has been sent!!--")
                time.sleep(7)
                keyboard.send("ctrl+F4")
                print ("\t--Whatsapp has been closed!!--")

                ################
                now = datetime.now()
                current_time = now.strftime("%H:%M")
                print ("\nNo. of messages sent : ",count,"\nMessage Sent at : ",current_time,"\n----\n")
                if count >= final:
                    break
                else:
                    print ("Initiating pause of 100 seconds!\n")
                    time.sleep(100)
                    print ("Sleep Time is over!!\n")
            
            except:
                now = datetime.now()
                current_time = now.strftime("%H:%M")
                print("\n\n+++++++++++++++++++++++++++++")
                print("\t\t!!!EXCEPTION CAUGHT!!!\n\n")
                time.sleep(2)

                ####################################################
                sendwhatmsg(f_num,string,int(current_time[:2]),m+1)
                ####################################################

                time.sleep(load_time)
                keyboard.send("enter")
                time.sleep(3)
                keyboard.send("enter")
                #click(1274,685)
                print("\n--Message has been sent!!--")
                time.sleep(7)
                keyboard.send("ctrl+F4")
                print ("--Whatsapp has been closed!!--")
                ################
                now = datetime.now()
                current_time = now.strftime("%H:%M")
                print ("\nNo. of messages sent : ",count,"\nMessage Sent at : ",current_time,"\n----\n")
                if count >= final:
                    break
                else:
                    print ("\nInitiating pause of 100 seconds!\n")
                    time.sleep(100)
                    print ("Sleep Time is over!!\n")
コード例 #8
0
def inject_keys(key: str, after_delay=0.0):
    """Inject a key combination into the Freelancer window."""
    assert window.is_foreground()
    time.sleep(after_delay)
    keyboard.send(key)
コード例 #9
0
ファイル: code.py プロジェクト: boyonkgit/tf2-bot-kicker
def execute():
    if len(commands) > 0:
        create_bk_execute()
        sleep(1)
        keyboard.send(execute_keybind)
コード例 #10
0
def left():
    #sleep();
    print("Left Triggered! go left")
    keyboard.send('windows, left', True, False)
コード例 #11
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def test_send_modifier_press_release(self):
     keyboard.send('ctrl+a', do_press=True, do_release=True)
     self.do([], d_ctrl+d_a+u_a+u_ctrl)
コード例 #12
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def test_send_single_none(self):
     keyboard.send('a', do_press=False, do_release=False)
     self.do([], [])
コード例 #13
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def test_send_single_release(self):
     keyboard.send('a', do_press=False, do_release=True)
     self.do([], u_a)
コード例 #14
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def test_send_single_press(self):
     keyboard.send('a', do_press=True, do_release=False)
     self.do([], d_a)
コード例 #15
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
    def test_send(self):
        keyboard.send("shift", True, False)
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "shift")])

        keyboard.send("a")
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "a"), (KEY_UP, "a")])

        keyboard.send("a, b")
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "a"), (KEY_UP, "a"), (KEY_DOWN, "b"), (KEY_UP, "b")])

        keyboard.send("shift+a, b")
        self.assertEqual(
            self.flush_events(),
            [(KEY_DOWN, "shift"), (KEY_DOWN, "a"), (KEY_UP, "a"), (KEY_UP, "shift"), (KEY_DOWN, "b"), (KEY_UP, "b")],
        )

        self.press("a")
        keyboard.write("a", restore_state_after=False, delay=0.001)
        # TODO: two KEY_UP 'a' because the tests are not clearing the pressed
        # keys correctly, it's not a bug in the keyboard module itself.
        self.assertEqual(self.flush_events(), [(KEY_UP, "a"), (KEY_UP, "a"), (KEY_DOWN, "a"), (KEY_UP, "a")])

        shift_scan_code = scan_codes_by_name["shift"]

        keyboard.send(shift_scan_code, True, False)
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "shift")])
        keyboard.send([[shift_scan_code]], True, False)
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "shift")])
        keyboard.send([["shift"]], True, False)
        self.assertEqual(self.flush_events(), [(KEY_DOWN, "shift")])
コード例 #16
0
def pressKey():
    keyboard.send('space')
コード例 #17
0
# Imports
import keyboard
from time import sleep
import requests

pressEnter = True
sleeptime = int(input('Time between insults\n> '))

print('Starting in 5 seconds...')
sleep(5)

while True:
    text = requests.get('https://insult.mattbas.org/api/insult').text
    # Keybord api hates uppercase
    text = text.lower()

    # Writes the text
    keyboard.write(text, delay=0.05)
    # If pressEnter = True then press enter after writing text.
    if pressEnter == True:
        # Slight delay because computers are not perfect
        sleep(0.3)
        keyboard.send('enter')
    sleep(sleeptime)
コード例 #18
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def test_send_modifiers_release(self):
     keyboard.send('ctrl+shift+a', do_press=False, do_release=True)
     self.do([], u_a+u_shift+u_ctrl)
コード例 #19
0
def up():
    sleep();
    print("UP Triggered! - zoom in")
    keyboard.send('windows,plus', True, False)
コード例 #20
0
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 6)

        cropped_face = frame[y:y + h, x:x + w]
        cropped_face_gray = gray[y:y + h, x:x + w]

        eyes = eye_cascade.detectMultiScale(cropped_face_gray, 1.1, 5)

        for (ex, ey, ew, eh) in eyes:
            curr_state = True
            cv2.rectangle(cropped_face, (ex, ey), (ex + ew, ey + eh),
                          (0, 255, 0), 2)

        if prev_state == False and curr_state == True:
            keyboard.send('command+t')  # resume

        if prev_state == True and curr_state == False:
            keyboard.send('command+p')  # pause

    cv2.imshow('Face detection', cv2.resize(frame, (300, 200)))
    #cv2.imshow('Face detection', frame)

    k = cv2.waitKey(10)

    if k == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break
コード例 #21
0
ファイル: code.py プロジェクト: boyonkgit/tf2-bot-kicker
def query():
    keyboard.send(query_keybind)
コード例 #22
0
import keyboard
import time


def idle(x, text=""):
    for i in range(x):
        print(text + str(x - i))
        time.sleep(1)


idle(2, "starting in ")
for i in range(50):
    keyboard.send("ctrl+shift+n")
    time.sleep(1)
    #keyboard.send("ctrl+v")
    keyboard.write("https://trovo.live/Wumbo?adtag=user.VonFriedricht.clip")
    keyboard.send("enter")
    time.sleep(8)
    keyboard.send("ctrl+w")
    time.sleep(1)
コード例 #23
0
 def setup_method(self, method):
     self.driver = webdriver.Chrome()
     self.driver.get('chrome://settings/clearBrowserData')
     time.sleep(10)
     keyboard.send("Enter")
     self.vars = {}
コード例 #24
0
def apply_to_mv(deposit_df):
    pyautogui.click(m3['tour_packages'])
    pyautogui.click(m3['deposit_1'])
    pyautogui.click(m3['change_deposit'])
    deposit_item_amount = count_items_in_deposit()
    sc.get_m6_coordinates()
    x, y = m6['deposit_1']
    y = y + 13 * (deposit_item_amount - 1)
    pyautogui.click(x, y)
    keyboard.send('alt + v')
    sc.get_m7_coordinates()
    pyautogui.doubleClick(m7['reference'])
    keyboard.press_and_release('ctrl + c')
    time.sleep(0.5)
    old_reference = clipboard.paste()
    old_reference = old_reference.upper()
    if old_reference[0] != 'D':
        sys.exit("Wrong Reference")
    new_reference = old_reference.replace("D-", "U-")
    clipboard.copy(str(new_reference))
    pyautogui.click(m7['cancel'])
    sc.get_m6_coordinates()
    pyautogui.click(m6['description'])
    keyboard.send('ctrl + z')
    keyboard.send('ctrl + c')
    r = Tk()
    old_description = r.selection_get(selection="CLIPBOARD")
    if 'AMS' in old_description:
        keyboard.write('AMS/Minivac')
    pyautogui.click(m6['payment'])
    sc.get_m8_coordinates()
    pyautogui.click(m8['transaction_code'])
    image = pyautogui.locateCenterOnScreen(
        'C:\\Users\\Jared.Abrahams\\Screenshots\\apply_to_mv.png',
        region=(136, 652, 392, 247))
    while image is None:
        image = pyautogui.locateCenterOnScreen(
            'C:\\Users\\Jared.Abrahams\\Screenshots\\apply_to_mv.png',
            region=(136, 652, 392, 247))
    pyautogui.click(image)
    pyautogui.click(m8['reference'])
    keyboard.write('APPLY TO MV')
    pyautogui.click(m8['ok'])
    time.sleep(0.3)
    pyautogui.click(880, 565)
    pyautogui.click(m6['payment'])
    sc.get_m8_coordinates()
    time.sleep(0.3)
    pyautogui.click(m8['transaction_code'])
    image = pyautogui.locateCenterOnScreen(
        'C:\\Users\\Jared.Abrahams\\Screenshots\\ams_credit_payment.png',
        region=(136, 652, 392, 247))
    while image is None:
        image = pyautogui.locateCenterOnScreen(
            'C:\\Users\\Jared.Abrahams\\Screenshots\\ams_credit_payment.png',
            region=(136, 652, 392, 247))
    pyautogui.click(image)
    pyautogui.doubleClick(m8['amount'])
    keyboard.write(deposit_df.Price[0])
    pyautogui.click(m8['reference'])
    keyboard.write(new_reference)
    cf.pause('Ok?')
    pyautogui.click(m8['ok'])
    sc.get_m6_coordinates()
    pyautogui.click(m6['ok'])
    print('Applied Refundable Deposit to Minivac')
    deposit_df.Deposit_Type[0] = 'Non_Refundable'
コード例 #25
0
 def sendChat(self, text="[Error] error"):
     self.__game.type_keys(text, with_spaces=True)
     sleep(0.2)
     self.__game.type_keys("{ENTER}")
     sleep(0.5)
     keyboard.send("t")
コード例 #26
0
        break

    prev_state = curr_state
    curr_state = False

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cropped_face = frame[y:y + h, x:x + w]
        cropped_face_gray = gray[y:y + h, x:x + w]
        eyes = eye_cascade.detectMultiScale(cropped_face_gray, 1.1, 5)
        for (ex, ey, ew, eh) in eyes:
            curr_state = True
            cv2.rectangle(cropped_face, (ex, ey), (ex + ew, ey + eh),
                          (0, 255, 0), 2)
        if prev_state == False and curr_state == True:
            keyboard.send('ctrl+shift+a')
        if prev_state == True and curr_state == False:
            keyboard.send('ctrl+shift+q')

    cv2.imshow('Face detection', frame)

    key_e = cv2.waitKey(10)
    win_e = cv2.getWindowProperty('Face detection', 1)
    if key_e == ord('q') or win_e == -1:
        cap.release()
        cv2.destroyAllWindows()
        break
コード例 #27
0
 def test_send_single_press(self):
     keyboard.send('a', do_press=True, do_release=False)
     self.do([], d_a)
コード例 #28
0
    # def changeSong():
    #     keyboard.send(-176)

    fired = 0

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        if x < 100:
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(frame, 'Next', (0, 200), font, 1, (200, 255, 155), 2,
                        cv2.LINE_AA)
            while fired == 0:
                fired += 1
                keyboard.send(-176)
                time.sleep(1)
                break
        # elif x > 100:
        #     fired += 1

        # while x > 300:
        #     if changeP == False:
        #         changeP = True
        #         break

    horizontal_img = cv2.flip(frame, 1)
    # Display the resulting frame
    cv2.imshow('Video', horizontal_img)

    # if changeP:
コード例 #29
0
 def test_send_single_none(self):
     keyboard.send('a', do_press=False, do_release=False)
     self.do([], [])
コード例 #30
0
ファイル: AutoSplit.py プロジェクト: snowshoe11/Auto-Split
    def autoSplitter(self):
        # error checking:
        if str(self.splitimagefolderLineEdit.text()) == 'No Folder Selected':
            self.guiChangesOnReset()
            self.splitImageDirectoryError()
            return
        if os.path.exists(self.splitimagefolderLineEdit.text()) == False:
            self.guiChangesOnReset()
            self.splitImageDirectoryNotFoundError()
            return
        if self.hwnd == 0 or win32gui.GetWindowText(self.hwnd) == '':
            self.guiChangesOnReset()
            self.regionError()
            return

        # get split image filenames
        self.split_image_filenames = os.listdir(self.split_image_directory)

        # Make sure that each of the images follows the guidelines for correct format
        # according to all of the settings selected by the user.
        for image in self.split_image_filenames:

            # Check to make sure the file is actually an image format that can be opened
            # according to the mask flag
            if split_parser.flags_from_filename(image) & 0x02 == 0x02:
                source = cv2.imread(self.split_image_directory + image,
                                    cv2.IMREAD_UNCHANGED)

                if source is None:
                    # Opencv couldn't open this file as an image, this isn't a correct
                    # file format that is supported
                    self.guiChangesOnReset()
                    self.imageTypeError(image)
                    return

                if source.shape[2] != 4:
                    # Error, this file doesn't have an alpha channel even
                    # though the flag for masking was added
                    self.guiChangesOnReset()
                    self.alphaChannelError(image)
                    return

            else:
                if cv2.imread(self.split_image_directory + image,
                              cv2.IMREAD_COLOR) is None:
                    # Opencv couldn't open this file as an image, this isn't a correct
                    # file format that is supported
                    self.guiChangesOnReset()
                    self.imageTypeError(image)
                    return

            #error out if there is a {p} flag but no pause hotkey set.
            if self.pausehotkeyLineEdit.text(
            ) == '' and split_parser.flags_from_filename(image) & 0x08 == 0x08:
                self.guiChangesOnReset()
                self.pauseHotkeyError()
                return

            if self.custompausetimesCheckBox.isChecked(
            ) and split_parser.pause_from_filename(image) is None:
                # Error, this file doesn't have a pause, but the checkbox was
                # selected for unique pause times
                self.guiChangesOnReset()
                self.customPauseError(image)
                return

            if self.customthresholdsCheckBox.isChecked(
            ) and split_parser.threshold_from_filename(image) is None:
                # Error, this file doesn't have a threshold, but the checkbox
                # was selected for unique thresholds
                self.guiChangesOnReset()
                self.customThresholdError(image)
                return

        if self.splitLineEdit.text() == '':
            self.guiChangesOnReset()
            self.splitHotkeyError()
            return

        # find reset image then remove it from the list
        self.findResetImage()

        # Check that there's only one reset image
        for image in self.split_image_filenames:

            if split_parser.is_reset_image(image):
                self.guiChangesOnReset()
                self.multipleResetImagesError()
                return

        # if there is no custom threshold for the reset image, throw an error.
        if self.reset_image is not None and self.reset_image_threshold is None:
            self.guiChangesOnReset()
            self.noResetImageThresholdError()
            return

        # If there is no reset hotkey set but a reset image is present, throw an error.
        if self.resetLineEdit.text() == '' and self.reset_image is not None:
            self.guiChangesOnReset()
            self.resetHotkeyError()
            return

        # construct groups of splits if needed
        self.split_groups = []
        if self.groupDummySplitsCheckBox.isChecked():
            current_group = []
            self.split_groups.append(current_group)

            for i, image in enumerate(self.split_image_filenames):
                current_group.append(i)

                flags = split_parser.flags_from_filename(image)
                if flags & 0x01 != 0x01 and i < len(
                        self.split_image_filenames) - 1:
                    current_group = []
                    self.split_groups.append(current_group)

        # construct dummy splits array
        self.dummy_splits_array = []
        for i, image in enumerate(self.split_image_filenames):
            if split_parser.flags_from_filename(image) & 0x01 == 0x01:
                self.dummy_splits_array.append(True)
            else:
                self.dummy_splits_array.append(False)

        # construct loop amounts for each split image
        self.split_image_loop_amount = []
        for i, image in enumerate(self.split_image_filenames):
            self.split_image_loop_amount.append(
                split_parser.loop_from_filename(image))

        if any(x > 1 for x in self.split_image_loop_amount
               ) and self.groupDummySplitsCheckBox.isChecked() == True:
            self.dummySplitsError()
            return

        self.guiChangesOnStart()

        # initialize some settings
        self.split_image_number = 0
        self.loop_number = 1
        self.number_of_split_images = len(self.split_image_filenames)
        self.waiting_for_split_delay = False
        self.split_below_threshold = False

        self.run_start_time = time.time()

        # First while loop: stays in this loop until all of the split images have been split
        while self.split_image_number < self.number_of_split_images:

            # Check if we are not waiting for the split delay to send the key press
            if self.waiting_for_split_delay == True:
                time_millis = int(round(time.time() * 1000))
                if time_millis < self.split_time:
                    QtGui.QApplication.processEvents()
                    continue

            self.updateSplitImage()

            # second while loop: stays in this loop until similarity threshold is met
            # skip loop if we just finished waiting for the split delay and need to press the split key!
            start = time.time()
            while True:
                # reset if the set screen region window was closed
                if win32gui.GetWindowText(self.hwnd) == '':
                    self.reset()

                # loop goes into here if start auto splitter text is "Start Auto Splitter"
                if self.startautosplitterButton.text(
                ) == 'Start Auto Splitter':
                    if self.autostartonresetCheckBox.isChecked():
                        self.startAutoSplitterSignal.emit()
                        return
                    else:
                        self.guiChangesOnReset()
                        return

                # calculate similarity for reset image
                reset_masked = None
                capture = None

                if self.shouldCheckResetImage():
                    reset_masked = (self.reset_mask is not None)
                    capture = self.getCaptureForComparison(reset_masked)

                    reset_similarity = self.compareImage(
                        self.reset_image, self.reset_mask, capture)
                    if reset_similarity >= self.reset_image_threshold:
                        keyboard.send(str(self.resetLineEdit.text()))
                        self.reset()

                # loop goes into here if start auto splitter text is "Start Auto Splitter"
                if self.startautosplitterButton.text(
                ) == 'Start Auto Splitter':
                    if self.autostartonresetCheckBox.isChecked():
                        self.startAutoSplitterSignal.emit()
                        return
                    else:
                        self.guiChangesOnReset()
                        return

                # get capture again if needed
                masked = (self.flags & 0x02 == 0x02)
                if capture is None or masked != reset_masked:
                    capture = self.getCaptureForComparison(masked)

                # calculate similarity for split image
                self.similarity = self.compareImage(self.split_image,
                                                    self.mask, capture)

                # show live similarity if the checkbox is checked
                if self.showlivesimilarityCheckBox.isChecked():
                    self.livesimilarityLabel.setText(str(self.similarity)[:4])
                else:
                    self.livesimilarityLabel.setText(' ')

                # if the similarity becomes higher than highest similarity, set it as such.
                if self.similarity > self.highest_similarity:
                    self.highest_similarity = self.similarity

                # show live highest similarity if the checkbox is checked
                if self.showhighestsimilarityCheckBox.isChecked():
                    self.highestsimilarityLabel.setText(
                        str(self.highest_similarity)[:4])
                else:
                    self.highestsimilarityLabel.setText(' ')

                # if its the last split image and last loop number, disable the skip split button
                if (self.split_image_number == self.number_of_split_images - 1
                        and self.loop_number == self.split_image_loop_amount[
                            self.split_image_number]
                    ) or (self.groupDummySplitsCheckBox.isChecked() == True
                          and self.dummy_splits_array[self.split_image_number:]
                          .count(False) <= 1):
                    self.skipsplitButton.setEnabled(False)
                else:
                    self.skipsplitButton.setEnabled(True)

                # if its the first split image and first loop, disable the undo split button
                if self.split_image_number == 0 and self.loop_number == 1:
                    self.undosplitButton.setEnabled(False)
                else:
                    self.undosplitButton.setEnabled(True)

                # if the b flag is set, let similarity go above threshold first, then split on similarity below threshold.
                # if no b flag, just split when similarity goes above threshold.
                if self.flags & 0x04 == 0x04 and self.split_below_threshold == False:
                    if self.waiting_for_split_delay == False and self.similarity >= self.similaritythresholdDoubleSpinBox.value(
                    ):
                        self.split_below_threshold = True
                        continue
                elif self.flags & 0x04 == 0x04 and self.split_below_threshold == True:
                    if self.waiting_for_split_delay == False and self.similarity < self.similaritythresholdDoubleSpinBox.value(
                    ):
                        self.split_below_threshold = False
                        break
                else:
                    if self.waiting_for_split_delay == False and self.similarity >= self.similaritythresholdDoubleSpinBox.value(
                    ):
                        break

                # limit the number of time the comparison runs to reduce cpu usage
                fps_limit = self.fpslimitSpinBox.value()
                time.sleep((1 / fps_limit) - (time.time() - start) %
                           (1 / fps_limit))
                QtGui.QApplication.processEvents()

            # comes here when threshold gets met

            # We need to make sure that this isn't a dummy split before sending
            # the key press.
            if (self.flags & 0x01 == 0x01):
                pass
            else:
                # If it's a delayed split, check if the delay has passed
                # Otherwise calculate the split time for the key press
                if self.split_delay > 0 and self.waiting_for_split_delay == False:
                    self.split_time = int(round(
                        time.time() * 1000)) + self.split_delay
                    self.waiting_for_split_delay = True
                    self.undosplitButton.setEnabled(False)
                    self.skipsplitButton.setEnabled(False)
                    self.currentsplitimagefileLabel.setText(' ')
                    self.currentSplitImage.setAlignment(QtCore.Qt.AlignCenter)

                    # check for reset while delayed and display a counter of the remaining split delay time
                    delay_start_time = time.time()
                    while time.time() - delay_start_time < (self.split_delay /
                                                            1000):
                        self.delay_time_left = str(
                            round((self.split_delay / 1000) -
                                  (time.time() - delay_start_time), 1))
                        self.currentSplitImage.setText('Delayed Split: ' +
                                                       self.delay_time_left +
                                                       ' sec remaining')
                        # check for reset
                        if win32gui.GetWindowText(self.hwnd) == '':
                            self.reset()
                        if self.startautosplitterButton.text(
                        ) == 'Start Auto Splitter':
                            if self.autostartonresetCheckBox.isChecked():
                                self.startAutoSplitterSignal.emit()
                                return
                            else:
                                self.guiChangesOnReset()
                                return

                        # calculate similarity for reset image
                        if self.shouldCheckResetImage() == True:
                            reset_masked = (self.reset_mask is not None)
                            capture = self.getCaptureForComparison(
                                reset_masked)

                            reset_similarity = self.compareImage(
                                self.reset_image, self.reset_mask, capture)
                            if reset_similarity >= self.reset_image_threshold:
                                keyboard.send(str(self.resetLineEdit.text()))
                                self.reset()
                                continue

                        QtTest.QTest.qWait(1)

                self.waiting_for_split_delay = False

                # if {p} flag hit pause key, otherwise hit split hotkey
                if (self.flags & 0x08 == 0x08):
                    keyboard.send(str(self.pausehotkeyLineEdit.text()))
                else:
                    keyboard.send(str(self.splitLineEdit.text()))

            # increase loop number if needed, set to 1 if it was the last loop.
            if self.loop_number < self.split_image_loop_amount[
                    self.split_image_number]:
                self.loop_number = self.loop_number + 1
            else:
                self.loop_number = 1

            # if loop check box is checked and its the last split, go to first split.
            # else if current loop amount is back to 1, add 1 to split image number
            # else pass, dont change split image number.
            if self.loopCheckBox.isChecked(
            ) and self.split_image_number == self.number_of_split_images - 1 and self.loop_number == 1:
                self.split_image_number = 0
            elif self.loop_number == 1:
                self.split_image_number = self.split_image_number + 1
            else:
                pass

            # set a "pause" split image number. This is done so that it can detect if user hit split/undo split while paused.
            pause_split_image_number = self.split_image_number
            pause_loop_number = self.loop_number

            # if its not the last split image, pause for the amount set by the user
            if self.number_of_split_images != self.split_image_number:
                # set current split image to none
                self.currentsplitimagefileLabel.setText(' ')
                self.currentSplitImage.setAlignment(QtCore.Qt.AlignCenter)
                self.imageloopLabel.setText('Image Loop #:     -')

                # if its the last split image and last loop number, disable the skip split button
                if (self.split_image_number == self.number_of_split_images - 1
                        and self.loop_number == self.split_image_loop_amount[
                            self.split_image_number]
                    ) or (self.groupDummySplitsCheckBox.isChecked() == True
                          and self.dummy_splits_array[self.split_image_number:]
                          .count(False) <= 1):
                    self.skipsplitButton.setEnabled(False)
                else:
                    self.skipsplitButton.setEnabled(True)

                # if its the first split image and first loop, disable the undo split button
                if self.split_image_number == 0 and self.loop_number == 1:
                    self.undosplitButton.setEnabled(False)
                else:
                    self.undosplitButton.setEnabled(True)

                QtGui.QApplication.processEvents()

                # I have a pause loop here so that it can check if the user presses skip split, undo split, or reset here.
                # Also updates the current split image text, counting down the time until the next split image
                pause_start_time = time.time()
                while time.time(
                ) - pause_start_time < self.pauseDoubleSpinBox.value():
                    self.pause_time_left = str(
                        round((self.pauseDoubleSpinBox.value()) -
                              (time.time() - pause_start_time), 1))
                    self.currentSplitImage.setText('None (Paused). ' +
                                                   self.pause_time_left +
                                                   ' sec remaining')

                    # check for reset
                    if win32gui.GetWindowText(self.hwnd) == '':
                        self.reset()
                    if self.startautosplitterButton.text(
                    ) == 'Start Auto Splitter':
                        if self.autostartonresetCheckBox.isChecked():
                            self.startAutoSplitterSignal.emit()
                            return
                        else:
                            self.guiChangesOnReset()
                            return

                    # check for skip/undo split:
                    if self.split_image_number != pause_split_image_number or self.loop_number != pause_loop_number:
                        break

                    # calculate similarity for reset image
                    if self.shouldCheckResetImage() == True:
                        reset_masked = (self.reset_mask is not None)
                        capture = self.getCaptureForComparison(reset_masked)

                        reset_similarity = self.compareImage(
                            self.reset_image, self.reset_mask, capture)
                        if reset_similarity >= self.reset_image_threshold:
                            keyboard.send(str(self.resetLineEdit.text()))
                            self.reset()
                            continue

                    QtTest.QTest.qWait(1)

        # loop breaks to here when the last image splits
        self.guiChangesOnReset()
コード例 #31
0
 def test_send_modifiers_release(self):
     keyboard.send('ctrl+shift+a', do_press=False, do_release=True)
     self.do([], u_a + u_shift + u_ctrl)
コード例 #32
0
ファイル: send_hotkey.py プロジェクト: abhineet123/PTF
        app_win = app.window(title=target_title)
    except BaseException as e:
        print('Failed to access app window for {}: {}'.format(target_title, e))
        exit(0)
    if mode == 1:
        app_win.type_keys("^+1")
    elif mode == 2:
        app_win.type_keys("^+2")
    elif mode == 3:
        app_win.type_keys("^+3")
    elif mode == 4:
        app_win.type_keys("^+4")
    elif mode == 5:
        app_win.type_keys("^+5")

else:
    if mode == 0:
        keyboard.send('ctrl+shift+alt+q')
    elif mode == 1:
        keyboard.send('ctrl+shift+1')
    elif mode == 2:
        keyboard.send('ctrl+shift+2')
    elif mode == 3:
        keyboard.send('ctrl+shift+3')
    elif mode == 4:
        keyboard.send('ctrl+shift+4')
    elif mode == 5:
        keyboard.send('ctrl+shift+5')

    # keyboard.send('ctrl+shift+alt+w')
コード例 #33
0
ファイル: read.py プロジェクト: pragaashm/test_repo
import RPi.GPIO as GPIO
import keyboard

from mfrc522 import SimpleMFRC522
from time import sleep


GPIO.setwarnings(False)    
reader = SimpleMFRC522()

rfid_Y = True;

while rfid_Y:
        try:
            
            
            id, text = reader.read()
            print(id)
            print(type(id))
            sleep(1)



            keyboard.send(str(id))


        except:
                GPIO.cleanup()
コード例 #34
0
import keyboard

# registering a hotkey that replaces one typed text with another
# replaces every "@email" followed by a space with my actual email
keyboard.add_abbreviation("@email", "*****@*****.**")

# invokes a callback everytime a hotkey is pressed
keyboard.add_hotkey("ctrl+alt+p", lambda: print("CTRL+ALT+P Pressed!"))

# check if a ctrl is pressed
print(keyboard.is_pressed('ctrl'))

# press space
keyboard.send("space")

# sends artificial keyboard events to the OS
# simulating the typing of a given text
# setting 0.1 seconds to wait between keypresses to look fancy
keyboard.write("Python Programming is always fun!", delay=0.1)

# record all keyboard clicks until esc is clicked
events = keyboard.record('esc')
# play these events
keyboard.play(events)

# remove all keyboard hooks in use
keyboard.unhook_all()

コード例 #35
0
def right():
    #sleep();
    print("Right Triggered! - go right")
    keyboard.send('windows, right', True, False)
コード例 #36
0
def runclient():
    global status
    global oldmsg
    global oldid
    global theid
    global downloadedfilepath
    try:
        while status == True:
            downloadedfilepath = wget.download(Addressoflogfileonserver)
            f = open(downloadedfilepath, "r")
            lines = f.readlines()
            lineid = lines[0]
            linekey = lines[1]
            linemouseposition = lines[2]
            theid = lineid

            f.close()
            os.remove(downloadedfilepath)
            if lineid != oldid:
                #keyboard and mouse click if and if
                print(linekey)
                oldid = lineid

                if ("pace" in str(linekey)):
                    print('Now Space should be pressed!')
                    keyboard.send("space")

                elif ("nter" in str(linekey)):
                    print('Now Enter should be pressed!')
                    keyboard.send("enter")

                elif ("MB" in str(linekey)):
                    print('Now LMB should be pressed!')
                    mouse.click(button='left')

                elif ("sc" in str(linekey)):
                    print('Now Esc should be pressed!')
                    keyboard.send("escape")

                elif ("hift" in str(linekey)):

                    positionarr = linemouseposition.split(' ')
                    print('Shift was pressed. Mouse moves to: ' + 'X = ' +
                          positionarr[0] + ' , Y = ' + positionarr[1])
                    autopy.mouse.smooth_move(
                        int(positionarr[0]),
                        int(positionarr[1]))  #smooth move is slow
                    #autopy.mouse.move(int(positionarr[0]),int(positionarr[1]))

                elif ("eft" in str(linekey)):
                    print('Now Left arrow button should be pressed!')
                    keyboard.send("left")

                elif ("ight" in str(linekey)):
                    print('Now Right arrow button should be pressed!')
                    keyboard.send("right")

#never pause the client you should only close the tab to end
                elif ("umLock" in str(linekey)):
                    print('host paused/unpaused the connection.')
##                    answer = input('Would you like to proceed the connection (answer: y/n)?')
##                    if answer == 'n' or answer == 'N':
##                        print('You are now disconnected. To start the client rerun the app.')
##                        status = False
    except:
        try:
            f.close()
            os.remove(downloadedfilepath)
            time.sleep(0.001)
            runclient()

        except FileNotFoundError:
            time.sleep(0.001)
            runclient()

        except:
            time.sleep(0.001)
            runclient()
コード例 #37
0
def kill():
    print("keyboard interrupt == ctrl+c")
    keyboard.send('ctrl,c', True, False)
コード例 #38
0
 def cycle_through_abilities():
     """Cycles through the powers on Farmer's 1st action bar from 1-n, where n is set in config file"""
     for i in range(1, SETTINGS['max_attack_key'] + 1):
         keyboard.send(str(i))
         time.sleep(0.5)
コード例 #39
0
def down():
    #sleep();
    print("Down Triggered! - zoom out")
    keyboard.send('windows,-', True, False)
コード例 #40
0
def download_chart_of_ticker(ticker, date, timeframe=1):
    now = dt.datetime.now()
    if not timeframe in ['d', 'D', 'w', 'W', 'q', 'Q', 'y', 'Y']:
        str_date = dt.datetime.strftime(date - dt.timedelta(days=2), "%d%m%Y")
        title_date = f'{date:%Y-%m-%d}'

    else:
        str_date = '01012011'
        title_date = '2011-01-01'

    ticker = ticker.upper()
    sleep(1)
    kb.send('alt+tab')
    sleep(1)

    kb.send('esc')

    # отправляем по символу тикер
    # for char in ticker:
    #    kb.send(char)

    kb.write(ticker)
    time.sleep(0.3)
    kb.send('enter')
    sleep(5)

    # выбираем таймфрейм и отправляем дату
    kb.send(f"esc, tab, comma, {timeframe}, enter, ctrl+shift+g")
    time.sleep(1.5)

    for i in str_date:
        kb.send(i)

    kb.send('enter')

    # переключаем на сам чарт
    if timeframe in ['d', 'D', 'w', 'W', 'q', 'Q', 'y', 'Y']:
        sleep(5)
    else:
        sleep(15)

    kb.send('esc, tab')

    kb.send('ctrl+alt+d')  # открываем окно "export to excel"

    time.sleep(0.4)
    kb.send('ctrl+a')

    path_dir = f'E:\\Trading_diary\\Esignal_charts\\{ticker}\\'

    if not os.path.exists(path_dir):
        os.makedirs(path_dir)

    if dt.datetime.now().time() > dt.time(16, 10):
        file_name = path_dir + f'{ticker}_{timeframe}_{title_date}_{now:%Y-%m-%d}.csv'

    else:
        file_name = path_dir + f'{ticker}_{timeframe}_{title_date}_{now - dt.timedelta(days=1):%Y-%m-%d}.csv'

    kb.write(file_name)

    kb.send('enter')

    sleep(12)
    kb.send('esc')
    time.sleep(0.1)
    kb.send('esc')
    time.sleep(0.1)

    if timeframe in ['d', 'D']:
        kb.send('ctrl+alt+d')  # открываем окно "export to excel"
        time.sleep(0.4)
        kb.send('ctrl+a')
        file_name = path_dir + f'{ticker}_latest_daily.csv'
        kb.write(file_name)
        time.sleep(0.3)
        kb.send('enter')
        sleep(5)
        kb.send('esc')
        time.sleep(0.1)
        kb.send('esc')
        time.sleep(0.1)

    kb.send('alt+tab')
    time.sleep(1)

    return file_name