Error when sending POSIX file as attachment with iMessage

applescriptmessages

So I have this applescript that tries to grab all images from a folder and sends them to a friend through iMessage.

The folder is structure like so:

Desktop
  my-folder
    image-1
    image-2
    image-2

The problem is that when I read all files to a variable as a string and then try to set them to a POSIX file I get the error:

Messages got an error: Can’t get POSIX file
"/Users/user/Desktop/my-folder/image-name".

do shell script "rm -f ~/Desktop/my-folder/.DS_Store"

tell application "System Events"
    set imgs to POSIX path of disk items of folder "~/Desktop/my-folder"
end tell

tell application "Messages"
    set targetServiceId to id of 1st service whose service type = iMessage
    set theBuddy to buddy "redacted phone#" of service id targetServiceId

    repeat with img in imgs
        set imageAttachment to POSIX file img # errors
        send imageAttachment to theBuddy
    end repeat
end tell

How can I set imageAttachment correctly to a POSIX file so that I can send it with iMessage?

Best Answer

You are running into AppleScript sandboxing. The Messages application does not have access to open that file. The trick is to turn the paths to POSIX files outside of the tell blocks. This will let the entitlement engine pass the entitlement into the tell block so the application can open it.

This code works:

tell application "System Events"
    set paths to POSIX path of disk items of folder "~/Desktop/my-folder"
end tell

set imgs to {}
repeat with f in paths
    set imgs to imgs & (POSIX file f)
end repeat

tell application "Messages"
    set targetServiceId to id of 1st service whose service type = iMessage
    set theBuddy to buddy "redacted" of service id targetServiceId
    repeat with img in imgs
        send img to theBuddy
    end repeat
end tell