Apple Script: how do I watch for new download file with specific name to trigger a script? - applescript

I have a script that downloads a report from an online service, waits a specified amount of time e.g. 30secs for the file to actually download and then renames the file. The script then repeats
What I would like to do is instead of putting a static delay in the script, to create a trigger that looks for the new file and once it appears triggers the renaming portion of the script.
The downloaded file name is constant.
The current portion of the script looks like this
`
tell application "Finder" to activate
tell application "System Events"
delay Wait_Time
key code 125
tell application "Finder"
set name of (selection as alias) to (the clipboard)
end tell
end tell
ultimately what I would like is to replace the delay Wait_Time with a something like:
repeat until file name found
Search Folder for "file name"
end repeat
select new file
rename new file to clipboard
obviously this wont work but it kind of captures my logic.
I have also tried a few other possible solutions but Im new to AppleScript and not overly confident that these approaches are suitable for my application.
The below is an example of a solution I have tried. This is just an example and im not sure if this particular code can even get me to where I need to be. I thought I would include it to show just how lost I am.
set excludes to {"Folder", "Application"}
tell application "Finder"
set search_folder to folder "Macintosh HD:Users:XXXXXXXX:Library:CloudStorage:OneDrive-Flinders:Flinders Connect Stats:Source Stats:Cisco Finesse:Agent State Summary by Interval Report"
set foundItems to (every item in search_folder whose name contains "Agent State Summary by Interval Report" and kind is not in excludes) as alias list
if foundItems is {} then return
repeat with once from 1 to 100
try
if (count of foundItems) = 1 then
tell application "Finder" to activate
tell application "System Events"
key code 125
tell application "Finder"
set name of (selection as alias) to (the clipboard)
end tell
end tell
exit repeat
end if
end try
end repeat
return
end tell
Im sure you can see I have no idea what im doing.
Anyway any help would be awesome!

I have found a solution... if anyone has ideas for improvement please let me know.
tell application "Finder" to activate
tell application "System Events"
repeat until (exists (files of folder folderPath whose name contains "Agent State Summary by Interval Report"))
delay 1
end repeat
end tell
tell application "System Events"
key code 125
tell application "Finder"
set name of (selection as alias) to (the clipboard)
end tell
end tell
end repeat
say "Finished!"
display dialog "Completed"
The original solution was found here AppleScript: How to repeat a search for a file until it is found?

Related

Open/search Spotify track in Apple Music (with Applescript)

I'd like an easy way to switch from a Spotify release to the same release in Apple Music.
I already found a way to search for the currently playing Spotify track in the Apple Music web player with Applescript:
tell application "Spotify"
if player state is not stopped then
set currentArtist to artist of current track as string
set currentTrack to name of current track as string
open location "https://music.apple.com/search?term=" & currentArtist & " " & currentTrack
end if
end tell
I'd love to:
Open the search in the native Music.app, not the web player. Is this supported?
Ideally not do a search, but go straight to the same release. Maybe with ISRC codes?
Take any selected Spotify track, not just the currently playing one. Looking at the Spotify Applescript dictionary tells me this in not possible.
had a similar problem right now and quickly hacked it out. In my case I want to simply trigger a search on the Music app.
Opened Automator and created a new "Service".
Workflow receives current > "Text" > in "every application".
Here's the AppleScript:
on run {input, parameters}
tell application "Music"
activate
end tell
tell application "System Events"
tell process "Music"
set window_name to name of front window
set value of text field 1 of UI element 1 of row 1 of outline 1 of splitter group 1 of window window_name to input
keystroke ""
key code 36
end tell
end tell
return input
end run
I saved it as "Find on Music" in Automator and now I can select text, right click > Service > Find on Music and Music plops open and shows me the results for the selected text. I hope you can use some parts of it.
I just figured out how to pass text from wherever to the search field in Music, with help from daemon's answer, which no longer works. This should work for what you want to do in conjunction with what you have.
Replace your "open location" line with a variable name for your concatenated string. Add this code below yours and pass that variable in place of 'input' (in my case 'input' is text from any application, which I use to select text of an artist name in an email/webpage/message that I want to send to Music's search).
First it checks to see if the main Music window is open vs the MiniPlayer, and open it if not to enable search via cmd-O, the cmd-F to find, then passes the input and hits return:
tell application "Music"
activate
end tell
tell application "System Events"
if not (exists (window "Music" of process "Music")) then
tell process "Music"
keystroke "0" using command down
end tell
end if
tell process "Music"
keystroke "f" using command down
keystroke input
key code 36
end tell
end tell
So, something like this (I don't have Spotify to check that section, but this should work assuming your code there is correct):
tell application "Spotify"
if player state is not stopped then
set currentArtist to artist of current track as string
set currentTrack to name of current track as string
set spotTrack to currentArtist & " " & currentTrack
end if
end tell
tell application "Music"
activate
end tell
tell application "System Events"
if not (exists (window "Music" of process "Music")) then
tell process "Music"
keystroke "0" using command down
end tell
end if
tell process "Music"
keystroke "f" using command down
keystroke spotTrack
key code 36
end tell
end tell
The only thing I couldn't figure out is how to check if the search field is already in focus, because if it is, the cmd-F causes a system alert sound. Generally not an issue as typically you'll search and interact with something else before running this script again, so calling it good. :)

Applescript quicklook: arrow key down 1000 times

I'm a total beginner in apple script.
I would like to open a folder directory that contains hundreds of photos and to view each photo 1 second with quick look and then go to the next (suppose to use down arrow / key code '124').
I don't have any idea of how to build the script. I tried to compile some formulas from other questions or use the manual rec but it doesn't work.
Thanks!
Try following script. I made the delay longer so you have time to stop the script (to test it):
set timePerPreview to 5
set thisFolder to (choose folder with prompt "Pick the folder containing the files to process:") as string
tell application "Finder"
activate
open folder thisFolder
select every item in folder thisFolder
delay 2
set fileCount to (count items in (get selection)) # (count files in folder thisFolder) is faster but counts also .DS_Store and other invisible files
if fileCount = 0 then
beep
return
end if
end tell
pressSpaceInFinder()
delay timePerPreview / 2 # first it has to open the window which seems to need a little time
repeat fileCount - 1 times # -1 because the first item is already displayed
delay timePerPreview
# do shell script "sleep" & space & timePerPreview as text
tell application "System Events"
tell application process "Finder"
set frontmost to true
# cursor right = 124, left = 123
key code 124
end tell
end tell
end repeat
delay timePerPreview
pressSpaceInFinder()
on pressSpaceInFinder()
tell application "System Events"
tell application process "Finder"
set frontmost to true
keystroke space
end tell
end tell
end pressSpaceInFinder
Be aware that it is hard to stop the script since the Finder gets activated every second. Will see if I can add a check to see if the Preview window is open and if not, stop the script.
Also: (without that check) the script will, when the Preview window is open before running, close it but you can just press the space key to open it again.
Also, the first part (getting the file count) isn't so great and may fail when the delay is to short. We could scan the whole folder for images and only count / select those (it has a file template for the scanner, see menu File) but of course you can remove the whole counting thing and just do repeat 1000 times.

Applescript to search Evernote notes

So I have a Hazel rule that says "If I see a statement from this company, do X" in this case I want X to do the following.
Open Evernote
Check to see if I have a note with the same title as the downloaded file's title.
If no, create a note from that file. If yes, do nothing.
So what I wrote so far is.
global fileNamez
tell application "Finder"
set fileNamez to name of theFile
tell application "Evernote"
activate
delay (3)
set searchString to "\"" & fileNamez & "\""
set matches to find notes searchString
if (not (matches exists)) then
display dialog "no matches"
create note title fileNamez from file theFile
end if
end tell
end tell
The problem is the searching, it does not work, and I don't know whats wrong with it. Anyone have any ideas?
Try:
tell application "Finder" to set fileNamez to name of theFile
if application "Evernote" is not running then
launch application "Evernote"
delay 3
end if
tell application "Evernote" to set matches to find notes fileNamez
if matches = {} then
tell application "Evernote" to set resultNote to create note from file theFile title fileNamez
tell application "SystemUIServer" to display dialog "no matches" buttons {"OK"}
end if

How to get name of frontmost app with AppleScript and use it to get the filepath

What I try to do:
When I'm in one of my text editors (TextEdit, Byword, FoldingText) I want this AppleScript to display the file path.
I figured asking for the frontmost window app get's me the apps name nice and easily and then I can ask for the POSIX path in the next step.
The Problem:
The script is already 99% there, but I'm missing something. When I try to use the variable of activeApp it doesn't work and I get this error:
Error Number:System Events got an error: Can’t get application {"TextEdit"}.
-1728
Here's the script:
tell application "System Events"
set activeApp to name of application processes whose frontmost is true
--This doesn't work either:
--do shell script "php -r 'echo urldecode(\"" & activeApp & "\");'"
tell application activeApp
set myPath to POSIX path of (get file of front document)
end tell
display dialog myPath
end tell
If I exchange activeApp with "TextEdit" everything works. Help would be appreciated.
Maybe there's something in here that helps: Get process name from application name and vice versa, using Applescript
Either get the path property of a document or use System Events to get value of attribute "AXDocument":
try
tell application (path to frontmost application as text)
(path of document 1) as text
end tell
on error
try
tell application "System Events" to tell (process 1 where frontmost is true)
value of attribute "AXDocument" of window 1
end tell
do shell script "x=" & quoted form of result & "
x=${x/#file:\\/\\/}
x=${x/#localhost} # 10.8 and earlier
printf ${x//%/\\\\x}"
end try
end try
The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn. The second method requires access for assistive devices to be enabled.
You are asking for...
set activeApp to name of application processes whose frontmost is true
Notice "processes", that's plural meaning you can get several processes in response so applescript gives you a list of names. Even though only one application is returned it's still in list format. Also see that your error contains {"TextEdit"}. The brackets around the name mean it's a list, so the error is showing you the problem.
You can't pass a list of names to the next line of code. As such you have a couple of choices. 1) you can ask for only 1 process instead of all processes. That will return a string instead of a list. Try this code...
set activeApp to name of first application process whose frontmost is true
2) you can work with the list by using "item 1 of the list". Try this code...
set activeApps to name of application processes whose frontmost is true
set activeApp to item 1 of activeApps
Finally, you shouldn't be telling system events to tell the application. Separate those 2 tell blocks of code. Here's how I would write your code.
tell application "System Events"
set activeApp to name of first application process whose frontmost is true
end tell
try
tell application activeApp
set myPath to POSIX path of (get file of front document)
end tell
tell me
activate
display dialog myPath
end tell
on error theError number errorNumber
tell me
activate
display dialog "There was an error: " & (errorNumber as text) & return & return & theError buttons {"OK"} default button 1 with icon stop
end tell
end try
I can't promise the "get file of front document" code will work. That depends on the application. Not all applications will understand that request. That's why I used a try block. In any case though you can be certain you are addressing the proper application. Good luck.
I've been using this snippet for a while, seems to work for all Cocoa apps (not sure about X11):
set front_app to (path to frontmost application as Unicode text)
tell application front_app
-- Your code here
end tell
None of this seems to work with a compiled AppleScript saved as an application and placed on the Dock. Whenever you run the application, IT is the frontmost, not the application that is showing its front window. That application becomes inactive as my Applescript runs. How do I write an Applescript application that isn't active when it runs?
I may have found a solution to the problem listed above. Just tell the user to reactivate the desired application, and give them time.
tell application "Finder"
activate
say "Click front window of your application"
delay 5
set myapp to get name of first application process whose frontmost is true
-- etc.
-- your code
end tell

Listing all windows of all applications

I am trying to write an applescript script that resizes all open windows. In order to make sure that I'm getting to all the windows, I'm making my script say the name of the application as well as the number of open windows of that application.
Interestingly, while I hear the names of all my open applications, my script says that they all have 0 windows open. How can I fix this issue?
Here's my code:
tell application "System Events"
repeat with theProcess in (every process)
if background only of theProcess is false then
if name of theProcess is not "Finder" then
if name of theProcess is "Google Chrome" then
say "Chrome woo hoo"
say (count windows as string)
else
say name of theProcess as string
say (count windows as string)
tell theProcess
repeat with theWindow in windows
say "found a window of"
say (name of theProcess) as string
tell theWindow
click button 2
end tell
end repeat
end tell
end if
end if
end if
end repeat
end tell
I'm on Mac OS X 10.7.5, using automator 2.2.4 to write/run this applescript
You have to tell the process to count windows. After all it's the process that knows about its windows, not system events.
You have told the process to say its name e.g. "say name of theProcess as string" however you only use "say (count windows as string)"... no process is tied to that. Try "count windows of theProcess". Basically you have lines where sometimes you tell the process, other times you don't, and other times where you tell the process even though you've already told the process, so you do it twice. That's where you have "say (name of theProcess) as string" but that code is inside a "tell theProcess" block so it's already being told to theProcess.
Really you need to go through your code and be more precise. A tip... if you want to click a button in a window then the window must be frontmost on the screen otherwise you can't click it. Another tip... "name" is already a string so you don't need to coerce that to a string.
By the way, I agree with Michael Dautermann's comment to your post... there will be processes where you won't get access. But you'll find that out as you progress.
Here's how I would write your code. Basically I would get all of the variables at the beginning using a "tell theProcess" block. Then I can do stuff with those variables. I hope that helps. Notice that I only made the process frontmost which means if it has multiple windows open it will only click a button on the front window. You'll have to add code to make each window come to the front before you can click its button. Good luck.
tell application "System Events"
repeat with theProcess in processes
if not background only of theProcess then
tell theProcess
set processName to name
set theWindows to windows
end tell
set windowsCount to count of theWindows
if processName is "Google Chrome" then
say "Chrome woo hoo"
say windowsCount as text
else if processName is not "Finder" then
say processName
say windowsCount as text
if windowsCount is greater than 0 then
repeat with theWindow in theWindows
say "found a window of " & processName
tell theProcess
set frontmost to true
tell theWindow
click button 2
end tell
end tell
end repeat
end if
end if
end if
end repeat
end tell
I create a list of all open windows of visible applications on Mavericks like this:
tell application "System Events"
set this_info to {}
repeat with theProcess in (application processes where visible is true)
set this_info to this_info & (value of (first attribute whose name is "AXWindows") of theProcess)
end repeat
this_info -- display list in results window of AppleScript Editor
end tell
You need to allow any app using this to access the interface under Accessibility.

Resources