Add selected contact to a specific group in Apple Contacts via AppleScript

Hi! Below are script which should in theory add a selected person in Apple Contacts to a specific group. I understand that syntax of line 2 is wrong, but couldn’t find any solutions online.

Could someone with better AppleScript knowledge to point out what I need to change to make this script to work?

tell application "Contacts"
	set thePerson to selection
	add thePerson to group "my group"
	save
end tell

It’s been a long time since I used AppleScript to manage contacts, but is it possible that you’ll get a list/array of people, and a list/array of one person if you only highlight one?

Then you’d need to get the people and do a for each loop.

If you haven’t worked this out already. @tf2 is right. You can add a person to a group but the selection is a list of persons, even if you have only one contact selected. Try this:

tell application "Contacts"
	set thePeople to selection
	set thePerson to item 1 of thePeople
	add thePerson to group "my group"
	save
end tell

I’m assuming here that you intend to use this when only one contact is selected. If you want to select several people and add them to the group all at once, use a repeat loop as @tf2 suggested.

1 Like

Indeed. What’s annoying is that the following command should work:

tell application "Contacts"
    add selection to group "my group"
end tell

But because selection is a list, not a reference, it doesn’t. And while add could accept either a single reference or a list of references, it doesn’t. Typical Cocoa Scripting-based app: dumb as a stump and thoughtlessly unhelpful.

Contrast Finder, which does exactly what you want when you tell it to do it:

tell application "Finder"
    duplicate selection to folder "my files"
end tell

While pre-OS X apps had their own issues, at least their developers designed them from a UI/UX perspective: “What does the user want to do?” Cocoa apps are just “Hur-dur, I haz API”, dumping all the drudge work on the user.

(Mind you, even CS will be a great improvement over its successor. A huge shame, as this tech could be fantastic with just a tiny bit of investment.)

Thank you @tf2 and @drdrang.

Yeah, I first opened one of Finder AppleScripts I use to check the syntax. As you write, it does not work in Contacts.