Search code examples
macosapplescriptimessage

How to start new conversation in iMessage using AppleScript?


So I'm working on creating an applescript which essentially automates sending an imessage. What I have working now is:

on run {msg, phoneNum}
    tell application "Messages"
        set serviceID to id of 1st service whose service type = iMessage
        send msg to buddy phoneNum of service id serviceID
    end tell
end run

This works for the most part except it doesn't work when starting a new conversation. When you run the script to a number which you don't have a conversation with in messages, you get a popup warning saying "Your message does not have any recipients". However, this creates a conversation with that person, and when you run the same script again it works.

I figured if it works the second time, there must be a way to create a new conversation somehow, however I have never really used applescript or really any script languages before so I'm not sure how to go about that.

Edit: Immediately after posting I thought of a rough workaround. If right before you send the message you send an empty string, you can create a new conversation, and it works with a already existing conversation.

on run {msg, phoneNum}
    tell application "Messages"
        set serviceID to id of 1st service whose service type = iMessage
        send "" to buddy phoneNum of service id serviceID
        send msg to buddy phoneNum of service id serviceID
    end tell
end run

While this works, I'd imagine there is a better/more elegant solution than this one.


Solution

  • My solution is to tell Applescript to press "Command + N", which is the shortkey for "Start a new conversation"

    activate application "Messages"
       tell application "System Events" to tell process "Messages"
       key code 45 using command down           -- press Command + N to start a new window
       keystroke "<replace with phone number>"  -- input the phone number
       key code 36                              -- press Enter to focus on the message area 
       keystroke "<replace with message>"       -- type some message
       key code 36                              -- press Enter to send
    end tell
    

    This script will start a new conversation and send the message to the phone number through iMessage