How do I from this list of records, get a 'choose from list' showing only 'Fornavn2' and 'Efternavn2', but setting var to corresponding 'ElevID2'???
I know this is not the correct syntax, but it goes to show what I want:
set var to ElevID2 of varEleveriklasse to choose from list (Fornavn2 of varEleveriklasse & " " & Efternavn2 of varEleveriklasse)
List:
set varEleveriklasse to {{Fornavn2:"Kenneth", Efternavn2:"Oddersen", ElevID2:"23442"}, {Fornavn2:"Thomas", Efternavn2:"Johansen", ElevID2:"23452"}, {Fornavn2:"Johan", Efternavn2:"Thomasen", ElevID2:"76590"}, {Fornavn2:"Charlotte", Efternavn2:"Frandsen", ElevID2:"78569"}, {Fornavn2:"Mathilde", Efternavn2:"Charlottesen", ElevID2:"64569"}}
It's impossible to populate the list without a repeat loop.
A smart solution to get the index of the chosen item is to include it in the list.
set varEleveriklasse to {{Fornavn2:"Kenneth", Efternavn2:"Oddersen", ElevID2:"23442"}, ¬
{Fornavn2:"Thomas", Efternavn2:"Johansen", ElevID2:"23452"}, ¬
{Fornavn2:"Johan", Efternavn2:"Thomasen", ElevID2:"76590"}, ¬
{Fornavn2:"Charlotte", Efternavn2:"Frandsen", ElevID2:"78569"}, ¬
{Fornavn2:"Mathilde", Efternavn2:"Charlottesen", ElevID2:"64569"}}
set fullNameList to {}
set indexCounter to 1
repeat with anItem in varEleveriklasse
set end of fullNameList to (indexCounter as text) & space & anItem's Fornavn2 & space & anItem's Efternavn2
set indexCounter to indexCounter + 1
end repeat
set chosenItem to choose from list fullNameList
if chosenItem is false then return
set chosenItem to item 1 of chosenItem // chosenItem is a list or boolean false
set listIndex to word 1 of chosenItem as integer
set ElevID to ElevID2 of item listIndex of varEleveriklasse
display dialog ElevID
Related
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.
Background: I am trying to pass caller information from a telephony application (Phone Amego) to my Samsung tv using its AllShare feature. In order to do so I have to send a soap message with the caller information. Phone Amego provides an easy way to assign an applescript to call events. But, I have no programming experience whatsoever!
Sofar I have succeeded in making a script which reads a soap message, updates the required fields and sends it to my tv. Perfect, at least the result, the code may not be perfect but it works. Here is the code.
set callerID_string to "John Doe : 1-917-123-4567"
set AppleScript's text item delimiters to {":"}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""}
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
tell application "Finder"
set theFile to alias "Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access alias "Macintosh HD:Users:Marc:Desktop:Test.txt" with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
end try
-- Close the file
close access myFile
end snr
set cmd to "/Usr/bin/nc 10.0.1.7 52235 < /Users/Marc/Desktop/Test.txt"
do shell script cmd
Problem: In the script above I have set a value to the variable callerID_string, but I should obtain it from Phone Amego through the handler call_from(callerID_string). But whatever I try, I cannot pass that callerID_string to my code. It consists of 2 parts namely the caller's name and number. The code should start like:
on call_from(callerID_string)
Any help would be highly appreciated.
I assume your script is running with the other app at the same time and it needs that handler and therefore a little re-designing so we can call the (former main) code as a subroutine.
I'm not sure if I understood the situation correctly but here it is anyway:
I added the on call_from... handler which calls the rest of the code as subroutine (myAction).
First commented line in code can be uncommented and used to test-run it with AppleScript Editor. Remove the line when not needed anymore.
testFilePath is a property and globally visible. Also, I changed the hardcoded file-path-stuff so it finds the path to the desktop.
property testFilePath : ""
-- my myAction("John Doe : 1-917-123-4567")
on call_from(callerID_string)
my myAction(callerID_string)
end call_from
on myAction(CIS)
if CIS is "" then
tell me to activate
display dialog "Caller ID is empty." buttons {"Quit"} default button 1 with icon 0
return
end if
set pathToDesktop to (path to desktop) as text
set testFilePath to pathToDesktop & "Test.txt"
set callerID_string to CIS -- "John Doe : 1-917-123-4567"
set lastTextItemDelimeter to AppleScript's text item delimiters
set AppleScript's text item delimiters to {" : "}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""} -- or lastTextItemDelimeter if you want to change it back to last
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
set templateFile to pathToDesktop & "IncCallMBsTemplate.txt"
tell application "Finder"
set theFile to templateFile as alias -- Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
set cmd to "/usr/bin/nc 10.0.1.7 52235 < " & quoted form of (POSIX path of testFilePath)
do shell script cmd
end myAction
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access (testFilePath as alias) with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
on error the error_message number the error_number
-- display dialog "Error: " & the error_number & ". " & the error_message buttons {"Cancel"} default button 1
log "Error: " & the error_number & ". " & the error_message
end try
-- Close the file
close access myFile
end snr
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
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
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