MacOS – Running AppleScript without activating the window

applescriptmacosmessages

I have a python script to read from Messages database and forward some specific new messages to specific contacts. It works but the AppleScript below to send message is making Messages.app appear.

I want it to send the message in the background without activating or un-hiding the window. Is this possible?

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
        set visible to false --> this throws an error on terminal
    end tell
end run

Best Answer

For Me adding:

tell application "System Events" to tell process "Messages" to set visible to false

AFTER end tell, worked like a charm