Applescript to change rating of song currently playing in iTunes - applescript

I set up an applescript to change the rating of the current song in iTunes and it worked the first few times but now does nothing. Here is the code:
tell application "System Events"
if (name of processes) contains "iTunes" then
set iTunesRunning to true
else
set iTunesRunning to false
end if
end tell
if iTunesRunning then
tell application "iTunes"
repeat with theTrack in (get selection)
set the rating of theTrack to 100
end repeat
end tell
end if
Anyone see any glaring issues in there? FYI, this is attached to a global hotkey, but even opening it in Applescript Editor and hitting "Run" does nothing.

Ack. All I had to was ask to find the answer myself.
tell application "System Events"
if (name of processes) contains "iTunes" then
set iTunesRunning to true
else
set iTunesRunning to false
end if
end tell
if iTunesRunning then
tell application "iTunes"
set rating of current track to 100
end tell
end if

I don't remember where I found this, but it's a more robust version that might help you. I execute it with a key command using FastScripts. It brings up a dialog box prompting you to rate the current song on a scale of 0 to 5 with a default rating of 4.
tell application "Finder"
set frontApp to name of first process whose frontmost is true
end tell
set currTrack to ""
set thisNum to false
tell application "iTunes"
if player state = playing then
set currTrack to current track
set thisName to name of current track
set thisArt to artist of current track
set numList to {"0", "1", "2", "3", "4", "5", "", "Rate All"}
set thisRating to rating of currTrack
set songArt to ("'" & thisName & "' by " & thisArt)
end if
end tell
tell application frontApp
if currTrack = "" then
beep
tell application frontApp
display dialog "There is no song playing in iTunes at this time." buttons "OOPS" default button "OOPS" with icon note
end tell
else
if thisRating ≠ 0 then
set thisRating to 4
set thisList to (choose from list numList with prompt "Select a rating for this song:" & return & songArt & return & "Select \"Rate All\" to apply rating to all matching songs." default items thisRating OK button name "Select" with empty selection allowed and multiple selections allowed)
else
set thisList to (choose from list numList with prompt "Select a rating for this song:" & return & songArt & return & "Select \"Rate All\" to apply rating to all matching songs." OK button name "Select" with empty selection allowed and multiple selections allowed)
end if
end if
end tell
if thisList ≠ false then
--tell application "iTunes"
set thisRating to ""
repeat with i from 1 to count of items of thisList
set thisItem to item i of thisList
if thisItem = "Rate All" then
if thisRating = "" then
display dialog "You must select a rating to apply to this song." buttons "OK" default button "OK" with icon caution
else
tell application "iTunes"
set dataList to {name, artist, album, time} of currTrack
set addSourceData to {time, size, year, bit rate} of currTrack
set matchList to {"Time", "Size", "Year", "Bit Rate"}
set matchDef to (choose from list matchList with prompt "You may choose criteria to match in addition to track name, artist, and album." with multiple selections allowed and empty selection allowed)
if matchDef = {} then set matchDef to false
set trackList to (every track of library playlist 1 whose ((name = item 1 of dataList) and (artist = item 2 of dataList) and (album = item 3 of dataList)))
set trackCount to count of items of trackList
repeat with j from 1 to trackCount
set thisTrack to item j of trackList
set notMatch to false
if matchDef ≠ false then
set addSynchData to {time, size, year, bit rate} of thisTrack
repeat with m from 1 to 4
if ((m = 1) and (matchDef contains "Time")) or ((m = 2) and (matchDef contains "Size")) or ((m = 3) and (matchDef contains "Year")) or ((m = 4) and (matchDef contains "Bitrate")) then
if item m of addSourceData ≠ item m of addSynchData then
set notMatch to true
exit repeat
end if
end if
end repeat
end if
if notMatch = false then
set rating of thisTrack to thisRating
end if
end repeat
if thisRating > 0 then
set thisRating to thisRating / 20 as integer
end if
end tell
display dialog "Rating of " & thisRating & " applied to " & trackCount & " song(s)." buttons "OK" default button "OK" giving up after 3
end if
else
set thisRating to thisItem * 20
tell application "iTunes"
set rating of currTrack to thisRating
end tell
end if
end repeat
--end tell
end if

Related

Get data from webpage via Apple script

I'm trying to get the data of Crypto name, Price, and % from the webpage https://www.worldcoinindex.com/
How can i get the % column value via the following scripts?
set theHtml to do shell script "curl -s " & quoted form of "https://www.worldcoinindex.com"
set text item delimiters to {"<tbody>", "</tbody>"}
set tableContents to theHtml's text item 2 # item 2 is the body of the price table
set text item delimiters to {"<h2>"} # site uses new h2 for each currency
set tableChunks to tableContents's text items 2 thru -1
set pasteStr to ""
repeat with aChunk in tableChunks
set text item delimiters to "><span>$ </span><span class=\"span\">"
tell aChunk's text item 1 to set {theSymbol, thePrice} to {first word, last word}
set pasteStr to pasteStr & theSymbol & tab & thePrice & return
end repeat
set the clipboard to pasteStr
Here is an alternate way for your consideration:
Note that this requires Allow JavaScript from Apple Events to be checked on the hidden Develop menu in Safari.
To unhide the hidden Develop menu:
Safari > Preferences… > Advanced > [√] Show Develop menu in menu bar
Example AppleScript code:
tell application "Safari"
make new document ¬
with properties {URL:"https://www.worldcoinindex.com"}
my waitForSafariPageToFinishLoading()
tell front document
set tickerList to {}
set lastPriceList to {}
set percentageList to {}
repeat with i from 0 to 99
set ticker to ¬
do JavaScript ¬
"document.getElementsByClassName('ticker')[" & i & "].innerText;"
copy words of ticker as text to end of tickerList
set lastPrice to ¬
do JavaScript ¬
"document.getElementsByClassName('number pricekoers lastprice')[" & i & "].innerText;"
copy lastPrice to end of lastPriceList
set percentage to ¬
do JavaScript ¬
"document.getElementsByClassName('percentage')[" & i & "].innerText;"
copy percentage to end of percentageList
end repeat
end tell
end tell
set tempListItem to {}
set groupedItemsList to {}
repeat with i from 1 to 100
copy item i of tickerList to end of tempListItem
copy item i of lastPriceList to end of tempListItem
copy item i of percentageList to end of tempListItem
copy tempListItem to end of groupedItemsList
set tempListItem to {}
end repeat
set tabDelimitatedListAsText to ""
repeat with anItem in groupedItemsList
set {TID, AppleScript's text item delimiters} to ¬
{AppleScript's text item delimiters, tab}
set thisItem to text of anItem as text
set AppleScript's text item delimiters to TID
set tabDelimitatedListAsText to ¬
tabDelimitatedListAsText & thisItem & linefeed
end repeat
set the clipboard to tabDelimitatedListAsText
on waitForSafariPageToFinishLoading()
-- # Wait for page to finish loading in Safari.
-- # This works in macOS Catalina and
-- # macOS Big Sur and may need adjusting
-- # for other versions of macOS.
tell application "System Events" to repeat until ¬
exists (buttons of groups of toolbar 1 of window 1 of ¬
process "Safari" whose name = "Reload this page")
delay 0.5
end repeat
end waitForSafariPageToFinishLoading
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Applescript - Check if Page Content of URLs List contain THIS_TEXT | Output all these URLs

Trying the following:
My script returns approx. 20 URLs as variable Single_URLs
Check if these URLs contain THIS_TEXT
Keep URL's containing THIS_TEXT
Delete the other URLs from the result
Pure Applescript or Shell.
My example script just checks IF the provided URL contains THIS_TEXT as i could not get any further by now.
--Open Pages
set site_url to "https://teespring.com/shop/CLASSIC-DODGE-CHARGER-MOP?aid=marketplace&tsmac=marketplace&tsmic=search#pid=212&cid=5819&sid=front"
tell application "Safari"
activate
open location site_url
end tell
-- wait until page loaded
property testingString : "CLASSIC DODGE CHARGER" --Text on website to look for
set pageLoaded to false
tell application "Safari"
repeat while pageLoaded is false
set readyState to (do JavaScript "document.readyState" in document 1)
set pageText to text of document 1
if (readyState is "complete") and (pageText contains testingString) then set pageLoaded to true
delay 0.2
end repeat
end tell
-- get number of links
set theLinks to {}
tell application "Safari" to set num_links to (do JavaScript "document.links.length" in document 1)
set linkCounter to num_links - 1
-- retrieve the links
repeat with i from 0 to linkCounter
tell application "Safari" to set end of theLinks to do JavaScript "document.links[" & i & "].href" in document 1
end repeat
theLinks
set nonExcludedURLs to {}
pageLoaded
This is a a charitable project to help Artists not being cheated. Every help is very welcome, Thanks.
Here's a script that would do that with AppleScript:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
on run
set URLFoundItems to {}
set SearchItemsList to {"CLASSIC DODGE CHARGER"}
set URLList to {"https://teespring.com/shop/CLASSIC-DODGE-CHARGER-MOP?aid=marketplace&tsmac=marketplace&tsmic=search#pid=212&cid=5819&sid=front"}
repeat with i from 1 to count of URLList
set URLv to item i of URLList
tell application "Safari"
try
tell window 1
set current tab to (make new tab with properties {URL:URLv})
end tell
on error
make new document with properties {URL:URLv}
end try
set readyState to (do JavaScript "document.readyState" in document 1)
set pageLoaded to false
repeat while pageLoaded is false
set readyState to (do JavaScript "document.readyState" in document 1)
set SearchIn to source of document 1
if (readyState is "complete") and SearchIn ≠ "" then
set pageLoaded to true
else
delay 0.2
end if
end repeat
repeat with z from 1 to count of SearchItemsList
set SearchString to item z of SearchItemsList
set x to offset of SearchString in SearchIn
if x > 0 then
set URLFoundItems to URLFoundItems & URLv & " (" & SearchString & ")" as string
end if
end repeat
tell window 1
close current tab
end tell
end tell
end repeat
return URLFoundItems
end run
I hope this helps.

How to display dialog "error" when variable returns incorrect answer

Okay so my code is below and when I input a word spelled incorrectly or a phrase that doesn't make sense it displays a dialog with "msng" but I want I to display an error message instead. I tried using both if theAnswer is/ contains "msng" then... but it will not work, any help is appreciated.
tell application "Safari"
quit
end tell
set defaultAnswer to ""
set cancelButton to "Cancel"
set buttonResearch to "ReSearch"
display dialog "Query: " default answer defaultAnswer buttons {cancelButton, buttonResearch} default button buttonResearch cancel button cancelButton with icon 1
copy the result as list to {button_pressed, text_returned}
tell application "Dragon Dictate"
set listening to false
end tell
if (button_pressed is buttonResearch) and (text_returned is not "") then
set theUrl to "http://www.wolframalpha.com/input/?i=" & encode_text(text_returned, true, false)
tell application "Safari"
tell window 1 to set current tab to (make new tab with properties {URL:theUrl})
tell me to say "let me look that up for you now"
tell document 1
repeat -- wait until loaded
delay 2
if (do JavaScript "document.readyState") = "complete" then exit repeat
end repeat
do JavaScript "document.getElementById('pod_0200').getElementsByClassName('action subpod-copyablept ')[0].click()" -- show the popup window
set theAnswer to do JavaScript "document.body.lastChild.getElementsByTagName('pre')[0].innerHTML;" -- get the answer in this popup window
end tell
end tell
activate
if theAnswer contains "msng" then
display dialog "There was an error, you may have misspelled a word or phrased it incorrectly"
else
display dialog theAnswer
end if
end if
tell application "Safari"
quit
end tell
-- encoding high-ASCII characters:
on encode_char(this_char)
set the ASCII_num to (the ASCII number this_char)
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 ((ASCII_num div 16) + 1) of the hex_list
set y to item ((ASCII_num mod 16) + 1) of the hex_list
return ("%" & x & y) as string
end encode_char
-- TEXT ENCODING: encode spaces and high-level ASCII characters (those above 127)
-- encode_URL_A = encode most of the special characters reserved for use by URLs.
on encode_text(this_text, encode_URL_A, encode_URL_B)
set the standard_characters to "abcdefghijklmnopqrstuvwxyz0123456789"
set the URL_A_chars to "$+!'/?;&#=#%><{}[]\"~`^\\|*"
set the URL_B_chars to ".-_:"
set the acceptable_characters to the standard_characters
if encode_URL_A is false then set the acceptable_characters to the acceptable_characters & the URL_A_chars
if encode_URL_B is false then set the acceptable_characters to the acceptable_characters & the URL_B_chars
set the encoded_text to ""
repeat with this_char in this_text
if this_char is in the acceptable_characters then
set the encoded_text to (the encoded_text & this_char)
else
set the encoded_text to (the encoded_text & encode_char(this_char)) as string
end if
end repeat
return the encoded_text
end encode_text
Use
if theAnswer is missing value then
display dialog "There was an error, you may have misspelled a word or phrased it incorrectly"
else
display dialog theAnswer
end if
Because «class msng» is the raw AppleScript code for missing value.
The display dialog command show the name of this class --> "msng"

Using Applescript to export list of URLs based on tags?

I am new to Applescript, so I found an awesome script online that will list all Evernote snaps that have an associated URL . For listing all snaps with URLs, this solution is great. How could I modify this script to filter the listed URLs based on specific tags?
Script I am currently using: http://veritrope.com/code/save-a-list-of-urls-from-your-evernote-items-as-a-file/
tell application "Evernote"
activate
set listOfNotebooks to {}
set EVNotebooks to every notebook
repeat with currentNotebook in EVNotebooks
set currentNotebookName to (the name of currentNotebook)
copy currentNotebookName to the end of listOfNotebooks
end repeat
set Folders_sorted to my simple_sort(listOfNotebooks)
set SelNotebook to choose from list of Folders_sorted with title "Select Evernote Notebook" with prompt ¬
"Current Evernote Notebooks" OK button name "OK"
set EVnotebook to item 1 of SelNotebook
set listofNotes to {}
set note_Records to {}
set allNotes to every note in notebook EVnotebook
repeat with currentNote in allNotes
try
set currentNoteURL to (the source URL of currentNote)
set currentNoteTitle to title of currentNote
if currentNoteURL is not missing value then
copy currentNoteURL to the end of listofNotes
copy {name:currentNoteTitle, URL:currentNoteURL} to the end of note_Records
end if
end try
end repeat
set Notes_sorted to my simple_sort(listofNotes)
set SelNote to ¬
choose from list of Notes_sorted with title ¬
"List Of URLs In Notes" OK button name "Export List" cancel button name "Close Window" with empty selection allowed
set record_Text to {}
repeat with note_Record in note_Records
set theCurrentRecord to ("Title: " & name of note_Record & return & "URL: " & URL of note_Record & return & return) as text
copy theCurrentRecord to the end of record_Text
end repeat
if (SelNote is not false) then
tell application "System Events"
-- convert list to text FILE
set ExportList to "Current List of URLs in Notes for " & EVnotebook & "-- " & (current date) & return & return & record_Text as Unicode text
set fn to choose file name with prompt "Name this file" default name "URL List for Notebook Named " & EVnotebook & ¬
".txt" default location (path to desktop folder)
set fid to open for access fn with write permission
write ExportList to fid
close access fid
end tell
else
set EVnotebook to item 1 of SelNotebook
end if
end tell
on simple_sort(my_list)
set the index_list to {}
set the sorted_list to {}
repeat (the number of items in my_list) times
set the low_item to ""
repeat with i from 1 to (number of items in my_list)
if i is not in the index_list then
set this_item to item i of my_list as text
if the low_item is "" then
set the low_item to this_item
set the low_item_index to i
else if this_item comes before the low_item then
set the low_item to this_item
set the low_item_index to i
end if
end if
end repeat
set the end of sorted_list to the low_item
set the end of the index_list to the low_item_index
end repeat
return the sorted_list
end simple_sort
Apologies for my code block being funky. If any mods can fix it I'd appreciate the help.
In your repeat with currentNote in allNotes loop you could add something like this:
set allTags to tags of currentNote
repeat with currentTag in allTags
if name of currentTag is "your_specific_tag" then
do what you want
...........
end if
end repeat

Applescript to repeat complete script for files in a folder

I have managed to get all this code together now and just need the last step to work. Any help would be greatly appreciated.
I have setup this script to open an .xlsx file in a folder, change the date, save it then PDF to another folder. It then creates a mail by looking up the client code (found in the excel file) to subsequently look for this code in a Database.xlsx file and return the e-mail address of the client and add it to the "To" field in mail. It then attaches the newly created PDF to this mail and I can just click and send.
The script stops after the first .xlsx file has been opened, just so I can check the details is correct before it PDF's and creates the mail.
My question is: How do I get this process to repeat for each file in the initial folder? I have tried the repeat function, but to no avail.
Any help would be greatly appreciated.
Thank you.
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
set theFolderList to list folder theFolder without invisibles
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd
property dialog_timeout : 36000
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
You need to move your handler outside of the repeat block:
property dialog_timeout : 36000
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
tell application "System Events" to set theFolderList to name of every file of folder theFolder whose visible is true
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd

Resources