The orbit_sdk package lets you add your own commands, screens, settings and event handlers to Orbit with Python. This page covers SDK API version 1, including the SDK 1.1 additions (settings, live panels, capabilities and the extra events). Everything in 1.1 is additive: scripts written for 1.0 keep working.
You do not install orbit_sdk: it ships inside Orbit. A script runs in its own process started by Orbit, where from orbit_sdk import ... always works. (For autocomplete in an editor, put a copy of the orbit_sdk folder next to your script; scripts cannot run outside Orbit.)
Contents
- Quick start
- Where scripts live
Script(...)- Commands and options
- The context:
ctx - Saved state
- Settings
- Panels and pages
- Live panel status
- Notifications
- Events
- Capabilities and approval
- Load and unload hooks, background tasks
- Limits
- Security model
- Complete example
- Version history
Quick start
from orbit_sdk import Context, Script
script = Script(
id="my-tools",
name="My tools",
version="1.0.0",
api_version=1,
description="My own commands.",
)
@script.command("hello", description="Say hello")
async def hello(ctx: Context, name: str = "world"):
return f"Hello, {name}!"
- In Orbit, open Scripts, type an id under New script and press Create from template, or copy a script folder into the scripts folder (Open folder) and press Rescan.
- Select the script, tick Enabled and confirm.
- Run it from the test field on the Scripts screen, the Overview command line, or Discord with your prefix:
.hello Ana.
Where scripts live
Each script is a folder holding one script.py, under Orbit’s data folder:
%APPDATA%\offbrand\orbit\scripts\<script-id>\script.py
The folder name is the script’s id and must match Script(id=...).
| Folder (under the data folder) | Holds |
|---|---|
scripts\<id>\ |
Your source, script.py (256 KiB at most). |
script-data\<id>\ |
The script’s own folder (ctx.data_dir): its saved state, settings, and any files it writes. |
script-history\<id>\ |
Every version that loaded; the newest 20 are kept. |
logs\scripts\<id>.log |
print output and ctx.logger messages (rotating, 256 KiB). |
A disabled script never runs: Orbit reads its Script(...) line without executing the file.
Script(...)
script = Script(id, name, version="0.1.0", author="", description="", api_version=1, capabilities=None)
| Argument | Rules |
|---|---|
id |
2–32 lowercase letters, digits and -, starting with a letter or digit. The folder’s name. |
name |
1–60 characters. Shown on the Scripts screen and as the label of its notifications. |
version, author, description |
Shown on the Scripts screen and in Community. |
api_version |
1. |
capabilities |
What the script uses; see Capabilities. Leave it out to declare nothing (the 1.0 behaviour). |
Write the arguments as plain values (strings, numbers, a tuple of strings). Orbit reads them without running the file; anything computed fails to load.
Commands and options
@script.command("greet", description="Say hello", aliases=("hi",))
async def greet(ctx: Context, name: str = "world"):
return f"Hello, {name}!"
- The handler is
async defand takesctxfirst. - Names and aliases: up to 24 lowercase letters, digits,
-and_, starting with a letter or digit. A name Orbit or another script already uses makes the load fail; nothing is replaced. - The description (under 200 characters) appears in
.help, the Commands screen and the command palette. - A script must define at least one command.
- Commands run from the Orbit window and, with your prefix, from Discord (only your own account’s messages).
Options
Every parameter after ctx is an option, typed str, int, float or bool; no annotation means str. A default makes it optional.
from typing import Annotated
from orbit_sdk import Choices, Range
@script.command("roll")
async def roll(ctx, count: Annotated[int, Range(1, 20)] = 1,
mode: Annotated[str, Choices("sum", "list")] = "sum"):
...
| Helper | Meaning |
|---|---|
Range(min, max) |
Inclusive bounds for an int or float; either side may be None. |
Choices(*values) |
The only accepted values, of the option’s type. |
boolaccepts yes/no, y/n, true/false, on/off and 1/0.floatrefuses NaN and infinity.- Values are separated by spaces. When the last option is
str, it takes the rest of the line as typed:say hello theregivestext="hello there". - Orbit writes the usage line (
roll [count] [sum|list]) and answers wrong input itself: missing values, too many values, out-of-range numbers, unknown choices. *argsand**kwargsare not supported.
Answering
- Return a string: that is the answer. Returning nothing answers “Done.”
await ctx.send(text)adds a line before the returned text. The whole answer is sent when the handler returns (20,000 characters at most; long Discord answers are paged).ctx.error("message")orraise ScriptError("message")stops with that message shown to the user.- Any other exception shows a short failure; the traceback appears on the Scripts screen and in the script’s log.
- A command has 10 seconds. Use
await asyncio.sleep(...), nevertime.sleep(...): a script that stops responding is ended and its commands are removed until it is reloaded.
The context: ctx
Every command, event handler and settings hook receives a Context.
| Member | Meaning |
|---|---|
ctx.source |
"Desktop" or "Discord" for a command; "Event" inside an event handler or settings hook. |
ctx.command |
The command name, or the event kind ("settings" in a settings hook). |
ctx.argument |
The raw text after the command. |
await ctx.send(text) |
Add a line to the answer. |
ctx.error(message) |
Stop with a message (raises ScriptError). |
ctx.state |
Saved values; see Saved state. |
ctx.settings |
The declared settings’ current values, read-only; see Settings. |
ctx.data_dir |
The script’s own folder (a pathlib.Path), for a database, exports or other files. |
ctx.logger |
A standard logging.Logger writing to the script’s log file. |
ctx.set_panel(title, text) |
A live status line on panels; see Live panel status. |
ctx.notify(title, body="") |
A desktop notification; see Notifications. |
Scripts never get your token, a Discord client, or channel and message objects. Everything from Discord arrives as plain data in events.
Saved state
ctx.state (also host.state in hooks) is a small JSON store kept in the script’s folder, saved on every change and kept across reloads and restarts.
count = ctx.state.get("count", 0) + 1
ctx.state.set("count", count)
| Method | Meaning |
|---|---|
get(key, default=None) |
A saved value. |
set(key, value) |
Save a JSON value (string key). |
delete(key) |
Remove a value. |
keys() |
Every saved key. |
key in state, state[key] |
Membership and lookup. |
At most 64 KiB in total. For more data, use your own file or SQLite database in ctx.data_dir.
Settings
Declare settings and Orbit draws a form for them on the Scripts screen while the script runs, checks the values, stores them (settings.json in the script’s folder) and passes them to the script.
script.setting("account", label="Discord account ID", max_length=20, help="Shown as a tooltip.")
script.setting("limit", label="Limit", type=int, default=10, minimum=1, maximum=100)
script.setting("ratio", label="Ratio", type=float, default=0.5)
script.setting("loud", label="Notify me", type=bool, default=True)
script.setting("mode", label="Mode", choices=("calm", "busy")) # a dropdown
@script.command("limit")
async def limit(ctx):
return f"The limit is {ctx.settings['limit']}"
@script.on_settings
async def changed(ctx, settings):
ctx.logger.info("New limit: %s", settings["limit"])
script.setting(key, *, label, type=str, default=None, choices=(), minimum=None, maximum=None, max_length=200, help="")
| Argument | Rules |
|---|---|
key |
Up to 32 lowercase letters, digits and _, starting with a letter; unique in the script. |
label |
1–60 characters, shown in the form. |
type |
str (a text field), int (a whole-number box), float (a number box) or bool (a checkbox). |
default |
Used until the user saves a value. Without one: "", 0, 0.0, False, or the first choice. |
choices |
Makes a dropdown of values of type (30 at most). |
minimum, maximum |
Bounds for numbers. |
max_length |
Text length, 1–500. |
help |
A tooltip, up to 200 characters. |
- Save settings checks every value, stores them and sends them to the running script at once;
@script.on_settingshooks then run (async def hook(ctx, settings), 10 seconds each). ctx.settingsis read-only; only the user changes settings. A stored value that no longer fits the declaration falls back to its default.- At most 20 settings per script. The form appears while the script is running.
Panels and pages
Panels are cards with text and buttons that run the script’s own commands. They can sit on Orbit’s Add-ons screen or on the script’s own sidebar pages.
On the Add-ons screen
script.panel("Dice", text="Quick rolls.", buttons=[("Roll d6", "roll"), ("Count", "dicecount")])
On sidebar pages
stats = script.page("Stats", category="My tools", subtitle="Numbers from my script")
stats.panel("Counter", text="Saved between runs.", buttons=[("Count +1", "mycount"), ("Reset", "myreset")])
script.page("Quick ping", category="Tools").panel("Ping", buttons=[("Ping", "myping")])
category="Tools","Discord"or"App"(any capitalization) puts the page under Orbit’s heading of that name; any other name makes a new heading, shared by scripts that use the same name.- Pages and panels appear while the script runs and disappear when it is disabled or stops.
Text input
script.page("Greeter", category="Tools").panel("Greet someone", input="A name", buttons=[("Greet", "greet")])
With input="hint", the panel gets a text field. Each button passes what is typed as its command’s argument, exactly as if typed after the command name; Enter runs the first button. An empty field passes nothing, so the command’s defaults apply.
| Call | Rules |
|---|---|
script.panel(title, *, text="", buttons=(), input="") |
Up to 3 per script. |
script.page(title, *, category, subtitle="") |
Up to 4 per script. Title 1–30 characters, unique; category 1–24; subtitle up to 120. Returns a page. |
page.panel(title, *, text="", buttons=(), input="") |
Up to 3 per page. |
| A panel | Title 1–60 characters, text up to 500, up to 6 buttons, input hint up to 60, typed text up to 500. |
| A button | (label, command): a label of 1–40 characters and one of this script’s command names. |
A button’s answer shows inside the panel only; nothing goes to Discord.
Live panel status
ctx.set_panel("Overview", "Listening now · 3 events today")
ctx.set_panel(title, text) shows a status line under the title of every panel of this script called title, on Add-ons and on its pages, until it is set again; "" clears it. It works in commands, events, settings hooks and load hooks.
- Up to 300 characters, shown as plain text.
- Updates are combined: the latest text per panel is sent at most twice a second, so setting it often is cheap.
- Status lines start empty each time the script loads.
Notifications
ctx.notify("New post", "Help with setup")
ctx.notify(title, body="") shows a desktop notification and adds it to Orbit’s Notifications inbox, labelled with the script’s name.
- Title up to 80 characters, body up to 300.
- At most 10 a minute per script; extra ones are dropped, and
notifyreturnsFalse. - A script that declares capabilities needs
"notifications"; otherwisenotifyraisesScriptError.
Events
A script can react to what happens while your account is connected, without a command:
@script.on_event("mention")
async def mentioned(ctx, event):
ctx.notify(f"Mentioned by {event['author_name']}", event["content"])
@script.on_event(kind) registers async def handler(ctx, event), where event is a plain dict. All IDs are strings.
| Kind | When | event |
Capability |
|---|---|---|---|
"connected" |
Your account connected or resumed | account |
connection |
"disconnected" |
The connection dropped or ended | (empty) | connection |
"thread" |
A thread (a forum post is one) was created, updated, deleted, or listed | see below | threads |
"message" |
You sent a message that is not a command (and not one of Orbit’s own answers) | message fields | my_messages |
"mention" |
Someone else’s message mentions you | message fields | mentions |
"dm" |
Someone sent you a direct message | message fields | dms |
"reaction" |
Someone reacted to one of your messages | action (“add”), message_id, channel_id, guild_id, user_id, emoji |
reactions |
"member" |
Someone joined or left a server you are in | action (“join” or “leave”), guild_id, user_id, name, bot |
members |
Every event except disconnected also carries account: the connected account’s ID.
Message fields (message, mention, dm): id, channel_id, guild_id (None in DMs), author_id, author_name, content (up to 500 characters) and time (ISO 8601).
Thread events: action is "create", "update", "delete" or "sync"; guild_id; channel_ids (a sync’s scope, or None); threads, each with id, parent_id, name, newly_created, archived and tags (applied forum tag IDs); and parent_tags, each parent forum’s {tag ID: tag name}. A field the update left out is None.
How events are delivered:
- In order, one at a time; each handler has 10 seconds. A failing handler is logged and never affects Orbit.
- Orbit only prepares an event while a running script receives it. If 500 are waiting in Orbit, or 200 in one script, further events are dropped rather than slowing Discord down.
- Events only come from your own connected session.
- Discord may only send
memberevents to accounts with moderation rights in that server.
Capabilities and approval
Declare what your script uses in its Script(...) line:
script = Script(id="my-watch", name="My watch", version="1.0.0", api_version=1,
capabilities=("threads", "notifications"))
Orbit reads the list without running the file and shows it on the Scripts screen and in the question asked before the script is enabled.
| Capability | Meaning | Enforced |
|---|---|---|
connection |
The connected and disconnected events |
Yes |
threads |
The thread event |
Yes |
my_messages |
The message event |
Yes |
mentions |
The mention event |
Yes |
dms |
The dm event |
Yes |
reactions |
The reaction event |
Yes |
members |
The member event |
Yes |
notifications |
ctx.notify(...) |
Yes |
network |
Using the internet | No: a label |
files |
Reading or writing files outside the script’s own folder | No: a label |
- Once a script declares capabilities, Orbit enforces them: registering an event it did not declare fails the load, only declared events are delivered, and
ctx.notifyneedsnotifications. - The script’s own folder (
ctx.data_dir) needs no capability. - Approval. Enabling a script approves what it declares. If a later version (an edit, a reload, a Community update) declares more, Orbit does not load it, at startup too, until the user presses Approve and run… on the Scripts screen. Approvals are kept in Orbit’s database, not in the script’s folder, so a script cannot approve itself.
- The list must be written out (a tuple or list of names), and the running script must declare the same set as its
Script(...)line. - A script that declares nothing keeps working as in SDK 1.0; the Scripts screen says it does not declare what it uses. Declaring is strongly recommended, and Community expects it.
Load and unload hooks, background tasks
import asyncio
@script.on_load
async def loaded(host):
host.logger.info("Ready")
host.task(tick(host)) # cancelled automatically when the script unloads
async def tick(host):
while True:
await asyncio.sleep(60)
host.logger.info("Still here")
@script.on_unload
async def unloaded(host):
host.logger.info("Bye")
Hooks receive host, which offers host.logger, host.state, host.settings, host.data_dir and host.task(coroutine). Each hook has 5 seconds; a load hook that fails makes the load fail. Background tasks started with host.task are cancelled when the script unloads.
Limits
| Limit | Value |
|---|---|
script.py size |
256 KiB |
| Loading a script | 30 seconds |
| A command | 10 seconds |
| An event handler or settings hook | 10 seconds |
| A load or unload hook | 5 seconds |
| A command’s answer | 20,000 characters |
| Commands at once | One per script |
| Saved state | 64 KiB |
| Settings | 20 per script; text up to 500 characters |
| Add-ons panels | 3 per script |
| Pages | 4 per script, 3 panels each |
| Buttons | 6 per panel |
| Panel status line | 300 characters, at most 2 updates a second |
| Notifications | 10 a minute; title 80, body 300 characters |
| Message text in events | 500 characters |
| Events waiting | 500 in Orbit, 200 per script |
| Saved working versions | 20 |
Security model
- Scripts are trusted local code. Each runs in its own process, which separates crashes from Orbit, but it is not a sandbox: Python can read files, use the network and do anything your Windows account can. Enable only code you have read.
- Capabilities tell you what a script means to do and limit what Orbit hands it (events, notifications). They do not stop a script from using Python itself.
- Scripts never receive your token or a Discord client. They cannot send messages through Orbit.
Orbit.exe --safe-mode(orpython -m orbit --safe-mode) starts Orbit without loading any script, keeping your Enabled choices.- The Scripts module switch in Modules turns every script command off at once.
- If a script’s current file fails at startup, Orbit runs its last working version and says so. Compare with last working and Restore last working are on the Scripts screen.
- A packaged
Orbit.exeincludes only the standard-library modules Orbit itself uses, so a script importing another module may need Orbit run from source. No third-party packages are installed for scripts.
Complete example
"""Mention log: notifies you when someone mentions you, keeps a count, and shows it live."""
from orbit_sdk import Context, Script
script = Script(
id="mention-log",
name="Mention log",
version="1.0.0",
author="You",
api_version=1,
description="Notifies you about mentions and counts them.",
capabilities=("mentions", "notifications"),
)
script.setting("notify", label="Show a notification for each mention", type=bool, default=True)
script.setting("keep", label="Mentions to keep", type=int, default=20, minimum=1, maximum=100)
def status(ctx):
count = len(ctx.state.get("mentions", []))
ctx.set_panel("Mentions", f"{count} mention{'s' if count != 1 else ''} kept")
@script.on_event("mention")
async def mentioned(ctx: Context, event):
kept = ctx.state.get("mentions", [])
kept.append(f"{event['author_name']}: {event['content'][:100]}")
ctx.state.set("mentions", kept[-ctx.settings["keep"]:])
if ctx.settings["notify"]:
ctx.notify(f"Mentioned by {event['author_name']}", event["content"])
status(ctx)
@script.command("mentions", description="Show the mentions kept")
async def show(ctx: Context):
return "\n".join(ctx.state.get("mentions", [])) or "No mentions yet."
@script.command("mentionsclear", description="Forget the mentions kept")
async def clear(ctx: Context):
ctx.state.set("mentions", [])
status(ctx)
return "Cleared."
@script.on_load
async def loaded(host):
status(Context(host, "load", "", "Event"))
script.page("Mentions", category="Discord").panel(
"Mentions", text="Messages that mentioned you.",
buttons=(("Show", "mentions"), ("Clear", "mentionsclear")),
)
Version history
| Version | Added |
|---|---|
| 1.0 | Commands with typed options, Range and Choices; ctx.state, ctx.logger; load and unload hooks with host.task; Add-ons panels; sidebar pages; panel text input. |
| 1.0 (events) | @script.on_event with connected, disconnected and thread; ctx.notify; ctx.data_dir. |
| 1.1 | Declared settings (script.setting, ctx.settings, @script.on_settings); live panel status (ctx.set_panel); capabilities and approval; the message, mention, dm, reaction and member events. |
Planned next: more panel controls (tables, toggles, dropdowns, several inputs) and read access to Orbit’s notes, reminders and saved replies.