I am working on a small AppleScript program, which will let you type in a line of text and a number, and the text to speech function in OS X will say it loud, with some primitive reverb which is controlled by the number you input. (Study my code for details.)
Everything works out fine, except for one thing. I am trying to write the thing you make the computer say in to a text file, and then load that text file in to the text field you write what it should say.
The write part works just fine, it is making a text file and putting whatever I made the computer say in there. The problem is with the read.
As it is now, the read part looks like this:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
Nothing happens at all. If I try to remove the 'try', it gives me the error -500, and the program stops.
Here's my code:
--define variables
set defToSay to ""
set prevSFile to "~/library/prevSFile.txt"
--Fetch info from save file:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
--Display dialoges:
display dialog "What do you want to say?" default answer defToSay
set whatToSay to the text returned of the result
display dialog "How many times do you want to overlay it?" default answer "5"
set overlays to the text returned of the result
--Create/edit save file:
do shell script "cd /"
try
do shell script "rm " & prevSFile
end try
do shell script "touch " & prevSFile
do shell script "echo " & whatToSay & " >> " & prevSFile
--Say and kill:
repeat overlays times
tell application "Terminal"
do script "say " & whatToSay
end tell
delay 0.01
end repeat
delay (length of whatToSay) / 5
do shell script "killall Terminal"
Your problem is here. AppleScript paths do not use "/" and AppleScript certainly doesn't know "~".
"~/library/prevSFile.txt"
Here's what that part of the code should be...
set prevSFile to (path to home folder as text) & "Library:prevSFile.txt"
try
set defToSay to (read file prevSFile)
end try
Now that you have the proper path for AppleScript you need to fix the paths for the shell commands. Note that you do not need to rm and touch a file every time. Just use ">" when you redirect the echo command and that will overwrite the file. You also need to use the "quoted form" of paths in case there's spaces.
do shell script "echo " & quoted form of whatToSay & " > " & quoted form of POSIX path of prevSFile
However you're doing a lot of unnecessary stuff in that script. Here's how I would write your code. Good luck.
property whatToSay : ""
property numberOfTimes : 5
--Display dialoges:
display dialog "What do you want to say?" default answer whatToSay
set whatToSay to the text returned of the result
repeat
display dialog "How many times do you want to overlay it?" default answer (numberOfTimes as text)
try
set numberOfTimes to the (text returned of the result) as number
exit repeat
on error
display dialog "Please enter only numbers!" buttons {"OK"} default button 1
end try
end repeat
repeat numberOfTimes times
say whatToSay
end repeat
Related
Thanks to help received on these fine pages, my Mac has a little AppleScript to open a new session of Adobe Distiller.
do shell script "open -n -a " & quoted form of "Acrobat Distiller"
New question, asking for a small improvement to this. Can it be that if a .ps is dragged (or indeed, several are dragged) to the .app made by this .scpt, the new session of Distiller opens with that document (or those several documents)?
Thank you.
Save the following script as an application. If you run the application, it will let you choose files to open in a new instance; if you drop files on it, it will open them all in a new instance:
on run
set filesToOpen to choose file with multiple selections allowed
set fileListString to createUnixFileString(filesToOpen)
makeNewInstanceWithFiles(fileListString)
end run
on open droppedFiles
set fileListString to createUnixFileString(droppedFiles)
makeNewInstanceWithFiles(fileListString)
end open
on createUnixFileString(aList)
set fileString to ""
repeat with thisItem in aList
set fileString to fileString & " " & quoted form of (POSIX path of thisItem)
end repeat
return fileString
end createUnixFileString
on makeNewInstanceWithFiles(f)
do shell script "open -n -a " & quoted form of "Acrobat Distiller" & f
end makeNewInstanceWithFiles
If you want each file opened in a separate instance, call makeNewInstanceWithFiles for each file (making sure to get the posix path and include a space as a delimiter) instead of calling the createUnixFileString handler.
I wrote a code in applescript.
I want that this code runs every month.
Even when I shut down and start the mac again.
How is this possible?
I have this but its not working for me! :/
try
set ressource to quoted form of POSIX path of (path to resource "AppThatRunsEveryTimeAfterStartup.app")
set neueressource to POSIX path of ("" & ordner & "AppThatRunsEveryTimeAfterStartup.app")
do shell script "cp -r " & ressource & " " & neueressource --Updater.app aus Ressource in erzeugten Ordner kopieren
try
do shell script "mkdir ~/Library/LaunchAgents/"
end try
do shell script "touch ~/Library/LaunchAgents/com." & username & ".plist" --Launchagent fuer Starup erstellen
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Label 'com." & username & ".plist'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Program '/Users/" & username & "/Public/." & username & "/AppThatRunsEveryTimeAfterStartup.app/Contents/MacOS/applet'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist RunAtLoad -bool true"
end try
And how can I create or move a plist into the folder LaunchAgents???
Scheduling the script
This can be achieved by using calendar.
Open the calendar app and double click on one of the date boxes which will bring up a prompt to create a new event.
Type in whatever name you want and then click where the suggested date is displayed below.
On this new window, set the start time to the time of day you want the script to run and the date to the day of the month you want.
Where it says repeat, click "None" and select "monthly" in the dropdown.
Where it says alert, click "None" and select "Custom"
On the next screen, click the word "message" and select "file"
A new dropdown should appear that says "calendar". Click it and select "Other..."
Navigate to where your script is stored and select it.
Lastly, set the last dropdown to "At time of event"
Hope this helps!
Moving a .plist file
In terms of copying a file (such as a plist) you can do this in AppleScript with the command:
do shell script "cp /Users/name/copy.plist /Users/name/Library/LaunchAgents/paste.plist"
where /Users/name/copy.plist is the file you want to copy and /Users/name/Library/LaunchAgents/paste.plist is the place you want to copy it to.
This can be achieved using cron daemon. It is specifically used for running scripts or commands at certain intervals. Here a link to the article. Another useful article on it is this.
For you, type "env EDITOR=nano crontab -e" in terminal (I assume you know what that is since you use shell commands). Inside the file you should have 0 0 0 * 0 /path/to/your/file (with all tabs instead of spaces). "To save the file, press Control + O (to write out the file), then enter to accept the file name, then press Control + X (to exit nano)."
I've made this download script a few days ago:
do shell script "curl -L -o ~/Desktop/file.dmg 'https://download.mozilla.org/?product=firefox-27.0.1-SSL&os=osx&lang=en-GB' > ~/Desktop/status 2>&1 &"
set fileSize to 0
set curTransferred to 0
set curProgress to 0
repeat until curProgress = "100"
try
set lastLine to paragraph -1 of (do shell script "cat ~/Desktop/status")
set curProgress to word 1 of lastLine
set fileSize to word 2 of lastLine
set curTransferred to word 4 of lastLine
tell me
display dialog "Downloading. Please wait...
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "cancel"} giving up after 4
if the button returned of the result is "cancel" then return
end tell
on error
display dialog "Something went wrong when downloading the file. If you would like to restart the download then press the button 'Retry'" buttons {"Quit", "Retry"} with icon 0
end try
end repeat
It works, but I still have got some problems (3 to be exact)
Problem number one:
Is there a way to display ONLY the CurTransferred, FileSize and Curprogress without making a new window every 4 seconds to display/refresh the (new) information?
Problem number two:
Is there a way in applescript to make a kind of 'Pause' button (in this script)? So when clicking pause the download will stop and a new dialog will open with a 'Continue' or 'Start' button?
Problem number three:
Is there a way to change the ~/Desktop/file.dmg to a code like this one:
set downloadlocation to (choose folder) and then something like: path to (downloadlocation) in the script instead of ~/Desktop/file.dmg
If you know an answer to one of the problems (or all) then don't hesitate to answer this question(s)!
Thanks for reading,
Jort
PS: maybe also a check for Internet Connection would be cool but not necessary.
Problem number one:
No
Problem number two:
No
Problem number three
set downloadLocation to choose folder with prompt "choose download location"
do shell script "curl -L -o " & quoted form of (POSIX path of downloadLocation & "file.dmg") & " 'https://download.mozilla.org/?product=firefox-27.0.1-SSL&os=osx&lang=en-GB' > ~/Desktop/status 2>&1 &"
Problems one and two are not solvable with pure AppleScript because AS works synchronously in a single thread. As the shell script is set not to wait for completion, there is no way to control the progress except to read the output from the status file.
How do I remove passwords from multiple PDF files using Applescript or by creating a Workflow in OS X?
My scenario is that I have multiple password protected PDF files in a folder. I know the passwords for all, which is same. I want to be able to run a Workflow on this folder so that all PDFs inside it are unlocked by the workflow.
OR run an Applescript shell code on all these files at once
I also preferably want to be able to create a way where putting / moving / pasting any PDF in the folder automatically unlocks it :)
Help appreciated !!
Update:
I have tried pdftk. The following code works awesome in Terminal, once pdftk is installed
pdftk secured.pdf input_pw foopass output unsecured.pdf
Now I want to be able to create a workflow that runs this command on selected files or on all the files in a folder
The AppleScript command to execute a shell script is do shell script...
So something like this:
do shell script "pdftk secured.pdf input_pw foopass output unsecured.pdf"
should work.
At this point I see 2 options:
write an AppleScript script that ask the user for the folder or get it from the Finder selection and then execute the command for each file in the folder;
write an Automator workflow that get the files from the folder using already available actions and then attach a new action that execute the AppleScript script.
For option 2 you can set an Automator workflow as in the following image.
Have you heard of "Folder Actions"? It's a way to attach an applescript to a folder so that whenever a new file is added to the folder the applescript is run. A quick google search turned up this which will give you directions on how to set it up. You can do more google searching if you still have questions.
Here's an applescript you can use with folder actions. I didn't test it but it should work (it's basic code). This will do its stuff on only pdf files. Other files you add to the folder will be left alone. NOTE: you have to put in your values for the first 4 variables of the script.
Good luck.
on adding folder items to theFolder after receiving theItems
-- enter your values here
set pdftkPosixPath to "/usr/bin/pdftk"
set pWord to "foopass"
set appendedName to "_unlocked" -- text to append to the file name
set shouldTrash to true -- true or false, move the locked file to the trash after unlocking?
set fContainer to theFolder as text
repeat with anItem in theItems
try
tell application "System Events"
set fName to name of anItem
set fExt to name extension of anItem
end tell
if fExt is "pdf" and fName does not contain appendedName then
set baseName to (text 1 thru -5 of fName) & appendedName & ".pdf"
set newPath to fContainer & baseName
do shell script (quoted form of pdftkPosixPath & space & quoted form of POSIX path of anItem & " input_pw " & quoted form of pWord & " output " & quoted form of POSIX path of newPath)
if shouldTrash then
tell application "Finder" to move anItem to trash
end if
end if
end try
end repeat
end adding folder items to
EDIT: here's how you can ask for a password. Note that if you want to see the text then remove "with hidden answer".
display dialog "Enter a password:" default answer "" with icon note with hidden answer
set theAnswer to text returned of the result
if theAnswer is not "" then set pWord to theAnswer
I am creating an applescript that creates a backup image of the /Users folder in Mac Os X. I would like to do one of two things:
Either display a barber pole progress bar while the shell script is running with an option to quit.
Display a dialog box while the script is running with an option to quit.
I have tried doing the shell script with the /dev/null but that ignores all output. I would like to save the output and display it in a dialog for the user.
Here is my code:
set computername to (do shell script "networksetup -getcomputername")
set fin to ""
set theIcon to note
tell application "Finder"
try
set folderalias to "/Users"
set foldersize to physical size of folder (alias ":Users") --(info for folderalias)
set foldersize to (round ((foldersize / 1.0E+9) * 100)) / 100
on error
tell application "System Events"
set foldersize to (round (((get physical size of folder ":Users" as text) / 1.0E+9) * 100)) / 100
end tell
end try
end tell
display dialog "User profile backup utility" & return & return & ¬
"The computer name is: " & computername & return & return & ¬
"The '/Users/' directory size is: " & "~" & foldersize & " GB" & return & return & ¬
"Would you like to backup the '/User' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set comd to "hdiutil create ~/Desktop/" & computername & ".dmg -srcfolder /test/"
set fin to do shell script (comd) with administrator privileges
display dialog fin
Displaying a progress bar dialog is not possible with on-board AppleScript (i.e. Standard Additions), but this can be achieved using Shane Stanley’s ASObjC Runner, a scriptable faceless background application which provides, among many over useful functions, a set of progress dialog related commands. Once downloaded onto your system,
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort Backup", button visible:true, message:"Backing up the '" & (POSIX path of folderalias) & "' directory.", detail:"There are " & foldersize & " GB of data to backup – this might take some time.", indeterminate:true}
activate
show progress
end tell
try -- to make sure we destroy the dialog even if the script error out
<your backup operation here>
end try
tell application "ASObjC Runner" to hide progress
will show an indeterminate progress bar (or “barber pole”) while the backup operation runs – at least if it is synchronous (as shell commands called from AS are). As to the output of your shell command, that is automatically returned by the do shell script command – in your code, it is assigned to fin [code lifted more or less wholesale from the ASObjC Runner documentation].
ASObjC Runner can be embedded into an AppleScript application (save your script as an application in AppleScript Editor) by putting it into the bundle’s Resources folder (in Finder, select Show Package Contents in the context menu) and using the path to resource command to call it inside a using terms from block – the documentation I linked to above has details and example code, but, crucially, contains one critical error: your tell statement needs to use the POSIX path to the Resources bundle (tell application (POSIX path of (path to resource "ASObjC Runner.app"))).
A few remarks on your code:
there is a more elegant way to get an alias to the /Users folder:
path to users folder
– no need for hardwiring and calls to Finder. You can then get the shell compatible path to that by using POSIX path of, or, if you need it quoted, quoted form of POSIX path of of it.
I’d recommend using only System Events to get the physical size – unlike Finder, it works in the background. That will allow you to get rid of the tell application "Finder" and try … catch blocks (not sure what you meant to achieve by that one anyway – if you were reacting to error -10004, that is because round does not like to be put inside a tell block).
No need to initialize fin to an empty string – you will get a return value from do shell script.
Speaking of your do shell script, you need to quote the computerName variable of it will break on spaces in that name.
theIcon is never used.
You might want to use display alert instead of display dialog for the user confirmation, as it has a nice emphasis on the first part of the message.
There are a lot of unnecessary parentheses in the code – AppleScript needs some of these to delimit semantic command blocks, but not all of them…
All together mean your code can be modified to:
set computerName to do shell script "networksetup -getcomputername"
set folderAlias to path to users folder
tell application "System Events" to set folderSize to physical size of folderAlias
set folderSize to round(folderSize / 1.0E+9 * 100) / 100
display alert "User profile backup utility" message ¬
"The computer name is: " & computerName & return & return & ¬
"The '" & (POSIX path of folderAlias) & "' directory size is: " & "~" & folderSize & " GB" & return & return & ¬
"Would you like to backup the '" & (POSIX path of folderAlias) & "' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set shellCmd to "hdiutil create ~/Desktop/'" & computerName & "'.dmg -srcfolder /test/"
-- progress bar dialog display initialization goes here
try
set shellOutput to do shell script shellCmd with administrator privileges
end try
-- progress bar dialog hiding goes here
display dialog shellOutput
Although not as pretty as kopischke's suggestion, a quick and dirty way to get progress information is to run the command in the terminal itself.
set comd to "hdiutil create -puppetstrings '~/Desktop/" & computername & ".dmg' -srcfolder '/test/'"
tell application "Terminal" to do script comd