AppleScript not working

I am attempting to grab the sole tag on an item and append the tag content to the name of the item. Beloved AI provides me with the following AppleScript which I run from a Keyboard Maestro macro, but nothing happens. I am trying to learn AppleScript but am finding it very difficult to get any to work. Any comments on the script most welcome (or alternative means to achieve my ends).

tell application id “DNtp”
try
set theRecord to content record 1
if theRecord is missing value then error “No content record”
set theTags to tags of theRecord
log message ("Tags: " & theTags as string)
if (count of theTags) = 1 then
set counterparty to item 1 of theTags
set oldName to name of theRecord
set newName to oldName & " - " & counterparty
set name of theRecord to newName
log message ("Renamed to: " & newName)
else
log message “Not exactly one tag”
end if
on error errMsg
log message ("Error: " & errMsg)
end try
end tell

Please use proper formatting for longer pieces of code. Instead of `inline code`, use a code block:

```
Code goes here,
	preserving whitespace/indentation
	which is especially important for AppleScript.

```

It is easier if you write and test scripts in Script Editor. If you open the log and look in the replies tab, it gives you an idea of what is going on. At least there is some feedback.

In this case, there is already a problem in the first statement – which doesn’t compile because of a syntax error:

Note that the problematic part (“1”) is highlighted. (It might be a bit hard to see behind the alert)

content record is a property (of either the application, window or tab). The “1” is a short form of specifying the first object/element of a certain class, for example selected record(s):

I guess AI doesn’t know the difference.

1 Like

The best way to learn programming is to grab a (digital) reliable source and learn. AI is notoriously bad at AppleScript. And this forum is full of scripting examples.

4 Likes

Methinks thy lover hast plunged a blade into your breast… :wink:


  1. Why a script?
  2. Why are you appending a tag to the name?
  3. Is your data conforming enough you won’t have two tags or 20 ?
  4. If not, how do you know item 1 is the desired tag?

IF there was only one tag on the document… a batch process would be sufficient…


And a simple, properly written script (spaced and commented for easy reading and learning)

tell application id "DNtp"
	if (selected records) is {} then return -- No selection, stop.
	
	repeat with theRecord in (selected records) -- Loop through selected records
	
		set recordTags to (tags of theRecord) -- Get the tags, which may or may not exist
		
		if recordTags's length is 1 then -- Tags are a list. If there's one tag, there's a list of 1. If there's only one…
			set name of theRecord to (theRecord's name without extension & "-" & recordTags as string) -- Append the tags (a list) to the name as a string.
			
		else -- If the tags don't equal 1, it's zero (no tags) or 2 or more…
			log message "Zero or more than one tag on this item." record theRecord -- Log a warning
		end if
	end repeat
end tell

PS: You don’t need Keyboard Maestro for this.

4 Likes

It’s definitely not that bad when using DEVONthink’s script assistant, see e.g. via Data > New > Script…. The assistant provides the complete, current script suite to the AI, checks that the script can be compiled at least (and performs automatic retries otherwise) and fixes the most common issues. The prompt is of course crucial too.

But unfortunately most users seem to ask the preferred chat app or DEVONthink’s generic chat assistant and the training data of (almost) all large language models contains little to nothing related to DEVONthink 4 scripting.

1 Like

E.g. here I just used the the original request for the prompt and Gemini 3.1 Pro:


A little bit more verbose than necessary but fully functional.

Please use proper formatting for longer pieces of code. Instead of `inline code`, use a code block

Thank you for this tip. I will use this method in future. (I also cannot get quoting to work!).

It is easier if you write and test scripts in Script Editor.

I will use Script Editor now.

The AI must be confused.

And this forum is full of scripting examples

I have used scripts from this forum before with great success.

Any other tips on sources for learning code greatly received :folded_hands:

Use three back ticks on top and bottom of code, not quotes. (bottom left on my Apple keyboard), e.g ```

More details at Posting code or preformatted text - Using Discourse - Discourse Meta

What mysterious potion hath mine own lover imbib’d from yon urn?

  1. Doesn’t have to be a script. I subsequently tried a smart rule to append tags to name, and that worked.
  2. Because I want the name to include key metadata (for a rainy day…).
  3. I am consciously sticking to one tag for the items to be subject to this action. (I did consider prefixing the relevant tag and working out a way to add to the selection the (one) tag with the prefix - using AppleScript or another solution). But can manage with one tag per item.
  4. N/a.

I like the idea of a batch process as well - haven’t yet explored so will read up on those as an alternative to smart rules.

Thank you for the non-mind-altered suggested script. I will investigate that further - in Script Editor!

The reason I am using KM is that I want to perform many actions end to end on one PDF starting in my mail program. So I have been incorporating actions in KM referencing DT menus including smart rules and AppleScripts (from here (–work) and from AI (stiff drink recommended)). Using DT menus via KM works well except in one case I am puzzled: a subject for a separate post.

Many thanks all.

1 Like

Wow. I will investigate!

I’ll try it out. Thank you.

I don’t know about the weather. But what about “DRY”? Say you append the first tag to the name. Some time later, you change the first tag – will you think of updating the name? Will you write smart rule to do that? Or what happens if you remove this tag?

Duplicating information in different places complicates things, because you then have to keep the information in sync. It (duplication, not sync) is something that is frowned upon in traditional database design. And for good reasons.

2 Likes

Interesting and I should consider.

I have also wanted the key metadata in the filename when I have to attach the file to the financial system. But shouldn’t I just link from that system back to the file in DT? If only I could. Vendors of such systems seem to go out of their way to ensure you cannot link to or involve any external system - duplication is forced.

I’m interested to know whether you think accepting the filename given to the file by the source (which may be unintelligible) as the DT item name is ok with appropriate metadata added to the item? I guess it depends on use case. Perhaps I should temper my pedantry!

1 Like

Another reason I regularly amend the item name:

I need to get a fair number of metadata fields populated for a large number of documents regularly. I find entering metadata in the RHS side bar involves quite a few keystrokes more than entering it in a KM user input action (eg. dates: typing 2026 over and over (over DT’s 31/12/2000 default, and I don’t use DT’s date fields anyway, I use single-line text fields for dates as DD/MM/YYYY is not my macOS default date format which DT does use in lists but not in metadata fields (?)) when a useful default can be set in KM); (eg. select from a list of options in a KM input field not limited like DT’s metadata set which only remembers a handful of options)–doesn’t seem like much but there are other shortcuts and I benefit from error reduction).

KM then renames the file with the metadata, each component delimited. A smart rule accessed from within KM, incorporates an AppleScript which takes the delimited components and populates each metadata field. The smart rule then uses various metadata fields and the sole tag to rename the item in a cleaner (non-delimited) way.

Yep, a very roundabout way to get what I want and I’m sure there are easier ways to cut this–pleased to receive any advice and recommended alternatives–but it is working (now).

I have difficulties understanding what exactly an item name looks before and after modification in your setup. And yes, I do modify item names by at least adding a sortable date (which can be done with a smart rule, BTW – there’s a placeholder for that).

Before: the names of items will be whatever a multitude of different document creators choose to name their PDFs; in some cases, a series of letters and digits with meaning only to the creator.

After: <sortable date (ISO date), being the document date (ie. the date recorded as the date of the document on the document, which may be different to the date it was sent to me, the date I received it, or the date on which the creator created the document)> <source of document / counterparty> <currency (if a transactional document with a monetary amount)> <monetary amount, where applicable>.

I would like to be able to use a smart rule to add a sortable document date (without needing to add it manually or use an external service to extract it and add it to the filename), but as far as I can tell I cannot add the document date with a smart rule; only dates relative to the current time, such as current date, and some system generated dates (created date, etc). No doubt there is a way to extract the document date using AI, but none I can see using DT’s current implementation of AI. I would love to be steered in the right direction if this is doable.

Subsequent to what I wrote in prior posts I am now using a third party to analyse the document and create the necessary metadata within the file name, then using an AppleScript to populate the metadata fields in DT. A much simpler process than my previous moves. If DT with AI had the capability to extract the metadata from the document I could forgo the external service.

Here’s what I see in my version of DT4:

The third variant of the date format is a sortable (ISO) one.
Check out the section on “placeholders” in the online documentation.

1 Like

I’ve tried using the following:

Using the above smart rule applied to many PDF+Text docs with dates in different formats, often with only one date on the page, and always within the first four pages; always return a revised name like this:

Name -

The date does not seem to be detected.

Will DT only accept certain date formats for detection?

I tried similar with Document Amount. This is successful in some cases, picking up currency identifier where it is ‘$’ and amount, but in other cases just the amount. Have not tested other currencies (not using ‘$’) I commonly use as yet.

It looks like you’re using a date placeholder for a custom metadata field named “Docdate”. That has nothing to do with dates detected in the file by DEVONthink. I marked them with a green box here:

The red box is a custom metadata field, simply called “Date”. (I think it’s one of the defaults you can enable).

1 Like