24.6 C
Colombia
domingo, julio 6, 2025

macos: ejecuta AppleScript cuando se recibe una notificación


¿En qué versión de macOS estás? Descubrí algo para poder descartar automáticamente esos molestos mensajes persistentes. updates out there notificaciones (que ocurren independientemente de la configuración de actualización automática), pero aparentemente las funciones de Applescript para las notificaciones cambian enormemente entre las versiones del sistema operativo. Mi solución no es realmente “actuar al recibir una notificación”, sino que verifica constantemente las notificaciones visibles en busca de ciertas cadenas. Eso es prácticamente lo mejor que puedes hacer solo con Applescript. Debería funcionar bien al menos en Monterrey y posiblemente algo más nuevo.

La parte superior es alguna configuración, luego, en la parte inferior, agregué un comentario para indicar dónde agregaría su manejo. Probablemente deberías leer el guión completo de todos modos. =]Como beneficio adicional, también he incluido la función de descarte automático, que debería ser independiente del idioma. Además, no estoy seguro de si todavía existen subtítulos, porque ninguno apareció en mis casos de prueba. Pero agregué un comentario donde puedes intentar recuperarlos.

international notificationStrings
set notificationStrings to {"Bricks + Agent"}

-- These *should* be the English names, since they are going to be translated to no matter's at present on the notification
international closeStrings
set closeStrings to {"Shut", "Clear All"}

international accessCheckTitle
set accessCheckTitle to "Notifications Monitor"

-- An error message will likely be instantly appended to this
international accessCheckSubtitle
set accessCheckSubtitle to "This app wants each Accessibility and Automation entry:nn"

international buttonOk
set buttonOk to "Shut"
international buttonSysPrefs
set buttonSysPrefs to "Open System Preferences"

-- Quantity of ticks earlier than we reload the strings (at return 3 that is about 300 seconds, or 5 min)
international reloadStringsInterval
set reloadStringsInterval to 100

-- END OF CONFIG

international reloadStringsTicks
set reloadStringsTicks to -1
international closeStringsl10n
set closeStringsl10n to {}

on idle
    checkNotifications()
    return 3 -- Delay for subsequent run (seconds)
finish idle

on stop
    proceed stop -- Permits the script to stop
finish stop

on checkNotifications()
    attempt
        -- All of those throw errors after they've explicitly been denied entry, in any other case they will immediate (not less than on the very first time)
        inform utility id "com.apple.SystemEvents" to set ncenterProcess to the primary course of whose bundle identifier = "com.apple.notificationcenterui" -- For Automation entry on System Occasions
        set ncenter to path to utility id "com.apple.notificationcenterui" -- For Automation entry on Notification Centre
        inform ncenterProcess to exists window 1 -- For Accessibility entry
    on error errmsg
        -- A attempt is important to deal with the cancel button with out "crashing" (thanks Apple)
        set openSysPrefs to false
        attempt
            set res to (show dialog (accessCheckSubtitle & errmsg) with title accessCheckTitle buttons {buttonOk, buttonSysPrefs} default button buttonSysPrefs cancel button buttonOk with icon cease)
            if button returned of res is the same as buttonSysPrefs then
                set openSysPrefs to true
            finish if
        finish attempt

        if openSysPrefs then
            open location "x-apple.systempreferences:com.apple.desire.safety?Privacy_Accessibility"
        finish if

        -- All the time have to stop right here in order that we are able to decide up on any newly granted permissions subsequent time we run
        delay 30
        stop
    finish attempt

    set reloadStringsTicks to reloadStringsTicks + 1
    if reloadStringsTicks is the same as 0 or reloadStringsTicks is bigger than or equal to reloadStringsInterval then
        set l10nTmp to {}
        attempt
            repeat with closeString in closeStrings
                set the top of l10nTmp to localized string closeString in bundle ncenter
            finish repeat
        on error
            -- I feel this will occur if this script runs too early after logging in, so let's make sure that we'll instantly attempt once more on the following run
            set reloadStringsTicks to -1
            return
        finish attempt
        set closeStringsl10n to l10nTmp
        set reloadStringsTicks to 0
    finish if

    inform utility id "com.apple.SystemEvents"
        inform ncenterProcess
            -- The principle window might not at all times (instantly/absolutely) exist apparently
            attempt
                set allNotifications to teams of UI component 1 of scroll space 1 of window 1
            on error
                return
            finish attempt

            repeat with checkNotification in allNotifications
                -- It might have already (been) closed within the meantime
                attempt
                    set nTitle to the worth of static textual content 1 of checkNotification
                    --set nContents to the worth of static textual content 2 of checkNotification
                    -- There *might* be a static textual content 3 for subtitles, however it did not exist in my take a look at instances

                    if nTitle is in notificationStrings then
                        -- That is the place you'll add your dialog and different dealing with, for instance (to dismiss the notification afterwards):
                        repeat with checkAction in actions of checkNotification
                            if description of checkAction is in closeStringsl10n then
                                attempt
                                    carry out checkAction
                                finish attempt
                                delay 2 -- Give it a while to shut
                            finish if
                        finish repeat
                    finish if
                finish attempt
            finish repeat
        finish inform
    finish inform
finish checkNotifications

Guárdalo como Softwaremientras se desactiva Present startup display screen y habilitando Keep open after run handler. Agregarlo a sus elementos de inicio debería funcionar bien.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles