如何使用 AppleScript 在 iMessage 中开始新对话?

Posted

技术标签:

【中文标题】如何使用 AppleScript 在 iMessage 中开始新对话?【英文标题】:How to start new conversation in iMessage using AppleScript? 【发布时间】:2016-12-25 22:53:07 【问题描述】:

所以我正在创建一个基本上可以自动发送信息的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

这在大多数情况下都有效,但在开始新对话时不起作用。当您将脚本运行到您在消息中没有与之对话的号码时,您会收到一条弹出警告,提示“您的消息没有任何收件人”。但是,这会创建与该人的对话,并且当您再次运行相同的脚本时它会起作用。

我想如果它第二次起作用,一定有一种方法可以以某种方式创建一个新的对话,但是我以前从未真正使用过 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

虽然这可行,但我想有一个比这个更好/更优雅的解决方案。

【问题讨论】:

这不起作用...开始新对话 【参考方案1】:

我的解决方案是告诉 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

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

【讨论】:

已确认这在莫哈韦沙漠有效。要求我将终端/iTerm 添加到系统偏好设置 > 安全和隐私 > 可访问性 tab键码是什么?似乎输入不再进入文本区域 这个脚本在 Catalina (10.15.4) 上为我工作。【参考方案2】:

有很多方法可以做到这一点。

第一个例子

on run targetBuddyPhone, targetMessage
    tell application "Messages"
        set targetService to 1st service whose service type = iMessage
        set targetBuddy to buddy targetBuddyPhone of targetService
        send targetMessage to targetBuddy
    end tell
end run

第二个例子

tell application "Messages"
    set targetBuddy to "+18001234567"
    set targetService to id of 1st service whose service type = iMessage
    repeat
        set textMessage to "Hello pal!"
        set theBuddy to buddy targetBuddy of service id targetService
        send textMessage to theBuddy
        delay (random number from 10 to 30)
    end repeat
end tell

【讨论】:

注意:苹果脚本不允许在 Message.app 中启动新线程。你只能写已经打开的对话。 嘿伙计们,我很困惑..为什么这被标记为答案?..它不会开始新的对话。

以上是关于如何使用 AppleScript 在 iMessage 中开始新对话?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Applescript 中调用 Automator 变量?

如何在 AppleScript 中操作“数据”对象

如何在Mail.app中运行的applescript中使用钥匙串中的密码?

如何使用 AppleScript 保存为 excel 文件

如何使用 AppleScript 更改当前工作目录

如何使用 AppleScript 登录远程 Mac?