I am attempting to write a simple script to create a group within Contacts that contains all the “Recently Added” contacts.
When I run the script, everything looks as though it is working fine. However, within Contacts, no group called “Recently Added” appears. I am using Yosemite.
Suggestions appreciated.
property pRecentTime : 30
property pRecentGroupName : "Recently Added"
tell application "Contacts"
try
set theGroup to group pRecentGroupName
delete theGroup
end try
set allGroups to the name of every group as list
make new group at the end of groups with properties {name:pRecentGroupName}
set selected of group pRecentGroupName to true
set allGroups to the name of every group as list
repeat with thePerson in people
if thePerson's creation date is greater than (current date) - (pRecentTime * days) then add thePerson to group pRecentGroupName
end repeat
end tell
end
you have to save the address book.
This might be bit faster, the variable allGroups isn’t used at all
property pRecentTime : 30
property pRecentGroupName : "Recently Added"
tell application "Contacts"
if exists group pRecentGroupName then
delete group pRecentGroupName
end if
make new group at the end of groups with properties {name:pRecentGroupName}
set selected of group pRecentGroupName to true
set recentAdded to people whose creation date comes after (current date) - (pRecentTime * days)
repeat with aPerson in recentAdded
add aPerson to group pRecentGroupName
end repeat
save
end tell
Stephan: Thank you so much! That was indeed the problem. Should have posted 5 hours earlier. So annoying that this type of thing is relatively undocumented.
None of the 2 scripts above worked for me, and here’s why:
1) may not exist recent contacts for less than 30 days,
2) not all recent contacts can be added to group. Some of them have not phone or email. As say, you forget to fill this fields or you want fill those later.
Both of these problems are solved using the try block:
property pRecentTime : 30
property pRecentGroupName : "Recently Added"
tell application "Contacts"
if exists group pRecentGroupName then delete group pRecentGroupName
make new group at the end of groups with properties {name:pRecentGroupName}
set selected of group pRecentGroupName to true
try
set recentAdded to people whose creation date comes after (current date) - (pRecentTime * days)
on error
display dialog "NO RECENT ADDED CONTACTS FOUNDED.
FOLDER \"RECENT ADDED\" WILL NOT BE CREATED." giving up after 5
return
end try
set countAdded_toGroup to 0
repeat with aPerson in recentAdded
try
add aPerson to group pRecentGroupName
set countAdded_toGroup to countAdded_toGroup + 1
end try
end repeat
if countAdded_toGroup ≠ 0 then
display dialog "FOLDER \"RECENT ADDED\" SUCCESSFULLY CREATED.
ADDED " & (countAdded_toGroup as string) & " RECENT CONTACTS" giving up after 5
else
display dialog "NO RECENT CONTACTS CAN BE ADDED FOUNDED.
FOLDER \"RECENT ADDED\" WILL NOT BE CREATED." giving up after 5
end if
save
end tell