Skip to content

Instantly share code, notes, and snippets.

@apexskier
Last active September 23, 2019 18:53
Show Gist options
  • Save apexskier/e831800530c22f47dd3b6b95aaae53d3 to your computer and use it in GitHub Desktop.
Save apexskier/e831800530c22f47dd3b6b95aaae53d3 to your computer and use it in GitHub Desktop.
Script to clean and add international +1 prefix to my contacts
# This script is used when I moved to poland and my phone started not recongizing saved contacts because the incoming number has +1 but the saved number doesn't
# it finds all numbers that aren't prefixed with a "+" country code and look like standard us phone numbers (10 digits, or 11 digits starting with 1) and reformats them to `+1 (DDD) DDD-DDDD`
#
# note: After this syncs to your phone, you'll probably need to restart in order for messages to show the contact name properly
set modified_count to 0
tell application "Contacts"
set all_people to every person
repeat with each_person in all_people
repeat with each_phone in (get phones of each_person)
set phone_number to value of each_phone
if phone_number does not start with "+" then
#log (first name of each_person) & " " & (last name of each_person)
set cleaned_number to my clean_number(phone_number)
if length of cleaned_number is 10 then
set formatted_number to my format_number(cleaned_number)
else if length of cleaned_number is 11 and item 1 of cleaned_number is "1" then
set formatted_number to my format_number(text 2 thru 11 of cleaned_number)
else
set formatted_number to null
end if
if formatted_number is not null then
set country_prefix_number to "+1 " & formatted_number
log phone_number & " -> " & country_prefix_number
tell each_phone
set value to country_prefix_number
set modified_count to modified_count + 1
end tell
end if
end if
end repeat
end repeat
save
end tell
if modified_count is 1 then
"modified " & (modified_count) & " contact"
else
"modified " & (modified_count) & " contacts"
end if
on clean_number(phone_number)
set cleaned_number to {}
repeat with c in the characters of phone_number
set c to c as text
try
set c to c as number
set the end of cleaned_number to c
end try
end repeat
return join_list_by(cleaned_number, "")
end clean_number
on format_number(cleaned_phone_number)
set cleaned_number to the characters of cleaned_phone_number
return ¬
"(" & text 1 thru 3 of cleaned_number & ¬
") " & text 4 thru 6 of cleaned_number ¬
& ¬
"-" & text 7 thru 10 of cleaned_number
end format_number
on join_list_by(the_list, delimiter)
set backup_delimiter to AppleScript's text item delimiters
set AppleScript's text item delimiters to delimiter
set return_string to the_list as string
set AppleScript's text item delimiters to backup_delimiter
return return_string
end join_list_by
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment