Skip to content

Instantly share code, notes, and snippets.

@evansalter
Forked from aktau/imessage
Last active January 6, 2016 22:20
Show Gist options
  • Save evansalter/5ee734430a6717038970 to your computer and use it in GitHub Desktop.
Save evansalter/5ee734430a6717038970 to your computer and use it in GitHub Desktop.
Send iMessage from the command line using phone number or contact name
#!/bin/sh
if [ "$#" -eq 1 ]; then stdinmsg=$(cat); fi
exec <"$0" || exit; read v; read v; read v; exec /usr/bin/osascript - "$@" "$stdinmsg"; exit
-- another way of waiting until an app is running
on waitUntilRunning(appname, delaytime)
repeat until my appIsRunning(appname)
tell application "Messages" to close window 1
delay delaytime
end repeat
-- the fact that Messages.app is running
-- does not mean it is ready to send,
-- unfortunately, add another small delay
delay delaytime
end waitUntilRunning
on appIsRunning(appName)
application appname is running
end appIsRunning
-- use system events (unused)
on SysevAppIsRunning(appName)
tell application "System Events" to (name of processes) contains appName
end appIsRunning
-- use finder (unusged)
on finderAppIsRunning(appName)
tell application "Finder" to (name of every process) contains appName
end appIsRunning
-- taken from:
-- http://stackoverflow.com/questions/11812184/how-to-send-an-imessage-text-with-applescript-only-in-provided-service
-- thanks to users @Senseful and @DigiLord
on run {targetBuddy, targetMessage}
tell application "Messages"
-- if Messages.app was not running, launch it
set wasRunning to true
if it is not running then
set wasRunning to false
launch
close window 1
my waitUntilRunning("Messages", 1)
close window 1
end if
try
set firstDigit to text 1 of targetBuddy as number
set secondDigit to text 2 of targetBuddy as number
set targetBuddyPhone to targetBuddy
on error
tell application "Contacts"
set p to the first person whose name is targetBuddy
set targetBuddyPhone to value of phone 1 of p
end tell
end try
-- send the message
set targetService to 1st service whose service type = iMessage
set targetBuddySend to buddy targetBuddyPhone of targetService
send targetMessage to targetBuddySend
-- if the app was not running, close the window
if not wasRunning
close window 1
end if
end tell
end run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment