You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AppleScript读取macOS请勿打扰(DND)状态?解决返回值始终为1的问题

解决macOS Monterey中读取DND状态总是返回1的问题

我完全懂你遇到的困扰——在macOS Monterey里用defaults -currentHost read ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb这个命令,不管请勿打扰实际是开还是关,返回值永远是1,根本没法判断真实状态。这其实是因为Monterey系统里DND状态的存储机制变了,旧的plist键已经不再实时更新了。

为什么旧方法失效?

在macOS Monterey及后续版本中,com.apple.notificationcenterui.plist文件里的doNotDisturb字段不再反映当前的DND实时状态,它可能只是存储了某个初始设置或者历史配置,所以不管你实际开关DND,这个值都不会变化,自然一直返回1。

正确的解决方案

推荐用AppleScript直接调用系统事件来获取实时状态,这是最可靠的方式:

tell application "System Events"
    set dndIsEnabled to do not disturb enabled of notification center
end tell
return dndIsEnabled

这个脚本会直接返回true(DND开启)或false(DND关闭),完全准确。

如果需要在shell环境中调用,也可以用osascript包装这个逻辑:

osascript -e 'tell application "System Events" to return do not disturb enabled of notification center'

在AppleScript里调用的话,就写成:

set dndStatus to do shell script "osascript -e 'tell application \"System Events\" to return do not disturb enabled of notification center'"
-- 这里dndStatus会是字符串"true"或"false",可以转成布尔值
set dndIsEnabled to dndStatus as boolean
return dndIsEnabled

测试一下上面的方法,就能准确获取当前的DND状态了。

内容的提问来源于stack exchange,提问作者user4150758

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:17:43