def run(script): from applescript import asrun script = u""" tell application "System Events" to click %s """ % (script) open('/Users/nateparrott/Desktop/xyz.scpt', 'w').write(script) asrun(script.encode('utf-8'))
def create_note(content, title = None, is_html = False, notebook = None, tags = None, created = None, attachments = None, url = None, latitude = None, longitude = None): en_script = 'tell application "Evernote"\n' en_script += u'set n to create note title {0}'.format(_get_title(title, created)) en_script += u' with {0} {1}'.format(_get_format(is_html), _get_content(content)) if tags: en_script += u' tags {{{0}}}'.format(_get_tags(tags)) if notebook: en_script += u' notebook {0}'.format(_get_notebook(notebook)) if created: en_script += u' created {0}'.format(_get_created(created)) if attachments: en_script += u' attachments {{{0}}}'.format(_get_attachments(attachments)) en_script += '\n' if created: en_script += 'set modification date of n to {0}\n'.format(_get_created(created)) if url: en_script += 'set source URL of n to {0}\n'.format(_get_url(url)) if latitude: en_script += 'set latitude of n to {0}\n'.format(_get_lat(latitude)) if longitude: en_script += 'set longitude of n to {0}\n'.format(_get_long(longitude)) en_script += 'end tell' asrun(en_script)
def run(query): from applescript import asrun, asquote from pipes import quote ascript = ''' set finderSelection to "" set theTarget to "" set appPath to path to application "Chocolat" set defaultTarget to (path to home folder as alias) tell application "Finder" set finderSelection to (get selection) if length of finderSelection is greater than 0 then set theTarget to finderSelection else try set theTarget to (folder of the front window as alias) on error set theTarget to defaultTarget end try end if open theTarget using appPath end tell ''' asrun(ascript)
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 run(type): from applescript import asrun, asquote ascript = ''' on to_hex(int) set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"} set x to item ((int div 16) + 1) of the hex_list set y to item ((int mod 16) + 1) of the hex_list return (x & y) as string end to_hex on color_component_to_hex(c) return to_hex(round (c / 65535 * 255)) end color_component_to_hex tell application "System Events" set activeApp to name of first application process whose frontmost is true end tell tell application activeApp set the_color to choose color end tell set color_type to "%s" if color_type is "hex" then set the_string to ("#" & color_component_to_hex(item 1 of the_color) & color_component_to_hex(item 2 of the_color) & color_component_to_hex(item 3 of the_color)) --hex color end if if color_type is "UIColor" then set the_string to "[UIColor colorWithRed:" & ((item 1 of the_color) / 65536) & " green:" & ((item 2 of the_color) / 65536) & " blue:" & ((item 3 of the_color) / 65536) & " alpha:1]" --uicolor end if set the clipboard to the_string display notification "Copied '" & the_string & "' to clipboard." ''' % (type) 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 _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 run(script): from applescript import asrun script = u""" tell application "System Events" to click %s """%(script) open('/Users/nateparrott/Desktop/xyz.scpt', 'w').write(script) asrun(script.encode('utf-8'))
def run(parsed): from applescript import asrun get_date = '' set_date = '' if '@date' in parsed: get_date = 'set theDueDate to epoch2datetime("{0}")'.format(parsed['@date']['timestamp']) set_date = "set due date of newReminder to theDueDate" script = """ on epoch2datetime(epochseconds) set myshell1 to "date -r " set myshell2 to " \\"+%m/%d/%Y %I:%M:%S %p\\"" log (myshell1 & epochseconds & myshell2) set theDatetime to do shell script (myshell1 & epochseconds & myshell2) return date theDatetime end epoch2datetime {0} tell application "Reminders" set newReminder to make new reminder set name of newReminder to "{1}" {2} display notification "Created reminder" with title "Flashlight" end tell """.format(get_date, parsed['~message'], set_date) print script asrun(script)
def run(query): from applescript import asrun, asquote from pipes import quote ascript = ''' set finderSelection to "" set theTarget to "" set appPath to path to application "Atom" set defaultTarget to (path to home folder as alias) tell application "Finder" set finderSelection to (get selection) if length of finderSelection is greater than 0 then set theTarget to finderSelection else try set theTarget to (folder of the front window as alias) on error set theTarget to defaultTarget end try end if open theTarget using appPath end tell ''' asrun(ascript)
def run(type): from applescript import asrun, asquote ascript = ''' on to_hex(int) set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"} set x to item ((int div 16) + 1) of the hex_list set y to item ((int mod 16) + 1) of the hex_list return (x & y) as string end to_hex on color_component_to_hex(c) return to_hex(round (c / 65535 * 255)) end color_component_to_hex tell application "System Events" set activeApp to name of first application process whose frontmost is true end tell tell application activeApp set the_color to choose color end tell set color_type to "%s" if color_type is "hex" then set the_string to ("#" & color_component_to_hex(item 1 of the_color) & color_component_to_hex(item 2 of the_color) & color_component_to_hex(item 3 of the_color)) --hex color end if if color_type is "UIColor" then set the_string to "[UIColor colorWithRed:" & ((item 1 of the_color) / 65536) & " green:" & ((item 2 of the_color) / 65536) & " blue:" & ((item 3 of the_color) / 65536) & " alpha:1]" --uicolor end if set the clipboard to the_string display notification "Copied '" & the_string & "' to clipboard." '''%(type) asrun(ascript)
def open_finder_item(): ascript = """ set finderSelection to "" set theTarget to "" set appPath to path to application "Sublime Text" set defaultTarget to (path to home folder as alias) tell application "Finder" set finderSelection to (get selection) if length of finderSelection is greater than 0 then set theTarget to finderSelection else try set theTarget to (folder of the front window as alias) on error set theTarget to defaultTarget end try end if open theTarget using appPath end tell """ import applescript applescript.asrun(ascript)
def run(file): from applescript import asrun, asquote asrun(""" tell application "CloudApp" upload POSIX file {0} end tell """.format(asquote(file)))
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 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 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 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 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 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 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(digit, is_facetime): import os from applescript import asrun import time if is_facetime: os.popen('open facetime://{0}'.format(digit)) else: os.popen('open tel://{0}'.format(digit)) asrun("tell application \"Facetime\" to activate") time.sleep(2) asrun("tell application \"System Events\" to keystroke return")
def current_app(): from applescript import asrun return asrun(""" tell application "System Events" get item 1 of (get name of processes whose frontmost is true) end tell """).strip()
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 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 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 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" 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)
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 run(timestamp): from applescript import asrun if timestamp: script = """on epoch2datetime(epochseconds) set myshell1 to "date -r " set myshell2 to " \\"+%m/%d/%Y %H:%M\\"" log (myshell1 & epochseconds & myshell2) set theDatetime to do shell script (myshell1 & epochseconds & myshell2) return date theDatetime end epoch2datetime set theTime to epoch2datetime("{0}") tell application "Calendar" activate view calendar at theTime end tell """.format(int(timestamp)) a = open("/Users/nateparrott/Desktop/script.txt", "w") a.write(script) a.close() asrun(script)
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 currentFlickrID(): '''Return the ID for the Flickr image currently showing in the browser. The function works through Apple Events and supports only the Safari browser. It will generate an IndexError if the frontmost tab of the browser isn't showing a Flickr image.''' # The regex for extracting user and photo info. infoRE = r'flickr\.com/photos/(.*)/(\d+)/?' # Get the URL of the current page in either Safari. thisURL = asrun('tell application "Safari" to get the URL of the front document') # Extract the user and photo info from the URL. info = re.findall(infoRE, thisURL) return info[0][1]
def currentFlickrID(): '''Return the ID for the Flickr image currently showing in the browser. The function works through Apple Events and supports only the Safari browser. It will generate an IndexError if the frontmost tab of the browser isn't showing a Flickr image.''' # The regex for extracting user and photo info. infoRE = r'flickr\.com/photos/(.*)/(\d+)/?' # Get the URL of the current page in either Safari. thisURL = asrun( 'tell application "Safari" to get the URL of the front document') # Extract the user and photo info from the URL. info = re.findall(infoRE, thisURL) return info[0][1]
def run_tyme_script(ascript_body): return asrun('''tell application "Tyme" activate {} activate end tell'''.format(ascript_body))
# -*- 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)
envadd="*****@*****.**" #enter you evernote mail address fname=raw_input("Enter file name to send: ") subject=raw_input("Enter note title: ") title=subject # open and reads file as string ffile=open(fname, "r") body=ffile.read() ffile.close() # composing mail -applescript mScript = ''' tell application "Mail" activate set newMsg to make new outgoing message with properties {{subject:"{0}", content:"{1}", visible:true}} tell the content of newMsg make new attachment with properties {{file name:"{4}"}} at after last paragraph end tell tell newMsg make new to recipient at end of to recipients with properties {{name:"{2}", address:"{3}"}} end tell end tell ''' # create mail message asrun(mScript.format(subject, body, title, envadd, 1))
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 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
# hard coding evernote e-mail address envadd = "*****@*****.**" #enter you evernote mail address fname = raw_input("Enter file name to send: ") subject = raw_input("Enter note title: ") title = subject # open and reads file as string ffile = open(fname, "r") body = ffile.read() ffile.close() # composing mail -applescript mScript = ''' tell application "Mail" activate set newMsg to make new outgoing message with properties {{subject:"{0}", content:"{1}", visible:true}} tell the content of newMsg make new attachment with properties {{file name:"{4}"}} at after last paragraph end tell tell newMsg make new to recipient at end of to recipients with properties {{name:"{2}", address:"{3}"}} end tell end tell ''' # create mail message asrun(mScript.format(subject, body, title, envadd, 1))
movie_quotes = open("data/moviequotes.memorable_quotes.txt") data = "" for line in movie_quotes: line = line.strip() line = line.split('+++$+++') data+=line[-1] words = data.split() words[0:2] model = markov.build_model(words, 2) " ".join(markov.generate(model, 2, ['the', 'police'])) # get the current text msword_text = asrun(current_text).split('\r') decoded_text = [] for line in msword_text: decoded_text.append(line.decode('utf-8').lower()) for i in range(2): asrun(linebreak()) # add a new line and then begin writting for line in decoded_text: if len(line) > 2: seed = line.split()[0:2] generated = markov.generate(model, 2, seed) generated = " ".join(generated[:randint(6,12)]) asrun(linebreak()) asrun(paste_text(generated)) # run the applescript to paste into msword
def run_script(template): asrun(template)
#!/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()
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 convertToList(string):
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