I didn't did an Applescript app on Xcode from ages,
here is my code
script AppDelegate
property parent : class "NSObject"
-- IBOutlets
property theWindow : missing value
property myTextField : missing value
on applicationWillFinishLaunching_(aNotification)
-- Insert code here to initialize your application before any files are opened
end applicationWillFinishLaunching_
on applicationShouldTerminate_(sender)
-- Insert code here to do any housekeeping before your application quits
return current application's NSTerminateNow
end applicationShouldTerminate_
on myButton_(sender)
-- AppleScript
end myButton_
on saveNote_(sender)
-- AppleScript
end saveNote_
end script
but I have this error :
/AppDelegate.applescript:32: error: Expected “end” but found unknown token. (-2741)
Command /usr/bin/osacompile failed with exit code 1
Can you help me here?
PS here is the AppleScript
to getInputByClass2(theClass, num)
tell application "Safari"
set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
end tell
return input
end getInputByClass2
getInputByClass2("field type-string field-DATAID", 0)
set theText to Unicode text
set theSource to getInputByClass2("field type-string field-DATAID", 0)
property leftEdge : "class=\"value\">"
property rightEdge : "</span>"
set saveTID to text item delimiters
set text item delimiters to leftEdge
set classValue to text item 2 of theSource
set text item delimiters to rightEdge
set theDATAID to text item 1 of classValue
set text item delimiters to saveTID
theDATAID
here is the result on xcode
You're using the reserved word date as a variable name which is not allowed. To avoid that use aDate or theDate or something meaningful compound like startDate.
Consider that you are actually using none of the variables at the end of the sections and most of the code is redundant and could be reduced with a repeat loop.
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.
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.
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"
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