Beispiel #1
0
def main():
    print('Listening for new pastes in clipboard...')

    while 1:
        pyperclip.waitForNewPaste()
        paste = pyperclip.paste()

        if 'chrome-extension://' in paste:
            new_url = paste.split('uri=')[1]
            pyperclip.copy(new_url)
            print(f"Fixed URL: {new_url}")
    def pasting_backend(self):

        cursor = Database.return_cursor(self)
        connector = Database.return_connector(self)
        today_date = datetime.now().strftime("%d/%m")
        insert_query = "INSERT INTO Clip_data( Data, Date_, Time_) VALUES (?,?,?)"
        previous_text = ""
        flag = 0

        while True:

            if flag == 0:
                copied_text = str(pyc.paste())#to copy text previously copied when script run for first time
                flag = 1
            else:
                copied_text = str(pyc.waitForNewPaste())# wait for new paste and then return it 

            copied_text = copied_text.replace("\r", "").strip()#eliminating carriage return and \n 

            if copied_text != previous_text and copied_text != "":

                time_now = datetime.now().strftime("%H:%M")# to pass time in query
                previous_text = copied_text #to check text don't repeat
                cursor.execute(insert_query, (copied_text, today_date, time_now))
                connector.commit() #to update the database side by side as query executed
Beispiel #3
0
def duplicate_clipboard(switch_key, clear):
    while True:
        old = waitForNewPaste()
        new = waitForNewPaste()

        copy(old)

        keyboard.wait(switch_key)
        copy(new)
        print("Clipboard switched!")

        if clear == True:
            old = ""
            new = ""

            keyboard.wait(switch_key)
            copy("")
            print("Clipboard cleared!")
Beispiel #4
0
def cmd():

    while True:
        new_text = text = pyperclip.waitForNewPaste()
        new_text = re.sub(r'[\r\n]', '', new_text)
        new_text = re.sub(r'([^a-zA-Z]) ([^a-zA-Z])', r'\1\2', new_text)
        new_text = re.sub(r'([a-zA-Z]) ([^a-zA-Z])', r'\1\2', new_text)
        new_text = re.sub(r'([^a-zA-Z]) ([a-zA-Z])', r'\1\2', new_text)
        pyperclip.copy(new_text)
        print(text, '->', new_text)
Beispiel #5
0
def main():
    global stop_capturing
    stop_capturing = 0
    global links
    links = []

    print("Welcome to the Udemy Courses Autoclaimer!")
    print(
        "Start copying links. \nWhen you're ready, press F10.\nTo exit the program press F9."
    )
    listener = keyboard.Listener(on_press=on_press_event_listener)

    listener.start()

    while stop_capturing == 0:

        try:
            pyperclip.waitForNewPaste(2)
            link = pyperclip.paste()
            links.append(link)

            if not re.search("https", link):
                print("[ERROR] Not a url")
                continue

            print(f"[INFO] Course captured: {link}")
        except pyperclip.PyperclipTimeoutException as ex:
            pass  # Timeout, receck condition

    start_browser()
    login()
    for link in links:

        if args.verbose:
            print(f"[DEBUG] Working on link: {link}")

        if is_coursetime_url(link):
            link = get_udemy_url(link)

        if add_to_cart(link) == -1:
            print("[INFO] Course is not free, not adding it to the cart.")

    checkout_cart()
Beispiel #6
0
 def deliver(self) -> NoReturn:
     if not self.valid:
         raise Exception(
             'Sorry, could not find any valid password for your options.')
     else:
         try:
             pyperclip.copy(self.password)
             capture = pyperclip.paste(
             )  # Capture paste and begin countdown
             try:
                 print('Password generated and copied to clipboard')
                 pyperclip.waitForNewPaste(
                     self.gen_opts.SECONDS_IN_CLIPBOARD)
             except:
                 pyperclip.copy('')
                 pass
         except:
             print('Password generated:\n{}'.format(self.password))
         finally:
             self.password = ''
             self.valid = False
             print('--Password-Generator end---')
Beispiel #7
0
 def run(self):
     write = open(self.wpath, "w")
     print("lgging starts")
     while True:
         try:
             url = pyperclip.waitForNewPaste()
             if not check_url(url):
                 continue
             url_line = url + "\n"
             write.write(url_line)
             print("save {}".format(url))
         except KeyboardInterrupt:
             break
     print("logging stops")
Beispiel #8
0
def main(passive, verbose, lang):
    click.echo("Ready!\n")

    if passive:
        # paste and re-copy
        while True:
            s = "".join(sys.stdin.readlines())
            click.echo(Text(s, lang=lang).clean)

    else:
        # read clipboard and re-copy
        clipText = Text(pyperclip.waitForPaste(), lang=lang)
        copy_echo(clipText.clean, verbose=verbose)
        while True:
            clipText = Text(pyperclip.waitForNewPaste(), lang=lang)
            copy_echo(clipText.clean, verbose=verbose)
Beispiel #9
0
def main():
    """youtube urls look like

    https://www.youtube.com/watch?v=hMk6rF4Tzsg
    https://www.youtube.com/watch?v=pL3Yzjk5R4M&list=RDCMUCmM3eCpmWKLJj2PDW_jdGkg&start_radio=1&t=8

    config file at ~/.config/ytcb:
        ---
        incoming: /home/chris/Videos/kmedia/incoming
        youtubedl: /home/chris/bin/youtube-dl

    incoming is the path to store incoming videos from youtube
    youtubedl is the full path to the youtube-dl executable
    """
    log.info(
        f"{appname} - youtube-dl clipboard queue processor {ccacb.__version__}"
    )
    userd = os.environ.get("HOME", os.path.expanduser("~"))
    defd = {
        "incoming": "/".join([userd]),
        "youtubedl": "/".join([userd, "bin/youtube-dl"]),
    }
    cf = ccaConfig(appname=appname, defaultd=defd)
    cfg = cf.envOverride()
    log.info(f"""Using {cfg["youtubedl"]}""")
    log.info(f"""youtube-dl will store files in {cfg["incoming"]}""")
    updateYoutubedl(cfg)
    Q = queue.Queue()
    thread = threading.Thread(target=doYouTube, args=[cfg, Q])
    thread.start()
    try:
        while True:
            txt = waitForNewPaste()
            if txt.startswith("https://www.youtube.com/watch"):
                log.info(f"adding to Q: {txt}")
                Q.put(txt)
    except KeyboardInterrupt:
        log.info("Interrupted: Will finish off the Q, then exit")
    Q.put("STOP")
    thread.join()
    log.info(f"{appname} has finished")
Beispiel #10
0
def watchClipBoard(cfg, Q, ev):
    global cbstatus
    cbstatus = f"Watching clipboard: {Q.qsize()} items on Q"
    thread = threading.Thread(target=doYouTube, args=[cfg, Q])
    thread.start()
    while True:
        try:
            txt = waitForNewPaste(1)
        except pyperclip.PyperclipTimeoutException:
            if ev.is_set():
                # print("watcher Stop found")
                # print("putting stop on q")
                Q.put("STOP")
                break
            continue
        if txt.startswith("https://www.youtube.com/watch"):
            Q.put(txt)
            notifyQSize(Q.qsize())
        elif txt.startswith("https://youtu.be/"):
            Q.put(txt)
            notifyQSize(Q.qsize())
    # print("waiting for child to exit")
    thread.join()
Beispiel #11
0
def main():
    global client, IP, SERVER_PORT, client_connected, my_clipboard, verbose
    server_thread = threading.Thread(target=serverThread, args=(), daemon=True)
    server_thread.start()

    # Try connecting as client
    while 1:
        try:
            client.connect((IP, SERVER_PORT))
            print("[bold blue][+][/bold blue]Connected as client. :smiley:")
            break
        except Exception as e:
            print(
                "[yellow][!][/yellow]Couldn't connect as client, trying again in 5 secs.."
            )
            time.sleep(5)

    while not client_connected:
        continue

    print(
        "\n[bold magenta][*]OK. Clipboard is now shared. :thumbs_up:[/bold magenta]\n"
    )
    while 1:
        data = "No data in clipboard"
        if cb.paste() == "" or cb.paste() == None:
            data = cb.waitForPaste()
        else:
            data = cb.waitForNewPaste()

        if not client_connected:
            print("[red][-][/red]No client to send data.")
            sys.exit(0)

        if client_connected and my_clipboard != data and data != "":
            sendClipboardData(data)
Beispiel #12
0
def download_media(record_file: str,
                   flush_records: int = 5,
                   download_dir: str = None) -> typing.NoReturn:
    """
    Read copy buffer, parse URL and download media in URL.

    :param record_file: Name of file to track previous dls and record new dls
    :param flush_records: Number of dl records before writing to file.
    :param download_dir: Relative location of dl directory.

    :return: None

    """

    dl_total = 0  # Current number of DLs during session
    had_dl = False

    # -----------------------------------
    # Catch the Ctrl-C, and write DL'd media names to file.
    # -----------------------------------
    def handler(signal_received: signal.SIGINT, frame: typing.Any):
        print("Control-C captured, exiting.")

        # If there was a file DL'd, write all metadata to file before exiting
        if had_dl:
            names.record_file_names(names_dict)
        exit(0)

    # -----------------------------------
    # Register the interrupt routine
    # -----------------------------------
    signal.signal(signal.SIGINT, handler)

    # -----------------------------------
    # Get list of previously DL'd media names
    #    to save new file info, and prevent duplicate downloads
    # -----------------------------------
    names = MediaRecords(record_file=record_file)
    names_dict = names.get_file_name_dict()

    # -----------------------------------
    # Until CTRL-C is pressed...
    # -----------------------------------
    while True:

        # -----------------------------------
        # Get the URL from the copy buffer
        # -----------------------------------
        url = pyperclip.waitForNewPaste()

        # -----------------------------------
        # Make sure the text from the buffer is an URL
        # -----------------------------------
        if not url.lower().startswith("http"):
            print(f"Invalid URL: {url}")
            continue

        # -----------------------------------
        # Get the media info (url, name, etc.)
        # -----------------------------------
        media = GetMedia(url_str=url, relative_dir=download_dir)

        # -----------------------------------
        # If the media file has not be DL'd, get the media file and
        # record that the media files have been DL'd so name list is written to file.
        # -----------------------------------
        if media.name not in names_dict:
            dl_total += 1
            media.set_index(dl_total)
            names_dict[media.name] = media.url

            # Download the target media from the provided URL
            try:
                media.download_media()

            except Exception as exc:
                names.record_file_names(names_dict)
                print(f"ERROR: {exc}")
                dl_total -= 1

            # Write all of the metadata to file after flush_records DLs
            else:
                had_dl = True
                if dl_total % flush_records == 0:
                    names.record_file_names(names_dict)

        # if the file has the media file name but not the URL, save the URL
        elif names_dict[media.name] == MediaRecords.UNKNOWN:
            names_dict[media.name] = media.url
            print(f"URL updated for {media.name}")

        # -----------------------------------
        # Duplicate media file (it was found in the list), so don't DL the media file.
        # -----------------------------------
        else:
            print(
                f"NOTE: Media file '{media.name}' has already been downloaded."
            )
Beispiel #13
0
def pyp_manager():
    clipboard_typo(pyperclip.waitForPaste())
    while True:
        clipboard_typo(pyperclip.waitForNewPaste())
Beispiel #14
0
pyperclip.copy('text to be copied')
print(pyperclip.paste())
# text to be copied

print(type(pyperclip.paste()))
# <class 'str'>

s = pyperclip.paste()
print(s)
# text to be copied

pyperclip.copy('')
print(pyperclip.waitForPaste())
# some text

print(pyperclip.waitForNewPaste())
# new text

# pyperclip.waitForNewPaste(5)
# PyperclipTimeoutException: waitForNewPaste() timed out after 5 seconds.

try:
    s = pyperclip.waitForNewPaste(5)
except pyperclip.PyperclipTimeoutException:
    s = 'No change'

print(s)
# No change

pyperclip.copy(100)
print(pyperclip.paste())
Beispiel #15
0
import pyperclip

pyperclip.copy("Hello world!")
text = pyperclip.paste()
print(text)

pyperclip.copy("original text")
text = pyperclip.waitForNewPaste()
print(text)
Beispiel #16
0
import socket
from pyperclip import waitForNewPaste
import time

HEADERSIZE = 10  #for socket communication

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
print('listening for connections...')

clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")

#for now just try one time
#wait for new paste, it will take time
while True:
    msg = waitForNewPaste()
    print(f'got a new message {msg}')

    #once it gets it, it will send to the client
    #add header to i
    msg = f"{len(msg):<{HEADERSIZE}}" + msg
    print(msg)
    clientsocket.send(bytes(msg, "utf-8"))
    #time.sleep(0.01)

#close the socket
clientsocket.close()
Beispiel #17
0
@author:maregul

to me, you are my perfect 
https://blog.csdn.net/nanbei2463776506/article/details/82967140

"""
import pyperclip


def E_trans_to_C(string):
    E_pun = u',.!?[]()<>"\''
    C_pun = u',。!?【】()《》“‘'
    table = {ord(f): ord(t) for f, t in zip(E_pun, C_pun)}
    return string.translate(table)


stop = False
while (stop == False):
    pyperclip.waitForNewPaste()
    a = pyperclip.paste()
    a.replace(" ", '')
    a.replace('\n', '')
    a.replace("\r", '')
    ca = E_trans_to_C(a)
    print(
        "********************************************************************")
    print(ca)
    pyperclip.copy(ca)
    print(
        "********************************************************************")
Beispiel #18
0
 def copy_clip():
     data = pyperclip.paste()
     pyperclip.waitForNewPaste()
     return data
Beispiel #19
0
'''
'''

https://quickchart.io/chart?bkg=white&c={type:%27bar%27,data:{labels:
[1984,1997,2001,2002,2003,2004,2005,2006,2007,2009,2012,2014,2015,2016,2017,2018,2019,2020,2021,2000,2008,2010,2011,2013,1991,1996,1999,1986,1994,1995,1987,1988,1992,1993,1998,1989]
,datasets:[{label:%27Publications_Per_Year%27,data:
[2,17,27,18,24,12,14,17,13,5,21,18,36,40,38,29,27,25,21,3,8,14,15,14,2,4,5,1,4,1,1,2,1,1,5,3]
}]}}


'''

while True:
    try:
        ("GETTING CLIPBOARD")
        original = pyperclip.waitForNewPaste()
        x = original

        x = x.replace(
            r'https://quickchart.io/chart?bkg=white&c={type:%27bar%27,data:{labels:',
            '')
        x = x.replace(r',datasets:[{label:%27Citations_Per_Year%27,data:', '')
        x = x.replace(r',datasets:[{label:%27Publications_Per_Year%27,data:',
                      '')
        x = x.replace(r'}]}}', '')

        x = x.replace('][', '],[')
        x = "[" + x + "]"
        x = eval(x)

        year = x[0]
def main():
    parser = argparse.ArgumentParser(
        prog="clipper",
        description=
        "Automated highlighting and export of code in clipboard using Pygments. For available lexers and formatters refer to output from 'pygmentize -L'",
    )
    parser.add_argument(
        "--lexer",
        default="c",
        help="which lexer/language to use for parsing code",
    )
    parser.add_argument(
        "--formatter",
        default="svg",
        choices=["svg"],
        help="formatter to use for exporting code",
    )

    parser.add_argument(
        "--line-numbers",
        dest="line_numbers",
        action="store_true",
        help="add line numbers to generated output",
    )

    parser.add_argument(
        "--crop",
        action="store_true",
        help=
        "attempt to set the height and width of the svg file to fit contents",
    )

    overwrite_clipboard_group = parser.add_mutually_exclusive_group()

    overwrite_clipboard_group.add_argument(
        "--overwrite-clipboard-text",
        dest="overwrite_clipboard_text",
        action="store_true",
        help="copy the textual representation of the result into the clipboard",
    )

    overwrite_clipboard_group.add_argument(
        "--overwrite-clipboard-file",
        dest="overwrite_clipboard_file",
        action="store_true",
        help=
        "copy the results into the clipboard as a reference to the stored file",
    )

    parser.add_argument(
        "--outdir",
        default="clipper_snippets",
        help="directory into which the exported snippets are saved",
    )

    # parse arguments
    args = parser.parse_args()

    outdir = Path(args.outdir)
    outdir.mkdir(exist_ok=True)

    # handle clipping

    while True:

        lexer = get_lexer_by_name(args.lexer)
        formatter = get_formatter_by_name(args.formatter,
                                          style=VSCodeLight,
                                          linenos=args.line_numbers)

        logger.info("waiting for new paste")
        s = pyperclip.waitForNewPaste()

        assert type(s) is str

        try:
            if s not in {"", None}:
                print(s)
                logger.info(
                    f"The following string was copied to the clipboard:\n{s}")

                ts = datetime.timestamp(datetime.now())
                outfile = outdir / f"{ts}.svg"

                svg = pygments.highlight(code=s,
                                         lexer=lexer,
                                         formatter=formatter)

                if args.crop:
                    height, width = infer_height_and_width(text=s, svg=svg)
                    logger.info(
                        f"cropping svg to height:{height} width:{width}")
                    from regex import sub

                    svg = sub(
                        pattern="<svg",
                        repl=f'<svg height="{height}" width="{width}" ',
                        string=svg,
                    )

                with open(outfile, "w") as f:
                    f.write(svg)

                if args.overwrite_clipboard_text:
                    pyperclip.copy(svg)

                if args.overwrite_clipboard_file:
                    raise NotImplementedError("Not implemented")

                logger.info(f"Snippet stores as: {outfile}")
            else:
                logger.warning(
                    "Contents of clipboard appears to be empty, no snippet generated"
                )
        except:
            logger.error(
                "An exception was raised when parsing clipboard, no snippet generated",
                exc_info=True,
            )
Beispiel #21
0
import keyboard, pyperclip, os

try:
    with open("fp.txt") as r:
        fp = r.read()
except FileNotFoundError:
    with open("fp.txt", "x"):
        pass
    fp = input("Type the folder where to save all the files:\n> ")

fn = input("Type the filename:\n> ")

if fn[:-4] != ".txt":
    fn += ".txt"

path = os.path.join(fp, fn)

with open(path, "a") as a:
    while True:
        if keyboard.read_key() == "esc":
            raise Exception("Program finished")

        copy = pyperclip.waitForNewPaste()
        a.write(copy + "\n")
        print(copy)
Beispiel #22
0
def data():
    text = ppc.waitForNewPaste()
    return text
Beispiel #23
0
#!/home/fitti/projects/wrappah/venv/bin/python
import pyperclip
from pyautogui import hotkey, press
from time import sleep

while True:
    to_wrap = pyperclip.waitForNewPaste()
    pyperclip.copy("What's \"" + to_wrap.strip("\n").strip() + "\"?")
    hotkey("ctrl", "v")
    sleep(.2)
    press("enter")
    print("Copied!")
Beispiel #24
0
# # import all necessary modules
import sqlite3 as sq
from datetime import datetime, date, time
from os import system
import pyperclip as pc
import time

# # import our modules
import clipboard_database as cd
new_clipboard_item = cd.database()
new_clipboard_item.make_clipboard_table()

# # infinite loop to run in background
# # checks if a new element has been added to clipboard
# # it will be added to our database as well
pc.paste()
while True:
    x = pc.waitForNewPaste()
    text = pc.paste()
    print(text)
    new_clipboard_item.add_new_item(text)
    time.sleep(2)