升级至macOS Monterey后批量短信AppleScript脚本运行报错求助
问题根源
macOS Monterey对Messages应用的UI交互逻辑和权限规则做了改动,原有脚本的旧交互逻辑不再适配:
- 新建对话窗口后,系统需要等待收件人输入框完全加载完成才会响应输入,原脚本没有加窗口加载等待,导致手机号输入时输入框未就绪,输入指令被漏掉
- 原有按回车跳转到消息输入框的逻辑在新版Messages中失效,输入手机号后按回车会直接确认收件人,不会自动聚焦到消息输入区
- Monterey新增了辅助功能权限校验,System Events的按键操作可能因为权限问题出现指令丢包
可行解决方案
前置权限配置
- 打开
系统设置→隐私与安全性→辅助功能,勾选你运行脚本的工具(脚本编辑器/自动化工具等) - 同路径下打开
完全磁盘访问权限,也勾选对应脚本运行工具 - 同时给Messages、Microsoft Excel也开启辅助功能权限
脚本修改方案
针对新版Messages的交互逻辑调整操作步骤:增加各步骤的等待间隔,将原回车跳转逻辑改为按Tab键主动切换到消息输入框,适配新版UI,修改后可用代码如下:
on run {input, parameters} set phoneCol to "B" set messageCol to "C" set startRow to 1 set counter to "D" set xlsFilePath to (path to desktop as text) & "texttest.xlsx" tell application "Microsoft Excel" to open file xlsFilePath tell application "Microsoft Excel" set endRow to value of cell (counter & startRow) as number end tell repeat with thisRow from startRow to endRow tell application "Microsoft Excel" set targetBuddyPhone to string value of cell (phoneCol & thisRow) as string set targetMessage to value of cell (messageCol & thisRow) as string end tell activate application "Messages" delay 1 -- 等待Messages完全激活 tell application "System Events" to tell process "Messages" key code 45 using command down -- 新建对话 delay 2 -- 等待新建窗口完全加载 keystroke targetBuddyPhone -- 输入手机号 delay 2 -- 等待系统识别手机号为有效收件人 key code 36 -- 确认收件人 delay 1 key code 48 -- 按Tab键切换到消息输入框 delay 1 keystroke targetMessage -- 输入短信内容 delay 1 key code 36 -- 发送 end tell delay 6 -- 避免发送频率过高被系统限制 end repeat return input end run
额外注意事项
- 如果仍出现输入错位,可以适当调大各个
delay后的数值,M1芯片运行速度快,部分系统UI响应跟不上脚本执行速度会导致操作错位 - 脚本运行过程中不要手动操作鼠标键盘,避免窗口焦点被抢走
- 首次运行提示权限错误时,退出脚本运行工具重新打开、重新授权即可
内容的提问来源于stack exchange,提问作者Steve1754a
相关产品推荐
相关产品推荐

