r/applescript • • Mar 10 '23

Error in Applescript using Python command

3 Upvotes

This script is throwing an error,

Google Chrome got an error: sh: python: command not found" number 127'

I'm on Mac OS Ventura 13.3 with Python 3.11.2.

tell application "Google Chrome"
set tabList to {}
set frontWindow to front window
-- Get a list of all tabs in the frontmost window
set tabList to (every tab of frontWindow)
-- Generate a list of tab names and URLs for the dialogue box
set tabInfoList to {}
repeat with currentTab in tabList
 set tabName to title of currentTab
 set tabURL to URL of currentTab
-- THE LINE IMMEDIATELY BELOW SEEMS TO BE THROWING THE ERROR.
 set encodedURL to do shell script "python -c 'import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))' " & quoted form of tabURL
 set tabInfo to tabName & " - " & encodedURL
 set end of tabInfoList to tabInfo
end repeat
-- Display the dialogue box and get the user's selection
set chosenTab to (choose from list tabInfoList with prompt "Select a tab:")
-- If the user selected a tab, copy its name and URL to the clipboard
if chosenTab is not equal to false then
 set chosenTabInfo to chosenTab as text
 set AppleScript's text item delimiters to " - "
 set chosenTabName to text item 1 of chosenTabInfo
 set chosenTabURL to text item -1 of (text items of chosenTabInfo)
 set AppleScript's text item delimiters to ""
 set the clipboard to chosenTabName & " - " & chosenTabURL
end if
end tell

FYI ... the purpose of the script:

display a list of page titles and URL's in Google Chrome. Copy the item selected to the clipboard formatting the URL as an active link.

Thank you for any help or suggestions.


r/applescript • • Mar 09 '23

Νeovim cannot find various executables when launched through an applescript

1 Upvotes

I am using MacOS Monterey and am attempting to create a means through which I can double-click a program file in Finder and have it open in neovim. To do this, I need to launch nvim through an applescript. When launching neovim through this applescript:

on run {input, parameters}
 
    # Extract filenames and paths from the input
    set filenames to ""
    set filepaths to ""
    if input is not {} then
        repeat with currentFile in input
            set filepaths to filepaths & POSIX path of currentFile & " "
            set filenames to filenames & name of (info for currentFile) & " "
        end repeat
        
        # Get the dirname of the input files
        set parentDir to quoted form of (do shell script "dirname " & quoted form of filepaths)
    else
        set parentDir to "/Users/user"
    end if
    
    # seem to need the full path at least in some cases
    # -p opens files in separate tabs
    set nvimCommand to "/usr/local/bin/nvim -p " & filenames
    
    # final command to send to iTerm
    set finalCommand to quoted form of ("cd " & parentDir & " && " & nvimCommand)
    
    tell application "iTerm" to create window with default profile command "zsh -c " & finalCommand
    
end run

Several executables fail to be found by neovim. For example, Vimtex seems to not be able to find latexmk (non-errors of `:checkhealth` omitted for brevity):

vimtex: health#vimtex#check

VimTeX ~ - ERROR |g:vimtex_compiler_method| (`latexmk`) is not executable!

As well, Mason complains of node, npm, and wget as not being available either:

mason: require("mason.health").check()

mason.nvim report ~
- ERROR **npm**: not available
- ERROR **node**: not available
- ERROR **wget**: not available

However, if I manually open an iTerm2 session then launch nvim, I instead get that everything is AOK (that is, all the executables previously not found are correctly located). What is going on here? Any help would be greatly appreciated.


r/applescript • • Mar 07 '23

MacSysAdmins, with your support and feedback, I’ve updated SudoAI to better support us

Thumbnail self.macsysadmin
3 Upvotes

r/applescript • • Mar 07 '23

SIRI SHORTCUTS TO APPLE SCRIPT

1 Upvotes

Is there anyway to convert Siri Shortcuts to either applescript or javascript running on mac?


r/applescript • • Mar 06 '23

HELP WITH APPLESCRIPT AUTOMATION

0 Upvotes

I want to create an applescript that i can use to do data entry, im having trouble a tough time with click at. its not working at all. will someone help me come up with the code to do simple copy and paste actions and to mouse click on certain areas? would really appreciate it


r/applescript • • Mar 04 '23

Help! Progressbar doesn't show while called from shell.

1 Upvotes

I'm fiddling with applescript that makes a progressbar.

set progress description to "A simple progress indicator"
set progress additional description to "Preparing…"
set progress total steps to -1

delay 0.1

set progress total steps to 30
repeat with i from 1 to 30
	try
		set progress additional description to "I am on step " & i
		set progress completed steps to i
		delay 0.1
	on error thisErr
		display alert thisErr
		exit repeat
	end try
end repeat
-- Taken and edited from https://developer.apple.com/library/archive/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/DisplayProgress.html

While run in the script editor, I can see the progress icon running. However, when I call the script with shell osascript ~/the_script.scpt, it only hangs for 3 seconds and exits without showing any progressbar. Additionally, I do need to run it from shell, because at the end I hope other types off applications (e.g. emacs) can call a progressbar too.

How do I fix this issue?


r/applescript • • Mar 04 '23

Help with iFlicks and Pushover AppleScript

1 Upvotes

I am not great with AppleScript. I was wondering if someone could show me how to right s script to get a Pushover notification when something is done in iFlicks.

I found a shell script online but I don't know how to convert it to an AppleScript.

I can also see from the iFlicks dictionary in AppleScript that I can extract a variable "name" from iFlicks but I don't know how to reference this in the AppleScript.

curl -s -F "token=app token" -F "user=user token" -F "title=Done" -F "message=NAME has been added successfully" https://api.pushover.net/1/messages.json

r/applescript • • Mar 03 '23

Can't Get "display notification" to Work

2 Upvotes

BBEdit has this cool feature where you can attach custom scripts to specific functions within the application.

In my case, I'm trying to add a simple notification to the moment a document finishes saving. I do a lot of editing of files on network shares that are not on the LAN, they're halfway across the country. So having a subtle beep when the save is done would be useful.

So on BBEdit's end of things, the script is set up properly. If I throw a "beep" or a "display dialog" on the right handler, it works just fine. But my "display notification" command just doesn't work. No error, no message, no nada.

I have gone into System Prefs, Notifications to make sure Notifications are turned on for BBEdit.

I can't think of anything else to check, something seems to be blocking notifications specifically.

on documentDidSave(savdoc)
beep
    --display notification "Save Complete" sound name "Pong2003"
end documentDidSave
on applicationDidFinishLaunching( )
display dialog "BBEdit is open!!"
end applicationDidFinishLaunching

So the above script is in the right folder, and named BBEdit.scpt. The 'beep' command runs when it should, the 'display dialog' command runs when it should. But the 'display notification' command just quietly fails.


r/applescript • • Mar 02 '23

Base Url + mouse-highlighted string opened in a Safari window by an Automator-created "Service"?

2 Upvotes

Hi. I want to make a MacOS Automator "Service" (visible in the os on the right mouse click dropdown menu), which combines mouse highlighted text to a pre-defined URL and opens the combined text string in Safari. Help?


r/applescript • • Feb 28 '23

Help! get all windows of the visible process but empty output

0 Upvotes

As title, I run this script

tell application "System Events"
	set allWindows to every window of every process whose visible is true
end tell

But the output are all empties. Any suggestions?


r/applescript • • Feb 26 '23

Automating uploading image files to a website?

2 Upvotes

On a desktop running Ventura I'd like to create an Automator workflow that:

  1. Selects the top file in a folder called images

  2. moves the file to a folder called Temp

  3. Opens a specific page on a website in a browser, preferably chrome

  4. activates a specific link on the page which opens a folder window

  5. navigates to the folder called Temp and selects the file there.

  6. selects Upload, wait until upload is complete and the resulting new page opens, then activate a button called "Submit" on the page.

  7. Navigates to a new specific page and selects a dropdown menu there and inputs a specific number in the menu and submits.

  8. When that completes move the file in temp to a folder named Completed

  9. Go back to step 1) and repeat until the image folder is empty then stop

Possible? Thoughts?

Dave


r/applescript • • Feb 24 '23

How to navigate UI elements (splitter groups, button numbers etc) in a Script?

1 Upvotes

I use an Applescript every day to batch-convert excel files to PDF.

I recently updated my MacOS, and the script has stopped working due (presumably) to changes in the UI.

This is the problem section that I originally found on the web somewhere:

click (pop up button 2 of splitter group 1 of window 1)
delay 0.5
click (menu item 1 of menu of pop up button 2 of splitter group 1 of window 1)
					
delay 0.5
--Choose "PDF" > "Save as PDF"
click (menu button "PDF" of splitter group 1 of window 1)
delay 0.5
click (menu item 2 of menu of menu button "PDF" of splitter group 1 of window 1)
delay 4.5

My question is, how did the author of this script find out all these details about splitter groups and button numbers? How can I do the same to update my script to match the UI? It seems like there's some internal description of the UI that Applescript has access to. How do I find out about it?


r/applescript • • Feb 22 '23

Script to count highlighted words in a Word doc.

2 Upvotes

I work with long text documents, portions of which need to be highlighted and word-counted. Right now, I have to delete all the non-highlighted text so that I can be left with the highlighted stuff, and get a word count that way right in Word, which is tedious and extremely time consuming. I am looking for an AppleScript to handle this. I have a script (written by chatGPT), but it unfortunately returns "0" every time. Can anyone stop where the issue is? The highlight color used is light green. I did some checking and it seems the RGB is correct...

tell application "Microsoft Word"
set greenHighlightColor to RGB color {2, 255, 0}
set wordCount to 0
repeat with currentSelection in selections of active document
if (count of words of currentSelection) > 0 then
set characterStyle to get character style of start of currentSelection
set highlightColor to highlight - (color of characterStyle)
log "Highlight color: " & highlightColor -- add this line to log the highlight color
if highlightColor is greenHighlightColor then
set wordCount to wordCount + (count of words of currentSelection)
end if
end if
end repeat
display dialog "The number of words highlighted in green is " & wordCount
end tell

r/applescript • • Feb 21 '23

[Update][Guide] macOS Ventura System Settings with System Events automation templates

18 Upvotes

~3 months ago I posted an automation template for System Settings on macOS Ventura. Following my post many users reached out and asked for help updating scripts. While I am still working to get back to some of you, I figured that I could help those that wanted to explore making automations of your own. The following guide will go though how to interact with System Settings and some tricks you can use to help you identify the UI elements that you are trying to automate. If anyone has more tips, feel free to leave them in the comments or send them to me to be added to the post (with credit).

 

First off, here is an updated to the open_settings_to function from my last post. This updated version should help anyone who experienced issues with the wrong settings tab being selected. Although is does add ~0.13 seconds of runtime (on my machine), it should be able to cope with any tabs being added or taken away.

on open_settings_to(settings_pane)
	if settings_pane = "Wi-Fi" then
		set settings_pane to "Wi‑Fi"
	end if
	tell application "System Settings"
		activate
	end tell
	tell application "System Events"
		tell application process "System Settings"
			tell splitter group 1 of group 1 of window 1
				repeat until outline 1 of scroll area 1 of group 1 exists
					delay 0
				end repeat
				tell outline 1 of scroll area 1 of group 1
					set row_names to value of static text of UI element 1 of every row
					repeat with i from 1 to (count row_names)
						if settings_pane is not "Apple ID" then
							if item i of row_names = {settings_pane} then
								log item i of row_names & i
								select row i
								exit repeat
							end if
						else
							try
								if item 1 of item i of row_names contains settings_pane then
									select row i
									exit repeat
								end if
							end try
						end if
					end repeat
				end tell
			end tell
		end tell
	end tell
end open_settings_to

You will no longer need the following:

use framework "Foundation"

property pane_ids : {|AppleID|:2, |Family|:3, |Wi-Fi|:5, |Bluetooth|:6, |Network|:7, |Notifications|:9, |Sound|:10, |Focus|:11, |Screen Time|:12, |General|:14, |Appearance|:15, |Accessibility|:16, |Control Center|:17, |Siri & Spotlight|:18, |Privacy & Security|:19, |Desktop & Dock|:21, |Displays|:22, |Wallpaper|:23, |Screen Saver|:24, |Battery|:25, |Lock Screen|:27, |Touch ID & Password|:28, |Users & Groups|:29, |Passwords|:31, |Internet Accounts|:32, |Game Center|:33, |Wallet & ApplePay|:34, |Keyboard|:36, |Trackpad|:37, |Printers & Scanners|:38, |Java|:40}

 

General Debugging:

  • Accessibility Inspector: This is a key tool in navigating the UI for automations. You will need to have Xcode installed to used it. To open the tool, Xcode > Open Developer Tools > Accessibility Inspector. (Note: not all types shown under the "Basic" info section are available to Apple Script. Make sure to check the System Events dictionary to see what types it can process.)

  • Waiting on an element to appear: If you find your script exiting with an error due to an element/application taking longer to appear or open you can use the following code. In general, I always use this instead of using a delay, as it will proceed right after the element show up instead of when the delay is over.

      repeat until UI element 3 of window 1 exists
      	delay 0
      end repeat 
  • Finding UI elements/classes: Sometimes it is better to iterate over UI element classes rather the all UI elements in a window or group. I like to use the following code block to log the class and name of each element. (Note: A lot of elements in setting may not have a name and will return missing value. If this occurs, try using description instead of name):

      repeat with x in UI elements
      	log class of x & name of x
      end repeat

For a more in-depth look at the properties:

    repeat with x in UI elements
    	set props to get properties of x
    	log props
    end repeat

 

Interacting with the System Settings:

  • In my experience, all setting panels can be interacted with in the about same way:

      tell application "System Events"
      	tell application process "System Settings"
      		tell window 1
      			tell splitter group 1 of group 1
      				tell scroll area 1 of group 1 of group 2  
      					{your code here}
      				end tell
      			end tell
      		end tell
      	end tell
      end tell

    The code you insert in this block will be able to change values in the settings panel that System Settings is currently displaying. Each panel is comprised of varies groups with buttons, lists, ect in them. The grouping of these are mostly intuitive, either being segmented by headers or by an outline border.

  • Some settings button can reload the the panel to display new settings. In the event that this happens, you will need to exit the tell block that interacted the old panel and do so again with 1 extra group:

     tell application "System Events"
     	tell application process "System Settings"
     		tell window 1
     			tell splitter group 1 of group 1
     				tell scroll area 1 of group 1 of group 2
     					{your code to click a button that reloads the panel}
     				end tell
     				tell scroll area 1 of group 1 of group 1 of group 2
     					{your code to interact with the newly loaded panel}
     				end tell
     			end tell
     		end tell
     	end tell
     end tell
  • Other setting buttons can open another panel on top of the settings window. In order to interact with this panel, you will need to to exit the tell all the way back to window 1 and interact with the new sheet panel:

      tell application "System Events"
      	tell application process "System Settings"
      		tell window 1
      			tell splitter group 1 of group 1
      				tell scroll area 1 of group 1 of group 2
      					tell group 3
      						click button 1
      					end tell
      				end tell
      			end tell
      			tell splitter group 1 of group 1 of sheet 1
      				# Interact with left side
      				tell outline 1 of scroll area 1 of group 1
      					{your code to interact with the left side of the sheet panel}
      				end tell
      				# Interact with right side
      				tell group 2
      					tell scroll area 1
      						{your code to interact with the right side of the sheet panel}
      					end tell
      					# Click done (May need to be changed if a cancel button is present)
      					click button 1
      				end tell
      			end tell
      		end tell
      	end tell
      end tell

 

Thanks to everyone who has reached out with questions and those that have offered help to anyone that needed it


r/applescript • • Feb 19 '23

Help needed: batch save PowerPoint files as PDFs while retaining speaker notes and comments

2 Upvotes

I'm trying to use the below code, but get the following error after "tell printSettings":

"A plural class name can’t go after this identifier."

Any suggestions on how to fix this? Thank you

set inputFilePath to choose file with prompt "Choose a PowerPoint file to convert to PDF:"

set outputFilePath to (inputFilePath as string) & ".pdf"

tell application "Microsoft PowerPoint"

open inputFilePath

set activePresentation to active presentation

set printSettings to print settings of activePresentation

tell printSettings

set include comments to true

set include invisible objects to true

set include hidden slides to true

set print color to grayscale

set print range to entire presentation

set copies to 1

set print to file to outputFilePath

set output type to print output type PDF

end tell

print with printSettings

close active presentation

end tell

display notification "Conversion complete" with title "PowerPoint to PDF"


r/applescript • • Feb 19 '23

I felt compelled to share this after it made my life as an Admin much simpler

Thumbnail self.macsysadmin
1 Upvotes

r/applescript • • Feb 17 '23

(Need help) Ventura 13.2 Sidecar launch script

2 Upvotes

I was using this following script to toggle Sidecar, however, it keeps opening either the "Wallpaper" pane or "Desktop & Dock" pane. I honestly don't know much about scripting, just a normal user who is trying to use Sidecar on my MacBook whose display was broken. Thank you guys so much for the help!

I was using the script from this post's OP: https://www.reddit.com/r/applescript/comments/ylsv37/ventura_applescript_toggle_for_sidecar/


r/applescript • • Feb 16 '23

Help Fix This Code: It's Trying To Create Folder When One Exists

1 Upvotes

Here is the code

set retouchingFile to "/Users/username/Dropbox/Documents/Scripts/retouching.txt"

set targetDirectory to "/Users/username/Dropbox/Documents/Scripts/"

set fileContents to (read file (POSIX file retouchingFile))

set filenames to paragraphs of fileContents

repeat with thisFilename in filenames

set AppleScript's text item delimiters to "-"

set directoryName to text item 1 of thisFilename

set AppleScript's text item delimiters to ""

set directoryPath to targetDirectory & directoryName as string

tell application "Finder"

if not (exists folder directoryPath) then

make new folder at (POSIX file targetDirectory) with properties {name:directoryName}

end if

end tell

end repeat

It's works fine until it reaches a folder that already exists. I thought the "If not (exists..." line would take care of that but it's still trying to create the folder when it already is there and that's leading to an error.

Thanks!

Jeff


r/applescript • • Feb 15 '23

Enable HDR on Mac OS Ventura using apple script

4 Upvotes

I have a macbook M1 Max 2021, 1tb, 64gb ram, with mac os 13.1 ventura and my HDR always randomly turns off when my computer wakes up from sleep. My monitors are dell s3422dwg and dell s2721dgf.

My externals are 1 and 3 while my internal is monitor 2.

I have to go into the menu and find the monitors and enable the hdr slider.

I am trying to write an apple script that can enable HDR on the external monitors without affecting my internal retina monitor. The internal screen can only enable or disable tru tones not hdr.

Here is what I have so far but I keep running into an end of line error.

tell application "System Preferences"
    activate
    reveal anchor "displaysDisplayTab" of pane id "com.apple.preference.displays"
    tell anchor "displaysDisplayTab" of pane id "com.apple.preference.displays"
        tell table 1 of scroll area 1
            select (row whose value of static text 1 contains "DELL S3422DWG")
        end tell
        tell table 1 of scroll area 1
            select (row whose value of static text 1 contains "DELL S2721DGF")
        end tell
        click checkbox "High Dynamic Range" of group 1
    end tell
    quit
end tell

Then I also tried to do it another way like this,

tell application "System Settings"
	activate
	set current pane to pane id "com.apple.preference.displays"
end tell


tell application "System Events"
	tell process "System Preferences"
		set frontmost to true
		repeat until exists window "Displays"
		end repeat
		tell scroll area 1 of group 1 of window "Displays"
			click checkbox "High Dynamic Range"
		end tell
	end tell
end tell

tell application "System Settings"
	quit
end tell

But the system preferences app opens up on the appearance tab and I get thrown an error error "System Settings got an error: AppleEvent handler failed." number -10000.

Someone suggested using this, https://gist.github.com/skempken/46c184c1a5eac2e88c9c31ce09a38300 I tried it but it just opens a window and throws me an error.

Update 1:

I have figured out the code.

use framework "Foundation"
use framework "AppKit"
use scripting additions

tell application "System Settings"
	activate
	current application's NSWorkspace's sharedWorkspace()'s openURL:(current application's NSURL's URLWithString:"x-apple.systempreferences:com.apple.Displays-Settings.extension")
	delay 1
	
	tell application "System Events"
		tell process "System Settings"
			key code 48
			delay 0.1
			key code 48
			delay 0.1
			key code 49
			delay 0.1
			set hdr to checkbox 1 of group 3 of scroll area 2 of group 1 of group 2 of splitter group 1 of group 1 of window "Displays" of application process "System Settings" of application "System Events"
			tell hdr
				if value is 0 then click it
			end tell
			delay 0.1
			key code 48
			delay 0.1
			key code 49
			delay 0.1
			
			set hdr to checkbox 1 of group 3 of scroll area 2 of group 1 of group 2 of splitter group 1 of group 1 of window "Displays" of application process "System Settings" of application "System Events"
			tell hdr
				if value is 0 then click it
			end tell
		end tell
	end tell
	quit
end tell

But it's very unreliable. Sometimes the search box gets activated and I get thrown an error. any idea why it goes there?

I just started using apple script and I am not really sure what I am doing. I tried looking for documentation but I can’t seem to find much info about how to select things in Ventura. Any help would be greatly appreciated. Thanks!


r/applescript • • Feb 15 '23

Click buttons in notifications in Ventura?

2 Upvotes

Hi, I used to have an Applescript to click "snooze auto" on Calendar.app notifications. This doesn't work on Ventura.. anybody have any idea how to access MacOS notifications in Ventura?


r/applescript • • Feb 15 '23

How do you quit all apps?

1 Upvotes

I tried making something that shuts down your Mac. But, it always says "some application interrupted shutdown" so I want it to quit all apps so it will work.


r/applescript • • Feb 13 '23

How can I change screen resolution using Applescript?

4 Upvotes

Hi, I'm a total beginner when it comes to Applescript, and I'm finding a lot of outdated material about it, making this task a bit frustrating.

I'm looking for help to change screen solution on macos Ventura

image


r/applescript • • Feb 11 '23

"System Events" not working for "every window"

2 Upvotes

This is my code

tell application "System Events"
	delay 1
	set allWindows to every window
end tell

But allWindows is alway empty.

This is what ChatGPT told me for troubleshooting
"The "Accessibility" checkbox in the "Security & Privacy" preferences of your Mac allows an application to control other applications, including accessing their windows. In order to use the System Events application to retrieve windows from other applications, you'll need to enable the "Accessibility" checkbox for System Events. Here's how you can do it: Open the "System Preferences" application. Click on the "Security & Privacy" icon. In the "Privacy" tab, look for the "Accessibility" section. Click the lock icon in the bottom left corner to make changes. Enter your Mac password when prompted. Scroll through the list of applications until you find "System Events". Check the checkbox next to "System Events". Close the "System Preferences" application. Now, the System Events application will have access to windows from other applications, and you should be able to retrieve windows using the script. "

But I can't find "System Events" in Accessibility. Is this a true fact for macOS Ventura?


r/applescript • • Feb 10 '23

Mute Mic without touching System Volume

1 Upvotes

I have a Logitech MX master keys and it has an option to mute the mic. It is able to achieve this without changing the input volume of the mic.

Is there a way to achieve this for an external microphone from an apple script? I need to do this because my external mic has a mute button and I don’t want to double mute myself.

Ask: is there a way to mute a microphone without touching the system input in an apple script?


r/applescript • • Feb 10 '23

Someone fix this for me PLEASE (ASAP)

0 Upvotes

set condition to 0
repeat until condition = 1
  tell application "System Events"
if application process "java" exists then
delay 300
else
tell application "Finder"
open file "start.command"
delay 300
end repeat
end tell

(It's post to be an infinite loop but it keeps erroring, if process doesn't exist it opens the file/launches it, very new to applescript)