Bear script API

Hello,

I just wrote a script API for Bear. It’s much nicer to use than writing URLs by hand (when you’re a developer, at least).

Usage examples (after including the “BearAPI” action):

  • Prepending to a note:

    Bear.prependTo("Project Ideas", "list");
    // "plain", "list" or "section"
    // Bear.appendTo also exists
    
  • Creating a note:

    Bear.create(draft.content);
    
  • Fetching a note and manipulating it:

    var n = BearNote.fetch("Project Ideas");
    console.log(n.identifier, n.title, n.content, n.isTrashed, n.creationDate, n.modificationDate);
    n.content = "Hello";
    n.append("World");
    n.trash();
    

Feedback welcome! I hope it’s useful to someone :slight_smile:

7 Likes

This is awesome! Thanks for sharing.

1 Like

Indeed, this is useful! Thank you.

1 Like

Thanks for the API. Do you still use it?

My current problem is to check if a note exists. If not create it with a certain template, otherwise append to it. Without any logic it isn’t possible but I will have a look and maybe try to do it via JavaScript within Drafts.

I still use it, but didn’t write many new actions since, so it didn’t evolve much.

I just made an updated version to support your use case: BearAPI 2 preview 1 action. The main difference is that it doesn’t fail the whole action if the note doesn’t exist but returns false instead.

Here it is in action:

var title = "My templated note";
var template = "My super template\n---\n";
var n = BearNote.fetch(title);
if (n === false) {
  n = BearNote.create(template, { "title": title });
  if (n === false) context.fail();
}
n.append(draft.content + "\n---\n");

Hope it works for you :slight_smile:

1 Like

Hi @olivier,

thanks. That was quick and I could make it work and built upon that. :slight_smile:

I have to look more into JavaScript but it can be really useful to add more logic to iOS/MacOS automations. Here is my first draft of the script.

let d = new Date()

// draft.setTemplateTag('daily-long-title', dailyLongTitle);

let title = strftime(d, `%Y-%m-%d Daily Note for %A`)
let dailyLongTitle = strftime(d, `%A, %d.%m.%Y (week %V & day: %j)`)
let tagYear = strftime(d, `%Y`)
let tagMonth = strftime(d, `%Y %m`)

var template = `
#dailies# #dailies/${tagYear}# #dailies/${tagYear}/${tagMonth}# 

---
*${dailyLongTitle}*
---
### Daily Tasks
- [ ] learn vocabulary with Anki
- [ ] check calendar
- [ ] check todos
---`;

var n = BearNote.fetch(title);
if (n === false) {
  n = BearNote.create(template, { "title": title });
  if (n === false) context.fail();
}
n.append("\n" + draft.content);