Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

macos - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...