💬

Writing a Night plugin

Setup (editor IntelliSense)

npm i -D @nascens/plugin-sdk   # types only — nothing ships in your plugin

jsconfig.json next to your plugin:

{
  "compilerOptions": { "checkJs": true, "module": "ESNext", "moduleResolution": "bundler", "target": "ES2022" },
  "files": ["node_modules/@nascens/plugin-sdk/globals.d.ts", "index.js"]
}

This types the global loader, so loader.SDK. autocompletes and the JSDoc of every method shows on hover.

Anatomy

A plugin is a folder with manifest.json, index.js, and optionally menu.html (settings form, see Settings menu), locales/, and view.css (styles for its views). index.js default-exports a class extending Process:

const { Process, Stats, Manyvids } = loader.SDK;

export default class MyPlugin extends Process {
    constructor(id, account, access_token_id) {
        super(id, account, access_token_id);
        this.output_log = new Stats(this.id, "output");
        this.mv = Manyvids.bind(this);          // every call runs as this process's account
    }

    async exec() {                              // the main loop
        const me = await this.mv.Account.get_me();
        this.output_log.add({ event: "hello", main_data: me.user.userId });
    }
}

See examples/example_plugin.js for a complete one.

Manyvids stays available for existing plugins. Code that should work on whichever platform the manifest's module names can look the platform up instead:

PlatformsEvery platform's SDK, keyed by module id (Platforms.manyvids === Manyvids)
get_platform(id)The platform for a module id or domain, or null
get_chat(id)The platform's Chat namespace, or null when it has no direct messages. Chat is the same on every platform: get_thread, send, is_following, set_following, get_own_bio, is_member_type
identity_of(id, account.extra)The account's platform-independent identity

manifest.json:

{ "title": "My plugin", "name": "my_plugin", "author": "you",
  "short_description": "One line for plugin cards",
  "long_description": "What it does, in as much detail as users need.",
  "version": "1.0.0", "sdk_version": "0.6.0", "module": "manyvids" }

short_description (up to 160 characters) is shown on plugin cards — the landing page catalogue and the plugin shop; long_description (up to 4000) where there is room for details. Both are read whenever plugins are (re)loaded. The older description key still works as long_description.

Messenger notifications

When a process runs on the server, users can get its log events in their linked messengers (Telegram). Only events your manifest declares are offered one by one; everything else falls under a single "Other activity" switch that is off by default. Declare them under notifications.events, keyed by the event you log:

"notifications": {
  "events": {
    "new_msg": {
      "log": "input",
      "label": "New message",
      "description": "Someone sent you a message.",
      "default": true,
      "icon": "💬",
      "context": "from <b>{{extra.author}}</b>",
      "quote": "{{live.text|main_data}}",
      "replyable": true,
      "card": "member_profile",
      "throttle": { "max": 20, "per_s": 300 }
    }
  }
}
FieldMeaning
label, descriptionShown in the user's notification settings. label is required and is the message's title.
iconOne emoji shown before the title. It is the only icon in the message.
logOnly entries of this log (the name given to new Stats(id, name)); any log when omitted.
defaultSent unless the user turns it off. Defaults to false.
contextOne short line under the title: who or what the message is about.
formatThe body: what happened, in a sentence or two. Defaults to {{main_data}}, or nothing when quote is given.
quoteSomeone else's words (a message, a comment, an error), shown as a quote.
replyableReplying to the message sends the reply to extra_data.sender_id via your plugin's on_send_direct_message(recipient_id, message, { attachments }). true for text only, or { "attachments": true } to also accept files (images and videos, up to 5 files of 20 MB), or { "attachments": { "accept": ["image/*"], "max_files": 3, "max_bytes": 10000000 } }. Files arrive as RemoteFiles; pass them to Media.upload_files / Chat.send like a File (server runs).
card"member_profile" adds a collapsed Profile section built from the entry's profile.
throttleAt most max messages per per_s seconds per process; the rest arrive as one "+N more" summary.
reviewA reply drafted for review: main_data is the text, extra_data.draft_id (16 hex chars) and extra_data.sender_id identify it. Messengers get Send / Regenerate / Reject buttons; views use ui.review_reply. Night logs the outcome as <event>_sent, <event>_rejected or <event>_regenerated (plus the new draft). Regenerating from a messenger calls your callable method regenerate_reply(draft) on the server.

Every notification has the same layout, and Night builds it from these parts: the icon and title, the context line, the body, the quote, the collapsed profile, and last a short italic hint such as "Reply to this message to answer them". Don't put the title or line breaks for layout into your templates.

context, format and quote are templates, not code. {{path}} inserts a value from the log entry: main_data, main_data.<field> for object payloads, extra.<path> for extra_data, live.<path> for the entry's live part (never stored), event, log. {{a|b}} uses b when a is empty, {{a|'text'}} falls back to a literal. Inserted values are HTML-escaped; the template itself may use <b> <i> <u> <s> <code> <pre> (balanced). Messages are cut to Telegram's length limit.

The server reads manifest.json whenever plugins are (re)loaded; invalid entries are skipped and logged. Process start/stop/failure notices are sent by Night itself — don't declare those.

Count-only events

Some events are only worth a number: "skipped this member", "page fetched". Every log entry is normally stored, so frequent events like these make up most of the log without anyone reading them one by one. List them under log.count_only (exact event names, or a prefix ending in *):

"log": {
  "count_only": ["s_*", "page_fetched"]
}

Matching entries are still counted everywhere (the process page's charts, the stats page, run reports), still appear live in an open dashboard, and still trigger notifications. They just aren't kept as log rows. That means:

  • they disappear from the log history after a reload;
  • query_log() never finds them, so never mark an event your plugin deduplicates on;
  • goals can't measure them.

Shared events

query_log() only looks at the current user's own runs of your plugin. To check whether anyone using the plugin already did something to a person, for example "skip members someone messaged in the last 7 days", list that event under log.shared:

"log": {
  "shared": ["p_follower"]
}

A query for a shared event that gives only event and main_data then covers every user's runs. It still answers only yes or no. Exact event names only, and a shared event can't be count-only.

Logging an entry once, and data that isn't stored

Two optional fields of a log entry change how it is stored:

  • live: an object that reaches the live log table and messenger notifications, but is never stored. A row loaded later has only extra_data. Use it for bulky details that only matter while the entry is new, and keep a small copy in extra_data.
  • once: a key. The entry is dropped when any run of your plugin on the same account already logged an entry with the same event, main_data and once. Use it for things a new run would see again, like a message that is still unread.

Where it runs

Plugin code never runs in the Night dashboard page. The same index.js runs isolated wherever it is started:

RunWherePlatform requests
Local (the user's browser)a hidden sandboxed iframe, created when the process starts and removed when it stopsthrough the Night Loader extension, with the account's session
Servera sandboxed process on Night's servers (own user, no network, no secrets)through the account's session and proxy IP, on the server

Either way the plugin can't reach the dashboard's DOM, cookies, storage or session, and every request goes through Night:

  • Use the platform namespaces (loader.SDK.Manyvids …) for platform requests; the host attaches the account's session and only lets requests reach the account's own platform.
  • Night's own API (fetch to constants.DASHBOARD_API_URL, NightFetch, query_log) is limited to the routes plugins may use, for the plugin's own process and access token.
  • Other fetch() targets work on the server only (public addresses only); in the browser they throw.
  • Code runs in both places, so never touch document/window outside views. constants.DEVELOPMENT is true on a development build of Night — fine for debug-friendly defaults, nothing else.
  • A platform call rejected because the account's session expired throws an SdkError with code UNAUTHORIZED: stop (this.fail(e)) rather than retrying it forever.
  • exec() has no page to build UI in. The UI is the static settings form plus your views; to ask the dashboard for something (a toast, opening a link), use loader.SDK.ui.
  • Only the version an admin approved runs: Night pins the sha256 of index.js when plugins are reloaded and refuses changed code until the next reload.

Lifecycle

HookWhen
constructorProcess created: the start of a run, or a view/call on an instance that's never started
on_activation(fn)Browser: the user started the process (local or server run), before its settings are saved. File fields are File objects here (e.g. upload them). Return an object to add it to the run's settings
before_start(fn)Every start, before exec()
exec()Main loop. Return to finish; check this.state === 'stopped' in long loops
after_start(fn)After exec() resolves
on_state_change(fn), on_error(fn)State transitions and unhandled errors

Settings from menu.html are available as this.options.obj — during a local run, the form's current values (they're pushed to the running plugin as the user edits them).

Methods the dashboard can call

List instance methods the dashboard may call in a static callable array. Night's conversation dialog, for example, asks for an AI reply through build_ai_reply(recipient_id, profile) when the plugin offers it. A call runs on the live instance when the process runs in that tab, otherwise on a fresh instance that is never started. Arguments and results must be plain data.

static callable = ["build_ai_reply"];

Night looks for a few more by name. Each one is optional and only used when the plugin lists it:

MethodUsed for
build_ai_reply(recipient_id, profile)The conversation dialog's "AI reply" button
regenerate_reply(draft)A new text for a reply drafted for review (review: true event), when the user taps Regenerate in a messenger
member_profile(sender_id)The full profile for the conversation dialog, when a log row stores only a slim copy (partial: true)
conversation(sender_id)A ChatThread (as from Chat.get_thread), shown under an entry opened from a messenger notification list

on_send_direct_message(recipient_id, message, { attachments }) is a plain method, not a callable. Night calls it with a messenger reply to a replyable notification, or with an approved reviewed reply.

on_platform_event({ type, data, at }) is another plain method. On server runs of platforms that have one (OnlyFans), Night keeps the platform's own live connection open for the whole run, the way the site's page does, and passes its events here: message (a new chat message, as the platform sends it), message_deleted, chat_counters, notification_counters, online (user ids now online). React to them instead of polling: a message event is the moment to fetch the conversation. Events arrive one at a time and aren't awaited; the connection's login never reaches the plugin. Messages.send_typing({ user_id }) shows "typing…" over the same connection.

Settings menu

menu.html is plain, static HTML — the settings form shown on the process page. Every named form control (input, select, textarea, and the SDK's custom inputs such as mv-multi-input) becomes a key of this.options.obj. Wrap the form in <div id="process_options" is="loader-process-options">.

Two placeholders are filled in by Night; nothing else is interpreted:

PlaceholderBecomes
{{t:key}}Your translation for the viewer's language, from locales/<lang>.json (en, ru); falls back to en, then to the key itself. Escaped, so it is safe in text and attribute values
{{icon:name}}One of Night's built-in icons (account, app, camera, categories, menu, people, squares_plus, subscription)
my_plugin/
├── manifest.json
├── index.js
├── menu.html          <label>{{t:enabled}} <input type="checkbox" name="enabled"></label>
├── view.css           optional: styles for your menu and views (never applied to the dashboard)
└── locales/
    ├── en.json        { "enabled": "Enabled" }
    └── ru.json        { "enabled": "Включено" }

The whole menu runs in one sandboxed frame on the process page, together with your views. Its CSP allows no inline scripts or event handlers: use attributes and views for behaviour. Style it with Night's classes. Interactive parts are declared with attributes Night carries out:

AttributeEffect
data-show-when="field" or "field=a|b"Shown only while checkbox field is checked, or field's value is a or b
data-status-of="checkbox_id", with data-on, data-off and a [data-status-text] childGets data-active="true"/"false" and the matching text as the checkbox changes
data-toggle-details (button)Opens/closes every details.separate in its .box_container
data-toggle-hidden="panel_id" (button)Shows/hides the panel; a click elsewhere hides it
data-insert="text" with data-insert-target="field_id" (button)Inserts the text at the field's cursor
data-template-preview="field_id" with data-preview-target="out_id" and data-sample='{…}' (button)Fills the field's message template with the sample values into out_id
data-chime-preview="select_id" (button)Plays the notification sound chosen in that select

<emoji-picker target="#field_id"> and Night's form components (range-slider, night-tab, multi-input, mv-multi-input) work as usual.

<night-file name="…"> and <mv-night-file name="…"> show as a button labelled with the element's text, which opens Night's file picker in the dashboard: files stay outside the frame until a run's on_activation hooks receive them in this.options.obj. On an account with the Storage addon switched on, the picked entries are RemoteFiles instead of Files: upload them in before_start by passing them to a platform upload such as Manyvids.Media.upload_files, and the host streams the bytes, in browser and server runs alike. Return them from the activation so they reach before_start through the settings.

The process' logs aren't part of the menu. Night shows them below it, one table per entry of the manifest's log.tables:

"log": {
  "tables": [
    { "name": "output", "title": "activity_title" },
    { "name": "input", "type": "input", "title": "inbox_title", "max_entries": 100 }
  ]
}

name is the log, title a key of your translations; type is output (default) or input, the table with the reply and chat actions.

Message templates in settings should use the shared syntax of loader.SDK.utils.fill_template: {{name}} inserts a value, {{[a|b|c]}} picks one option at random.

Views

Dynamic UI (dashboards, charts, review queues) is made of views: named functions exported next to your class.

export const views = {
    async dashboard(root, ctx) {
        const url = `${constants.DASHBOARD_API_URL}/manyvids/dashboard?access_token_id=${ctx.process.access_token_id}`;
        const data = await (await fetch(url)).json();
        root.querySelector("#total").textContent = data.scan?.total ?? "—";
    },
};

Place one in your menu with <night-plugin-view name="dashboard">…</night-plugin-view>. Its content is the view's static markup (translated with {{t:…}} like the rest of the menu), and views.dashboard(root, ctx) takes over with root being that element. Fields of a view without a name stay out of the settings. The frame has Night's stylesheets, your view.css, Chart.js (window.Chart), <table is="night-table"> and the form attributes above; it follows the user's contrast and text size by itself as long as you use Night's tokens and rem units.

ctx
pluginAn instance of your class that is never started — use its helpers; platform calls run as the process' account
process{ id, access_token_id, state, on_state(fn) }
settings(), on_settings(fn)The settings form's current values
log(name)The process' log name (entries are saved and appear in its table)
on_log(fn)New log entries of the process as they arrive (from its run, or from Night)
call(method, ...args)A callable method — on the live run when there is one
uiSame as loader.SDK.ui

Views may call a few more Night routes than a running process (its dashboards' read endpoints), still only for their own process and access token.

Asking the dashboard

loader.SDK.ui sends requests to the Night dashboard, which carries them out or refuses:

Call
ui.toast({ type, title, description, seconds })A toast, labelled with your plugin's name
ui.open_url(url)Opens an http(s) link in a new tab
ui.copy(text)Copies to the clipboard (after a click in your view)
ui.open_member_chat({ sender_id, profile })Night's conversation dialog for a platform member
ui.review_reply({ process_id, draft_id, action, message_text })Acts on a reply drafted for review (review: true event): approve, mark_sent, reject or regenerate (asks the user for their key when the server needs it)
ui.prefs.get(key), ui.prefs.set(key, value)Your plugin's device-local preferences

On the server there's no dashboard: every call resolves without effect (ui.available is false).

Errors

Every SDK method rejects with SdkError:

try {
    await this.mv.Messages.send_message({ recipient_id, message });
} catch (e) {
    if (e instanceof loader.SDK.SdkError && e.code === "REJECTED") { /* e.g. NO_MESSAGE_PRIVILEGE */ }
    else throw e;
}

e.code is one of:

Code
TRANSPORTThe request didn't get an answer: network down, platform unreachable, retries exhausted
UNEXPECTED_RESPONSEThe platform answered, but not in the expected shape
REJECTEDThe platform refused with a business error (e.message says which)
UNAUTHORIZEDThe platform refused the account's session (HTTP 401): the user has to sign in again
INVALID_ARGUMENTMissing or invalid params
NO_CONTEXTNo account could be resolved for an account-scoped call
UNSUPPORTEDThe call can't run where the plugin runs (browser vs. server)

Stop on UNAUTHORIZED rather than retrying: every further request fails the same way until the session is renewed.

Log e.message, not the error object. Log tables render main_data as text.

Reference