如何使用AppleScript在iMessage中启动新对话?

HaH*_*gry 14 macos applescript imessage

所以我正在努力创建一个基本上自动发送imessage的applescript.我现在的工作是:

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
Run Code Online (Sandbox Code Playgroud)

除了在开始新会话时不起作用外,这大部分都有效.当您将脚本运行到与消息中没有对话的号码时,会收到一条弹出警告,提示"您的消息没有任何收件人".但是,这会创建与该人的对话,并且当您再次运行相同的脚本时,它会起作用.

我想如果它第二次运行,必须有办法以某种方式创建一个新的对话,但我从来没有真正使用过AppleScript或者之前的任何脚本语言,所以我不知道该怎么做.

编辑:发布后我立刻想到了一个粗略的解决方法.如果在您发送消息之前发送空字符串,则可以创建新会话,并且它可以与现有会话一起使用.

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
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我认为有一种比这更好/更优雅的解决方案.

小智 9

我的解决方案是告诉 Applescript 按“Command + N”,这是“开始新对话”的快捷键

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
Run Code Online (Sandbox Code Playgroud)

此脚本将开始新的对话并通过 iMessage 将消息发送到电话号码

  • 已证实这在莫哈韦工作。要求我将 Terminal/iTerm 添加到系统偏好设置 &gt; 安全和隐私 &gt; 可访问性 (2认同)
  • 该脚本适用于我的 Catalina (10.15.4)。 (2认同)