def run(applicationName): from applescript import asrun, asquote applicationName = applicationName.capitalize() ascript = """ tell application %s activate end tell delay 0.1 -- fix for termianl.app set location to (user locale of (get system info)) if location is equal to "zh_TW" then tell application "System Events" click menu item "合併所有視窗" of menu "視窗" of menu bar 1 of process %s end tell else tell application "System Events" click menu item "Merge All Windows" of menu "Window" of menu bar 1 of process %s end tell end if """ % ( asquote(applicationName), asquote(applicationName), asquote(applicationName), ) asrun(ascript.format(asquote(applicationName)))
def __init__(self, name, project, tags): self.name = name if len(name) > 0 else default_name self.project = project self.tags = tags run_tyme_script(init_script_body.format(asquote(self.project.name), asquote(self.name))) for tag in self.tags: add_tag(tag)
def send_mail(recipients, subject, body, attach_file_path): emails = [] address_book = contacts.address_book_to_list() for recip in recipients: if '@' in recip: emails.append(recip) else: result = contacts.find_contact(recip, address_book, "email") if result: emails.append(result['email'][0]) recipient_lines = [] for email in emails: recipient_lines.append("make new to recipient with properties {address:%s}"%(asquote(email))) file_command = u"make new attachment with properties {file name: (POSIX file %s as alias)} at after last paragraph of content"%(asquote(attach_file_path)) if attach_file_path else "" script = u""" tell application "Mail" activate set mgMessage to make new outgoing message with properties {subject:%s, content:%s, visible:true} tell mgMessage %s %s end tell end tell """%(asquote(subject), asquote(body), "\n".join(recipient_lines), file_command) print script asrun(script)
def create_event(name, from_date, to_date, location): import datetime def timestamp_to_applescript(timestamp): string = datetime.datetime.fromtimestamp(timestamp).strftime( "%m/%d/%Y %I:%M:%S %p") return ' date "{0}"'.format(string) props = { "summary": asquote(name), "start date": timestamp_to_applescript(from_date), "end date": timestamp_to_applescript(to_date) } if location: props['location'] = asquote(location) props_str = u"{" + u", ".join( [u"{0}:{1}".format(key, value) for (key, value) in props.iteritems()]) + u"}" script = u""" tell application "Calendar" activate set newEvent to make new event at end of events of calendar "Home" with properties {0} show newEvent end tell """.format(props_str) print script asrun(script)
def send_mail(recipients, subject, body, attach_file_path): emails = [] address_book = contacts.address_book_to_list() for recip in recipients: if '@' in recip: emails.append(recip) else: result = contacts.find_contact(recip, address_book, "email") if result: emails.append(result['email'][0]) recipient_lines = [] for email in emails: recipient_lines.append( "make new to recipient with properties {address:%s}" % (asquote(email))) file_command = u"make new attachment with properties {file name: (POSIX file %s as alias)} at after last paragraph of content" % ( asquote(attach_file_path)) if attach_file_path else "" script = u""" tell application "Mail" activate set mgMessage to make new outgoing message with properties {subject:%s, content:%s, visible:true} tell mgMessage %s %s end tell end tell """ % (asquote(subject), asquote(body), "\n".join(recipient_lines), file_command) print script asrun(script)
def _alert(title, message): from applescript import asrun, asquote script = u"""tell application "Finder" display notification <!--MESSAGE--> with title <!--TITLE--> end tell""".encode('utf8').replace("<!--TITLE-->", asquote(title)).replace( "<!--MESSAGE-->", asquote(message)) asrun(script)
def send_message(recipient, body, attach_selected_files): buddy = recipient set_selected_files = """ tell application "Finder" set selectedFiles to selection end tell """ if attach_selected_files else "set selectedFiles to {}" script = """ %s using terms from application "Messages" tell application "Messages" activate set targetService to 1st service whose service type = iMessage set targetBuddy to buddy %s of targetService send %s to targetBuddy repeat with theFile in selectedFiles send (theFile as alias) to targetBuddy end repeat end tell end using terms from """%(set_selected_files, asquote(buddy), asquote(body)) print script asrun(script)
def add_tag(tag): self.tags.append(tag) ascript_body = ''' set targetProject to first item of (every project whose name = {0}) set targetTask to first item of (every task of targetProject whose name = {1}) make new taskTag with properties {{name:{2}}} at the end of targetTask '''.format(asquote(self.project_name), asquote(self.name), asquote(tag)) run_tyme_script(ascript_body)
def add_tag(tag, task, project): asrun('''tell application "Tyme" activate set targetProject to first item of (every project whose name = {0}) set targetTask to first item of (every task of targetProject whose name = {1}) make new taskTag with properties {{name:{2}}} at the end of targetTask activate end tell'''.format(asquote(project), asquote(task), asquote(tag)))
def create_new_task(task, project): ascript_body = '''set projectName to {0} if ((count of (every project whose name = projectName)) = 0) then make new project with properties {{name:projectName, archived:false}} end if set targetProject to first item of (every project whose name = projectName) make new task with properties {{name:{1}}} at the end of targetProject'''.format( asquote(project), asquote(task)) return run_tyme_script(ascript_body)
def create_new_task(name, project_name): ascript_body = ''' set projectName to {0} if ((count of (every project whose name = projectName)) = 0) then make new project with properties {{name:projectName, archived:false}} end if set targetProject to first item of (every project whose name = projectName) make new task with properties {{name:{1}}} at the end of targetProject '''.format(asquote(self.project_name), asquote(self.name)) return run_tyme_script(ascript_body)
def run(content): from applescript import asrun, asquote name = content.split("\n")[0] if len(name) == 0: name = "New note" script = u"""tell application "Notes" set theContainerFolder to container of first note set theNote to make new note at theContainerFolder with properties {body:<!--BODY-->, name:<!--NAME-->} display notification "Created note" with title "Flashlight" end tell """.replace("<!--BODY-->", asquote(content)).replace("<!--NAME-->", asquote(name)) asrun(script)
def create_new_task(task, project): asrun('''tell application "Tyme" activate set projectName to {0} if ((count of (every project whose name = projectName)) = 0) then make new project with properties {{name:projectName, archived:false}} end if set targetProject to first item of (every project whose name = projectName) make new task with properties {{name:{1}}} at the end of targetProject activate end tell'''.format(asquote(project), asquote(task)))
def run(file): from applescript import asrun, asquote asrun(""" tell application "CloudApp" upload POSIX file {0} end tell """.format(asquote(file)))
def send_message(recipient, body, attach_selected_files): buddy = None if normalize_phone(recipient): buddy = normalize_phone(recipient) else: address_book = contacts.address_book_to_list() result = contacts.find_contact(recipient, address_book, "phone") if result: buddy = result["phone"][0] if not buddy: asrun( 'display notification %s with title "Limelight"' % (asquote("Couldn't find iMessage contact for %s." % recipient)) ) return set_selected_files = ( """ tell application "Finder" set selectedFiles to selection end tell """ if attach_selected_files else "set selectedFiles to {}" ) script = """ %s using terms from application "Messages" tell application "Messages" activate set targetService to 1st service whose service type = iMessage set targetBuddy to buddy %s of targetService send %s to targetBuddy repeat with theFile in selectedFiles send (theFile as alias) to targetBuddy end repeat end tell end using terms from """ % ( set_selected_files, asquote(buddy), asquote(body), ) print script asrun(script)
def run(command): from applescript import asrun, asquote from pipes import quote import json ascript_currentdir = ''' tell application "Finder" if (count of Finder windows) is not 0 then set currentDir to (target of front Finder window) as text set dir to (quoted form of POSIX path of currentDir) else set dir to "~/" end if end tell ''' settings = json.load(open('preferences.json')) # If the app is terminal, or _not_ iTerm2 if settings["app"] == "terminal" or settings["app"] not in ("iterm2", "iterm3"): ascript = ascript_currentdir + ''' tell application "Terminal" activate delay 0.1 -- fix for termianl.app do script "cd " & dir do script {0} in front window end tell '''.format(asquote(command)) else: # iTerm 2.9+ uses "window" instead of "terminal" for applescript window_name = "terminal" if settings["app"] == "iterm2" else "window" ascript = ascript_currentdir + ''' tell application "iTerm" tell (make new {1}) activate current session launch session "Default Session" tell the last session write text "cd " & dir write text {0} end tell end tell end tell '''.format(asquote(command), window_name) asrun(ascript)
def run(command): from applescript import asrun, asquote from pipes import quote import json ascript_currentdir = ''' tell application "Finder" if (count of Finder windows) is not 0 then set currentDir to (target of front Finder window) as text set dir to (quoted form of POSIX path of currentDir) else set dir to "~/" end if end tell ''' settings = json.load(open('preferences.json')) # If the app is terminal, or _not_ iTerm2 if settings["app"] == "terminal" or settings["app"] not in ("iterm2", "iterm3"): ascript = ascript_currentdir + ''' tell application "Terminal" activate do script "cd " & dir do script {0} in front window end tell '''.format(asquote(command)) else: # iTerm 2.9+ uses "window" instead of "terminal" for applescript window_name = "terminal" if settings["app"] == "iterm2" else "window" ascript = ascript_currentdir + ''' tell application "iTerm" tell (make new {1}) activate current session launch session "Default Session" tell the last session write text "cd " & dir write text {0} end tell end tell end tell '''.format(asquote(command), window_name) asrun(ascript)
def create_event(name, from_date, to_date, location): import datetime def timestamp_to_applescript(timestamp): string = datetime.datetime.fromtimestamp(timestamp).strftime("%m/%d/%Y %I:%M:%S %p") return ' date "{0}"'.format(string) props = {"summary": asquote(name), "start date": timestamp_to_applescript(from_date), "end date": timestamp_to_applescript(to_date)} if location: props['location'] = asquote(location) props_str = u"{" + u", ".join([u"{0}:{1}".format(key, value) for (key, value) in props.iteritems()]) + u"}" script = u""" tell application "Calendar" activate set newEvent to make new event at end of events of calendar "Home" with properties {0} show newEvent end tell """.format(props_str) print script asrun(script)
def run(command): from applescript import asrun, asquote # TODO: set the current working dir to the frontmost dir in Finder ascript = ''' tell application "Finder" set theItems to selection set filePath to (POSIX path of (the selection as alias)) end tell set the clipboard to filePath '''.format(asquote(command)) asrun(ascript)
def send_msg (module, subject, send=False): # Addresses cmds = [] for address in module.TO: name, email = address cmds.append (applescript.email_to_as (name, email, 'to')) for address in module.CC: name, email = address cmds.append (applescript.email_to_as (name, email, 'cc')) # Build message send_cmd = ('', 'send')[send] ascript = ASCRIPT %({'recipents_commands': '\n'.join(cmds), 'body': applescript.asquote(module.BODY), 'subject': applescript.asquote(subject), 'send': send_cmd}) # Run it applescript.asrun (ascript)
def send_message(recipient, body, attach_selected_files): buddy = None if normalize_phone(recipient): buddy = normalize_phone(recipient) else: address_book = contacts.address_book_to_list() result = contacts.find_contact(recipient, address_book, "phone") if result: buddy = result['phone'][0] if not buddy: asrun("display notification %s with title \"Flashlight\""%(asquote("Couldn't find iMessage contact for %s."%recipient))) return set_selected_files = """ tell application "Finder" set selectedFiles to selection end tell """ if attach_selected_files else "set selectedFiles to {}" script = """ %s using terms from application "Messages" tell application "Messages" activate set targetService to 1st service whose service type = iMessage set targetBuddy to buddy %s of targetService send %s to targetBuddy repeat with theFile in selectedFiles send (theFile as alias) to targetBuddy end repeat end tell end using terms from """%(set_selected_files, asquote(buddy), asquote(body)) print script asrun(script)
def run(command): from applescript import asrun, asquote # TODO: set the current working dir to the frontmost dir in Finder ascript = ''' tell application "Finder" if (count of Finder windows) is not 0 then set currentDir to (target of front Finder window) as text set dir to (quoted form of POSIX path of currentDir) else set dir to "~/" end if end tell tell application "Terminal" activate do script "cd " & dir & " && " & {0} end tell '''.format(asquote(command)) asrun(ascript)
def run(command): from applescript import asrun, asquote from pipes import quote ascript = ''' tell application "Finder" if (count of Finder windows) is not 0 then set currentDir to (target of front Finder window) as text set dir to (quoted form of POSIX path of currentDir) else set dir to "~/" end if end tell tell application "Terminal" activate do script "cd " & dir do script {0} in front window end tell '''.format(asquote(command)) asrun(ascript)
# -*- coding: utf-8 -*- #!/usr/bin/python from applescript import asrun, asquote subject = 'A new email' body = '''This is the body of my "email." I hope it comes out right. Regards, Dr. Drang ''' ascript = ''' tell application "Mail" activate make new outgoing message with properties {{visible:true, subject:{0}, content:{1}}} end tell '''.format(asquote(subject), asquote(body)) print ascript asrun(ascript)
def load_menu_items(): app = current_app() text = get_cached_text(app) if not text: from time import time from applescript import asrun, asquote _rstart = time() text = asrun(""" set AppleScript's text item delimiters to {"\n"} on toString(anyObj) local i, txt, errMsg, orgTids, oName, oId, prefix set txt to "" repeat with i from 1 to 2 try if i is 1 then if class of anyObj is list then set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} set txt to ("{" & anyObj as string) & "}" set AppleScript's text item delimiters to orgTids # ' else set txt to anyObj as string end if else set txt to properties of anyObj as string end if on error errMsg # Trick for records and record-*like* objects: # We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9). try set txt to do shell script "egrep -o '\\\\{.*\\\\}' <<< " & quoted form of errMsg end try end try if txt is not "" then exit repeat end repeat set prefix to "" if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then set prefix to "[" & class of anyObj set oName to "" set oId to "" try set oName to name of anyObj if oName is not missing value then set prefix to prefix & " name=\\"" & oName & "\\"" end try try set oId to id of anyObj if oId is not missing value then set prefix to prefix & " id=" & oId end try set prefix to prefix & "] " end if return prefix & txt end toString tell application "System Events" tell process %s set x to (entire contents of menu bar 1) end tell end tell get toString(x) """%(asquote(app))) cache_text(app, text) classes = { "«class mbri»": "menu bar item", "«class menI»": "menu item", "«class mbar»": "menu bar", "«class menE»": "menu", "«class pcap»": "process" } if text == '': return None for class_name, real_name in classes.iteritems(): text = text.replace(class_name, real_name) import re items = [] parent_menus_regex = re.compile(r'of menu "([^"]+?)"') for match in re.finditer(r'menu item "(?P<title>[^"]+?)" (?P<parents>(of menu "[^"]+?" .*?)+?) of menu bar 1 of process ".*?"', text): item = MenuItem() item.title = match.group('title').decode('utf-8') item.parent_menus = list(reversed([s.decode('utf-8') for s in [m.group(1) for m in re.finditer(parent_menus_regex, match.group('parents'))]])) item.applescript = match.group(0) items.append(item) return items
def _get_title(title, created): if title == None: if created == None: created = datetime.now() title = created.strftime('%A, %B %d, %Y %I:%M:%S %p') return asquote(title)
def load_menu_items(): app = current_app() text = get_cached_text(app) if not text: from time import time from applescript import asrun, asquote _rstart = time() text = asrun(""" set AppleScript's text item delimiters to {"\n"} on toString(anyObj) local i, txt, errMsg, orgTids, oName, oId, prefix set txt to "" repeat with i from 1 to 2 try if i is 1 then if class of anyObj is list then set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} set txt to ("{" & anyObj as string) & "}" set AppleScript's text item delimiters to orgTids # ' else set txt to anyObj as string end if else set txt to properties of anyObj as string end if on error errMsg # Trick for records and record-*like* objects: # We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9). try set txt to do shell script "egrep -o '\\\\{.*\\\\}' <<< " & quoted form of errMsg end try end try if txt is not "" then exit repeat end repeat set prefix to "" if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then set prefix to "[" & class of anyObj set oName to "" set oId to "" try set oName to name of anyObj if oName is not missing value then set prefix to prefix & " name=\\"" & oName & "\\"" end try try set oId to id of anyObj if oId is not missing value then set prefix to prefix & " id=" & oId end try set prefix to prefix & "] " end if return prefix & txt end toString tell application "System Events" tell process %s set x to (entire contents of menu bar 1) end tell end tell get toString(x) """ % (asquote(app))) cache_text(app, text) classes = { "«class mbri»": "menu bar item", "«class menI»": "menu item", "«class mbar»": "menu bar", "«class menE»": "menu", "«class pcap»": "process" } if text == '': return None for class_name, real_name in classes.iteritems(): text = text.replace(class_name, real_name) import re items = [] parent_menus_regex = re.compile(r'of menu "([^"]+?)"') for match in re.finditer( r'menu item "(?P<title>[^"]+?)" (?P<parents>(of menu "[^"]+?" .*?)+?) of menu bar 1 of process ".*?"', text): item = MenuItem() item.title = match.group('title').decode('utf-8') item.parent_menus = list( reversed([ s.decode('utf-8') for s in [ m.group(1) for m in re.finditer(parent_menus_regex, match.group('parents')) ] ])) item.applescript = match.group(0) items.append(item) return items
] answers = inquirer.prompt(inquiry) areaCode = "+1" # Manually edit if you live outside the USA messageContent = movieDictionary[answers['movieType']] recipientPhoneNum = areaCode + answers['phoneNum'] # TODO: Let the user know the script has executed userMessage = "The devilish script has been executed, we'll let you know once it's complete. You will send the following message word for word: " + messageContent executeScript = ''' tell application "Messages" set textbuddy to buddy {0} of service id {1} send {2} to textbuddy end tell '''.format(asquote(yourPhoneNumber), asquote(serviceID), asquote(userMessage)) asrun(executeScript) # Wait for 3 seconds time.sleep(3) # TODO: Remove all punctuation from the string punctuations = '''!()-[]{};:'"\\,<>./?@#$%^&*_~''' cleanMessage = "" for char in messageContent: if char not in punctuations: cleanMessage = cleanMessage + char # TODO: Make the new message into an array of words, AKA a list. Store it to 'convertedMessage'
def _alert(title,message): from applescript import asrun, asquote script = u"""tell application "Finder" display notification <!--MESSAGE--> with title <!--TITLE--> end tell""".encode('utf8').replace("<!--TITLE-->",asquote(title)).replace("<!--MESSAGE-->", asquote(message)) asrun(script)
def _get_notebook(notebook): return asquote(notebook)
def _get_content(content): return asquote(content)
def add_tag(tag, task, project): ascript_body = '''set targetProject to first item of (every project whose name = {0}) set targetTask to first item of (every task of targetProject whose name = {1}) make new taskTag with properties {{name:{2}}} at the end of targetTask'''.format(asquote(project), asquote(task), asquote(tag)) run_tyme_script(ascript_body)
#!/usr/bin/env python3 from applescript import asrun, asquote import sys import time cmd = 'tell application "Fantastical" to parse sentence %s add immediately true' print(sys.argv[1]) file = open(sys.argv[1], "r") for line in file.readlines(): print("adding :") print(line.replace("\n", "")) asrun(cmd % asquote(line.replace("\n", ""))) time.sleep(1) file.close()
def add_tag(tag, task, project): ascript_body = '''set targetProject to first item of (every project whose name = {0}) set targetTask to first item of (every task of targetProject whose name = {1}) make new taskTag with properties {{name:{2}}} at the end of targetTask'''.format( asquote(project), asquote(task), asquote(tag)) run_tyme_script(ascript_body)