Guides
Script examples
Entry points
onActivate
onRoomEvent
onMessage
onCharEvent
onExitUse
onCommand
onRequest
API references
Mucklet scripts are written in AssemblyScript, a strictly typed TypeScript-like language. For more info on AssemblyScript, its types, and standard library, see:
The standard library of AssemblyScript has been extended with classes and functions to interact with Mucklet realms. See the API references for a complete list of those extensions.
| Script file | Description |
|---|---|
| ambience.ts | A script showing ambient descriptions with random time intervals. |
| day_and_night.ts | A script cycling between a "day" and "night" room profile based on real time. |
| intercom_inside.ts | An intercom script allowing communication with another room running the intercom_outside.ts script. |
| intercom_outside.ts | An intercom script allowing communication with another room running the intercom_inside.ts script. |
| lock_inside.ts | A script that locks a door preventing others from using an exit in the room running the lock_outside.ts script. |
| lock_outside.ts | A script that prevents characters from using an exit locked by the lock_inside.ts script. |
| secret_exit.ts | A script that reveals a secret passage when the password "tapeworm" is spoken. |
| vip_list.ts | A script that manages a list of VIP characters, requested by another room running the vip_guard.ts script. |
| vip_guard.ts | A script that prevents characters from using an exit unless they are listed as VIP character by the vip_list.ts script. |
The script entry points are exported functions that are called on different types of events, such as the script activating, someone entering a room, or a command being called.
The only entry point that is required is onActivate.
onActivate is called each time a script is activated or updated. It is primarily used to call Script.listen, Room.listen, or Room.addCommand, to have the script listening for events, messages, or commands.
When a script is updated, previous listeners, (e.g. Room.listen), commands (Room.addCommand), or scheduled posts (Script.post with delay), will be removed, and onActivate will be called again on the new script version.
// Send a describe to the room and log a message to the console on activation.
export function onActivate(): void {
Room.describe("Hello, world!");
console.log("Hello, console!");
}onRoomEvent is called when an event occurs in the room, such as a say, arrive, or sleep. Room.listen must have been called earlier to start listening to room events, usually in the onActivate function.
addr(string): Address of this script instance receiving the event.ev(string): Event encoded as a json string.
// Check the event type and decode the event.
export function onRoomEvent(
addr: string,
ev: string,
): void {
const eventType = Event.getType(ev);
if (eventType == 'say') {
const say = JSON.parse<Event.Say>(ev);
// Handle the say event
}
}onMessage is called when another script sends a message to this script, using Script.post or Script.broadcast. Script.listen must have been called earlier to start listening to messages, usually in the onActivate function.
addr(string): Address of this script instance receiving the message.topic(string): Topic of the message. Determined by the sender.data(string | null): JSON encoded data of the message or null. Determined by the sender.sender(string): Address of the sending script instance.
// Receive a message from another script to change room profile
export function onMessage(
addr: string,
topic: string,
data: string | null,
sender: string,
): void {
if (topic == "changeProfile") {
Room.setProfile(JSON.parse<string>(data))
}
}onCharEvent is called when a character enters a room, leaves a room, or changes any of its properties while inside the room. Room.listenCharEvent must have been called earlier to start listening to character events, usually in the onActivate function.
addr(string): Address of this script instance receiving the event.charId(string): ID of character.after(string | null): Character state after the event encoded as a json string, or null if the character left the room.before(string | null): Character state before the event encoded as a json string, or null if the character entered the room.
// Output to log when a character arrives or leaves
export function onCharEvent(
addr: string,
charId: string,
after: string | null,
before: string | null,
): void {
if (after == null && before != null) {
// If after is null, the character left
const char = JSON.parse<Room.Char>(before);
console.log(`${char.name} left.`)
}
if (before == null && after != null) {
// If before is null, the character arrived
const char = JSON.parse<Room.Char>(after);
console.log(`${char.name} arrived.`)
}
}onExitUse is called when a character tries to use an exit. Room.listenExit must have been called earlier to start listening to exit use, usually in the onActivate function. The script should call either ExitAction.cancel or ExitAction.useExit to determine what should happen. If neither method is called, the action will timeout after 1 second, automatically canceling the exit use with a default message.
addr(string): Address of this script instance receiving the event.cmdAction(ExitAction): Exit action object.
// Prevent anyone from using an exit
export function onExitUse(
addr: string,
exitAction: ExitAction,
): void {
exitAction.cancel("The door seems to be locked.");
}onCommand is called when a character uses a custom command. Room.addCommand must have been called earlier to register the command, usually in the onActivate function. The script may send a response to the caller using either CmdAction.info, CmdAction.error, or CmdAction.useExit, but it is not required. The response must be sent within 1 second from the call.
addr(string): Address of this script instance receiving the action.cmdAction(CmdAction): Command action object.
// Adding a ping command on activation
export function onActivate(): void {
Room.addCommand("ping", new Command("send ping", "Sends a ping to the script.");
}
// Adds a "send ping" command that responds with an info message
export function onCommand(
addr: string, // Address of this script instance receiving the action.
cmdAction: CmdAction, // Command action object.
): void {
cmdAction.info("Pong!");
}onRequest is called when another script sends a request to this script, using Script.request. Script.listen must have been called earlier to start listening to requests, usually in the onActivate function.
addr(string): Address of this script instance receiving the request.request(Request): Request object.
// Receive a request from another script and send a response.
export function onRequest(
addr: string,
request: Request,
): void {
if (request.topic == "getValue") {
// Parse any data passed as arguments.
const key = request.parseData<string>()
const value = Store.getString(key)
// Send a response to the request
request.reply(value)
}
}Type aliases
type Duration
type ID
type Timestamp
Enums
enum CharState
enum CommandFlag
enum ExitIcon
enum ExitNav
enum IdleLevel
enum RPState
Interfaces
interface CommandField
method getType
method getDesc
method getOpts
Classes
class CmdAction
method info
method error
method useExit
class Command
method field
method setPriority
method setRestricted
method setUnlisted
method json
class ExitAction
method useExit
method cancel
class Request
method parseData
method reply
method error
class Response
method isError
method parseResult
Namespaces
Event namespace
Field namespace
FieldValue namespace
JSON namespace
Room namespace
Script namespace
Store namespace
Event functions
function Event.getType
Event classes
class Event.Action
class Event.Arrive
class Event.Base
class Event.BaseCharMethodMsg
class Event.BaseCharMsg
class Event.BaseCharPoseMsg
class Event.Char
class Event.Describe
class Event.Leave
class Event.OOC
class Event.Pose
class Event.Roll
class Event.RollResult
class Event.Say
class Event.Sleep
class Event.Wakeup
Field classes
class Field.Bool
method getType
method getDesc
method getOpts
class Field.Char
method getType
method getDesc
method getOpts
method setInRoom
method setState
class Field.Float
method getType
method getDesc
method getOpts
method setMin
method setMax
class Field.Integer
method getType
method getDesc
method getOpts
method setMin
method setMax
class Field.Keyword
method getType
method getDesc
method getOpts
method setRemoveDiacritics
method setMinLength
method setMaxLength
class Field.List
method getType
method getDesc
method getOpts
method addItem
method setItems
class Field.Text
method getType
method getDesc
method getOpts
method setSpanLines
method setSpellCheck
method setFormatText
method setMinLength
method setMaxLength
FieldValue classes
class FieldValue.Bool
class FieldValue.Char
class FieldValue.Float
class FieldValue.Integer
class FieldValue.Keyword
class FieldValue.List
class FieldValue.Text
JSON enums
enum JSON.Types
JSON functions
function JSON.parse
function JSON.stringify
JSON classes
class JSON.Box
method set
method from
method toString
class JSON.Obj
method set
method get
method has
method delete
method keys
method values
method toString
method from
class JSON.Raw
method set
method toString
method from
class JSON.Value
method empty
method from
method set
method get
method as
method toString
Room functions
function Room.addCommand
function Room.canEdit
function Room.charIterator
function Room.describe
function Room.exitIterator
function Room.getChar
function Room.getDetails
function Room.getExit
function Room.getExitById
function Room.getExitOrder
function Room.listen
function Room.listenCharEvent
function Room.listenExit
function Room.privateDescribe
function Room.profileIterator
function Room.removeCommand
function Room.setExit
function Room.setRoom
function Room.sweepChar
function Room.unlisten
function Room.unlistenCharEvent
function Room.unlistenExit
function Room.useProfile
Room classes
class Room.Char
class Room.CharIterator
method next
method rewind
method getID
method isValid
method close
method getChar
class Room.Exit
class Room.ExitIterator
method next
method rewind
method getID
method isValid
method close
method getExit
class Room.MoveMsgs
class Room.Profile
class Room.ProfileIterator
method next
method rewind
method getID
method isValid
method close
method getProfile
class Room.RoomDetails
Script functions
function Script.broadcast
function Script.cancelPost
function Script.getChar
function Script.listen
function Script.post
function Script.request
function Script.unlisten
Script classes
class Script.Char
Store functions
function Store.deleteKey
function Store.getBuffer
function Store.getString
function Store.readOnly
function Store.setBuffer
function Store.setString
function Store.totalBytes
Store classes
class Store.Iterator
method withPrefix
method inReverse
method next
method seek
method rewind
method getKeyString
method getKeyBuffer
method getValueString
method getValueBuffer
method isValid
method isValidForPrefix
method close
type Duration = i64Duration in milliseconds.
type ID = stringID for in game entities such as characters, rooms, and areas.
type Timestamp = i64Timestamp as a UTC timestamp in milliseconds.
const enum CharState {
Asleep = 0,
Awake = 1,
Dazed = 2,
Any = 255,
}States that a character may have.
const enum CommandFlag {
None = 0,
Restricted = 1,
Unlisted = 2,
}Command flag.
const enum ExitIcon {
None = 0,
North = 1,
NorthEast = 2,
East = 3,
SouthEast = 4,
South = 5,
SouthWest = 6,
West = 7,
NorthWest = 8,
Up = 9,
Down = 10,
In = 11,
Out = 12,
}Exit navigation icon.
const enum ExitNav {
None = 0,
North = 1,
NorthEast = 2,
East = 3,
SouthEast = 4,
South = 5,
SouthWest = 6,
West = 7,
NorthWest = 8,
}Exit navigation directions.
const enum IdleLevel {
Asleep = 0,
Active = 1,
Idle = 2,
Inactive = 3,
}Idle levels that a character may have.
const enum RPState {
None = 0,
LFRP = 1,
}Roleplaying state that a character may have.
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
CmdAction is a command action triggered by a character.
actionId(i32): Action IDchar(Event.Char): Character performing the actionkeyword(string): Command keyworddata(string): Command data in JSON format.
info(msg: string): voidResponds to the command action with an info message.
msg(string): Info message. It may be formatted with info formatting and span multiple paragraphs.
error(msg: string): voidResponds to the command action with an error message.
msg(string): Error message. It may be formatted and span multiple paragraphs.
useExit(exitId: ID): voidResponds to the command action by making the character use an exit.
The exit may be hidden or inactive. May not be used in combination with info or error.
exitId(ID): Exit ID.
Command class is a representation of a custom command, and is used as an argument when calling Room.addCommand.
See also: Writing scripts - Custom commands
new Command(pattern: string, desc: string = "")Creates a new instance of the Command class.
pattern(string)desc(string)
priority(u32)flags(u32)pattern(string)desc(string)
field(key: string, def: CommandField): CommandSets the definition for a command field.
key(string): Field as found in command pattern.def(CommandField): Field definition.
- (Command): This instance, allowing method chaining.
setPriority(priority: u32): CommandSets command priority.
priority(u32): Priority for sort order (descending) and when two or more commands match the same input. Higher priority is selected first.
- (Command): This instance, allowing method chaining.
setRestricted(): CommandSets the command as restricted, only accessible to character able to edit the room.
- (Command): This instance, allowing method chaining.
setUnlisted(): CommandSets the command as unlisted, not showing up in the interface. It can
still be used, and will be listed using list commands.
- (Command): This instance, allowing method chaining.
json(): stringConverts the command into a JSON structure.
- (string)
ExitAction is an action representing an intercepted use of an exit.
It is passed to onExitUse entry point when a character tries to use an exit that is being listen to with Room.listenExit.
useExit(exitId: ID | null = null): voidMakes the character use an exit. If exitId is null, the character is sent through the exit that they originally tried to use.
The exit may be hidden or inactive.
exitId(ID | null): Exit ID or null for the originally used exit.
cancel(msg: string | null = null): voidCancels a character's attempt to use an exit and shows them an info message instead. If msg is null, the default exit timeout message will be shown.
msg(string | null): Info message to show, or default message if null.
Request is a request sent from another script.
actionId(i32): Action IDtopic(string): Request topicdata(string): Request data encoded as JSON.sender(string): Request sender address.
parseData<T>(): TParses the data into a value of type T.
- (T)
reply(result: string | null = null): voidResponds to the request with a reply containing JSON encoded result.
result(string | null): Reply data encoded as JSON.
error(msg: string): voidResponds to the request with an error message.
msg(string): Error message.
Response is a response to a request sent by the script.
result(string | null): Result encoded as JSON.error(string | null): Error string or null on no error.
isError(): booleanReturns true if it is an error response by checking that the error property is not a null value.
- (boolean)
parseResult<T>(): TParses the result into a value of type T.
- (T)
Event.getType(ev: string): stringGet event type from a json encoded event.
ev(string)
- (string)
Action event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Arrive event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.method(string): Method
Base event shared by all events.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.
Base event for message events by a character where a method is included, such as leave and arrive.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.method(string): Method
Base event for message events by a character, such as say, describe, pose, etc.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Base event for message events by a character that may optionally be marked as a pose, such as OOC events.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.pose(boolean): Message is a pose.
Character object with name and ID.
id(string): Character ID.name(string): Character name.surname(string): Character surname.
Describe event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Leave event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.method(string): Method
OOC event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.pose(boolean): Message is a pose.
Pose event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Roll event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.total(i32): Roll total.result(Array<Event.RollResult>): Roll result.quiet(boolean): Quiet roll.
Results in a roll event.
type(string)op(string): Modifier operator. Either "+" or "-".count(i32): Dice count. Always 0 on type "mod".sides(i32): Sides on dice. Always 0 on type "mod"dice(Array<i32>): Roll value for each die. Always empty slice on type "mod"value(i32): Modifier value. Always 0 on type "std".
Say event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Sleep event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
Wakeup event.
id(string): Event ID.type(string): Event type.time(i64): Unix timestamp (milliseconds).sig(string): Signature.msg(string): Message.char(Event.Char): Acting character.puppeteer(Event.Char | null): Acting puppeteer.
An bool field is used for boolean values.
new Field.Bool(desc: string = "")desc(string)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
A char field is used to enter the name of a character.
new Field.Char(desc: string = "")desc(string)
inRoom(boolean)state(CharState)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
setInRoom(): thisSets inRoom flag, requiring the character to be in the room.
- (this): This instance, allowing method chaining.
setState(state: CharState): thisSets state that the character must be in. Default is CharState.Any.
state(CharState)
- (this): This instance, allowing method chaining.
A float field is used for decimal numbers.
new Field.Float(desc: string = "")desc(string)
min(f64)max(f64)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
setMin(min: f64, inclusive: bool): thisSets float min value. Must be smaller than (or equal if both are inclusive) to max value.
min(f64): Min value of float.inclusive(bool): Flag to tell if min value is inclusive (>=) on true, or exclusive (>) on false.
- (this): This instance, allowing method chaining.
setMax(max: f64, inclusive: bool): thisSets float max value. Must be greater than (or equal if both are inclusive) to min value.
max(f64): Max value of float.inclusive(bool): Flag to tell if max value is inclusive (<=) on true, or exclusive (<) on false.
- (this): This instance, allowing method chaining.
An integer field is used for whole numbers.
new Field.Integer(desc: string = "")desc(string)
min(i64)max(i64)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
setMin(min: i64): thisSets integer min value. Must be smaller or equal to max value.
min(i64): Min value of integer.
- (this): This instance, allowing method chaining.
setMax(max: i64): thisSets integer max value. Must be greater or equal to min value.
max(i64): Max value of integer
- (this): This instance, allowing method chaining.
A keyword field is used for keyword names using a limited set of characters that will be transformed to lower case. By default, a keyword allows Letters, Numbers, Spaces, apostrophes ('), and dash/minus (-).
new Field.Keyword(desc: string = "")desc(string)
removeDiacritics(boolean)minLength(u32)maxLength(u32)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
setRemoveDiacritics(removeDiacritics: boolean): thisSets flag to remove diacritics from the keyword by decomposing the characters and removing any non-print characters and marker in the Mn Unicode category. Is false by default.
removeDiacritics(boolean): Flag telling if diacritics should be removed.
- (this)
setMinLength(minLength: u32): thisSets text min length. Must be smaller or equal to max length unless max length is set to zero (0).. Is 0 by default.
minLength(u32): Min length of text.
- (this)
setMaxLength(maxLength: u32): thisSets text maximum length. Zero (0) means server max length. Is 0 by default.
maxLength(u32): Max length of text.
- (this)
A list field is used to select between a list of items. Items must be unique, not containing non-printable or newline characters, and be trimmed of leading, trailing, and consecutive spaces.
Items should not contain characters used as delimiters to continue the command.
new Field.List(desc: string = "")desc(string)
items(Array<string>)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
addItem(item: string): thisAdds a single item to the list.
item(string)
- (this): This instance, allowing method chaining.
setItems(items: Array<string>): thisSets an array of list items, replacing any previously set items.
items(Array<string>): Array of list items.
- (this): This instance, allowing method chaining.
A text field is used for arbitrary text, such as messages, descriptions, or titles.
new Field.Text(desc: string = "")desc(string)
spanLines(boolean)spellCheck(boolean)formatText(boolean)minLength(u32)maxLength(u32)
getType(): stringReturns the type of the command field.
- (string)
getDesc(): stringReturns the help description of the command field.
- (string)
getOpts(): string | nullReturns the options of the command field as a JSON encoded string.
- (string | null)
setSpanLines(spanLines: boolean): thisSets span lines flag. Is false by default.
spanLines(boolean): Flag telling if the text can be spanned across multiple lines.
- (this): This instance, allowing method chaining.
setSpellCheck(spellCheck: boolean): thisSets flag to spellCheck text. Is true by default.
spellCheck(boolean): Flag telling if the text should be checked for spelling errors.
- (this): This instance, allowing method chaining.
setFormatText(formatText: boolean): thisSets flag to format text while typing. Is false by default.
formatText(boolean): Flag telling the text should be formatted while typing.
- (this): This instance, allowing method chaining.
setMinLength(minLength: u32): thisSets text min length. Must be smaller or equal to max length unless max length is set to zero (0).. Is 0 by default.
minLength(u32): Min length of text.
- (this): This instance, allowing method chaining.
setMaxLength(maxLength: u32): thisSets text maximum length. Zero (0) means server max length. Is 0 by default.
maxLength(u32): Max length of text.
- (this): This instance, allowing method chaining.
value(bool)
id(string): Character ID.name(string): Character name.surname(string): Character surname.
value(f64)
value(i64)
value(string)
value(string)
value(string)
enum Types {
Raw = 0,
U8 = 1,
U16 = 2,
U32 = 3,
U64 = 4,
F32 = 5,
F64 = 6,
Null = 7,
Bool = 8,
String = 9,
Object = 10,
Array = 12,
Struct = 13,
}Enum representing the different types supported by JSON.
JSON.parse<T>(data: string): TParses valid JSON strings into their original format
JSON.parse<T>(data)data(string): string
- (T): T
JSON.stringify<T>(data: T, out: string | null = null): stringSerializes valid JSON data
JSON.stringify<T>(data)data(T): Tout(string | null)
- (string): string
Box for primitive types
new JSON.Box<T>(value: T)value(T)
value(T)
set(value: T): Box<T>Set the internal value of Box to new value
value(T): T
- (JSON.Box<T>): this
from<T>(value: T): Box<T>Creates a reference to a primitive type This means that it can create a nullable primitive
JSON.stringify<Box<i32> | null>(null);
// nullvalue(T)
- (JSON.Box<T>): Box
toString(): string- (string)
new JSON.Obj()storage(Map<string, JSON.Value>)
set<T>(key: string, value: T): voidkey(string)value(T)
get(key: string): Value | nullkey(string)
- (JSON.Value | null)
has(key: string): boolkey(string)
- (bool)
delete(key: string): boolkey(string)
- (bool)
keys(): Array<string>- (Array<string>)
values(): Array<Value>- (Array<JSON.Value>)
toString(): string- (string)
from<T>(value: T): Objvalue(T)
- (JSON.Obj)
new JSON.Raw(data: string)data(string)
data(string)
set(data: string): voiddata(string)
toString(): string- (string)
from(data: string): Rawdata(string)
- (JSON.Raw)
METHODS(Map<u32, u32>)type(i32)
empty(): ValueCreates an JSON.Value instance with no set value.
- (JSON.Value): An instance of JSON.Value.
from<T>(value: T): ValueCreates an JSON.Value instance from a given value.
value(T): The value to be encapsulated.
- (JSON.Value): An instance of JSON.Value.
set<T>(value: T): voidSets the value of the JSON.Value instance.
value(T): The value to be set.
get<T>(): TGets the value of the JSON.Value instance.
- (T): The encapsulated value.
as<T>(): TGets the value of the JSON.Value instance. Alias for .get()
- (T): The encapsulated value.
toString(): stringConverts the JSON.Value to a string representation.
- (string): The string representation of the JSON.Value.
Room.addCommand(keyword: string, cmd: Command, priority: u32 = 0): voidAdds a custom command to the room.
Pattern is a string describing the general command structure, and may contain <Fields> parts. Any field defined in the pattern must have a corresponding field entry.
See also: Writing scripts - Custom commands
keyword(string): Keyword for the command.cmd(Command): Command to add.priority(u32): Deprecated: Use Command.setPriority instead.
Room.canEdit(charId: ID): booleanChecks if a character is the owner of the room, or if the owner shares the same player as the character. It does not include admins or builders.
charId(ID): Character ID.
- (boolean)
Room.charIterator(state: CharState = CharState.Any, reverse: boolean = false): CharIteratorGets an iterator for the characters in the room that iterates from the character most recently entering the room.
state(CharState): State of the characters to iterate over.reverse(boolean): Flag to reverse the iteration direction, starting with the character that has been in the room the longest.
Room.describe(msg: string): voidSends a "describe" event to the current room instance.
msg(string)
Room.exitIterator(): ExitIteratorGets an iterator for the exits in the room. Order is undefined.
Room.getChar(charId: ID): Char | nullGets a character in the room by ID.
charId(ID): Character ID.
Room.getDetails(): RoomDetailsGet detailed room information, such as description and settings.
Room.getExit(keyword: string): Exit | nullGets an exit in the room by keyword.
keyword(string): Exit keyword.
Room.getExitById(exitId: ID): Exit | nullGets an exit in the room by ID.
exitId(ID): Exit ID.
Room.getExitOrder(): Array<ID>Gets the exit order of visible exits in the room as an array of ID values.
- (Array<ID>)
Room.listen(instance: string | null = null): booleanStarts listening to room events on the current instance. If instance is
set, it starts listening for events in that specific instance, or null
for any room instance. Room events will be sent to onRoomEvent for the
instance.
instance(string | null): Instance or null for the non-instance.
- (boolean): Returns true if a new listener was added, otherwise false.
Room.listenCharEvent(instance: string | null = null): booleanStarts listening to char events in the room. If instance is set, it
starts listening for events in that specific instance, or null for any
room instance. Char events will be sent to onCharEvent for the
instance.
instance(string | null): Instance or null for any instance.
- (boolean): True if a new listener was added, otherwise false.
Room.listenExit(exitId: string | null = null): booleanStarts listening to exit usage in the room, including any instance. If
exitId is null, it acts as a wildcard to listen to any exit otherwise
not being listened to specifically. Exit use events will be sent to
onExitUse.
Only one script may listen to a given exit at any time. Only one script may listen to any exit with the null wildcard at any one time
exitId(string | null): Exit ID or null for any exit.
- (boolean): True if a new listener was added, otherwise false.
Room.privateDescribe(msg: string, targetCharIds: Array<ID>): voidSends a "privateDescribe" event to one or more target characters in the current room instance. A private describe can only be seen by the targeted characters.
msg(string)targetCharIds(Array<ID>)
Room.profileIterator(): ProfileIteratorGets an iterator for the profiles for the room. Order is undefined.
Room.removeCommand(keyword: string): booleanRemoves a custom command, added by the script, from the room.
keyword(string): Keyword for the command.
- (boolean)
Room.setExit<T>(exitId: ID, fields: T): voidSet exit information.
The field parameter must an object that can be converted to a json object string with JSON.stringify, containing the following fields. Any other fields will be ignored.
{
name?: string, // Name of the exit.
keys?: string[], // Exit keywords used with the go command.
leaveMsg?: boolean, // Message seen by the origin room. Usually in present tense (eg. "leaves ...").
arriveMsg?: boolean, // Message seen by the arrival room. Usually in present tense (eg. "arrives from ...").
travelMsg?: boolean, // Message seen by the exit user. Usually in present tense (eg. "goes ...").
icon?: ExitIcon, // Icon for the exit.
nav?: ExitNav, // Navigation direction for the exit.
hidden?: boolean, // Flag telling if the exit is hidden, preventing it from being listed.
inactive?: boolean, // Flag telling if the exit is inactive, preventing it from being listed and used.
transparent?: boolean, // Flag telling if the exit is transparent, allowing you to see awake characters in the target room.
order?: i32|i32u|i64|i64u, // Sort order of the exit with 0 being the first listed. Ignored if the exit is hidden or inactive.
}// Setting a room exit to be active
Room.setExit(exitId, new Map<string, boolean>().set("inactive", false))exitId(ID): Exit ID.fields(T): Exit fields to update as an object that can be stringified to json.
Room.setRoom<T>(fields: T): voidSet room information.
The field parameter must an object that can be converted to a json object string with JSON.stringify, containing the following fields. Any other fields will be ignored.
{
name?: string, // Room name.
desc?: string, // Room description.
isDark?: boolean, // IsDark flags if other character can be seen or whispered to in the room.
isQuiet?: boolean, // IsQuiet flags if a room is quiet and won't allow communication.
isHome?: boolean, // IsHome flags if the room can be set as home by others.
isTeleport?: boolean, // IsTeleport flags if the room can be added as a teleport node by others.
isInstance?: boolean, // IsInstance flags if the room creates an instance.
autosweep?: boolean, // Autosweep flags if sleepers in the room should be sent home automatically.
autosweepDelay?: Duration, // AutosweepDelay is the time in milliseconds until a sleeper is swept.
customTeleportMsgs?: boolean, // CustomTeleportMsgs flags if the room uses custom teleport messages.
overrideCharTeleportMsgs?: boolean, // OverrideCharTeleportMsgs flags if the custom teleport messages should override any set character teleport messages.
teleportLeaveMsg?: object, // Custom teleport message shown when someone teleports away from the room.
teleportArriveMsg?: object, // Custom teleport message shown when someone teleports into the room.
teleportTravelMsg?: object, // Custom teleport message shown to the character teleporting into the room.
}// Setting the room to be dark
Room.setRoom(new Map<string, boolean>().set("isDark", true))fields(T): Room fields to update as an object that can be stringified to json.
Room.sweepChar(charId: ID, msg: string | null): voidSweep a single character from the room by sending them home.
charId(ID): Character ID.msg(string | null): Message to show too the room when the character is teleported away. Defaults to other teleport messages.
Room.unlisten(instance: string | null = null): booleanStops listening to room events on the current instance. If instance is
provided, it stops listening for that specific instance, or null for the
non-instance room.
instance(string | null): Instance or null for the non-instance.
- (boolean): True if a listener existed, otherwise false.
Room.unlistenCharEvent(instance: string | null = null): booleanStops listening to char events in the room. If instance is set, it
stops listening for events in that specific instance, or null for any
room instance.
instance(string | null): Instance or null for any instance.
- (boolean): True if a listener existed, otherwise false.
Room.unlistenExit(exitId: string | null = null): booleanStops listening to exit usage in the room. If exitId is set, it stops
listening for exit use for that specific exit, or null to stop listening
for the the wildcard listener.
exitId(string | null): Exit ID or null for any exit.
- (boolean): True if a listener existed, otherwise false.
Room.useProfile(keyword: string, safe: boolean = false): voidSwitches to a stored room profile by profile key.
keyword(string): Keyword for the stored profile.safe(boolean): Flag to prevent the room's current profile to be overwritten by the stored profile, if it contains unstored changes.
Room character.
id(ID): Character ID.name(string): Character name.surname(string): Character surname.avatar(ID): Character avatar.species(string): Character species.gender(string): Character gender.desc(string): Character description.image(ID): Character image.state(CharState): Character state.idle(IdleLevel): Character idle status.rp(RPState): Character RP state.
new Room.CharIterator(iterator: i32)Constructor of the Iterator instance.
iterator(i32)
iterator(i32)
next(): voidAdvances the iterator by one. Always check isValid() after a next() to ensure have not reached the end of the iterator.
rewind(): voidRewinds the iterator cursor all the way back to first position, which would be the smallest key, or greatest key if inReverse() was called.
Any iterator prefix passed to withPrefix() will be used on rewind. The iterator is rewound by default.
getID(): IDReturns the key string of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (ID)
isValid(): booleanReturns false when the cursor is at the end of the iterator.
- (boolean)
close(): voidCloses the iterator. Any further calls to the iterator will cause an error. May be called multiple times.
getChar(): CharReturns the current char. It will abort if the cursor has reached the end of the iterator.
Room exit.
id(ID): Exit ID.keys(Array<string>): Exit keys.name(string): Exit name.icon(ExitIcon): Exit icon.nav(ExitNav): Exit navigation direction.leaveMsg(string): Leave message.arriveMsg(string): Arrival message.travelMsg(string): Travel message.targetRoom(ID): Target room.created(i64): Created timestamp.hidden(boolean): Is hidden flag.inactive(boolean): Is inactive flag.transparent(boolean): Is transparent flag.
new Room.ExitIterator(iterator: i32)Constructor of the Iterator instance.
iterator(i32)
iterator(i32)
next(): voidAdvances the iterator by one. Always check isValid() after a next() to ensure have not reached the end of the iterator.
rewind(): voidRewinds the iterator cursor all the way back to first position, which would be the smallest key, or greatest key if inReverse() was called.
Any iterator prefix passed to withPrefix() will be used on rewind. The iterator is rewound by default.
getID(): IDReturns the key string of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (ID)
isValid(): booleanReturns false when the cursor is at the end of the iterator.
- (boolean)
close(): voidCloses the iterator. Any further calls to the iterator will cause an error. May be called multiple times.
getExit(): ExitReturns the current char. It will abort if the cursor has reached the end of the iterator.
Move messages used when entering or leaving a room.
leaveMsg(string)arriveMsg(string)travelMsg(string)
Room profile.
id(ID): Profile ID.name(string): Profile name.key(string): Profile key.desc(string): Profile desc.image(ID): Profile image.
new Room.ProfileIterator(iterator: i32)Constructor of the Iterator instance.
iterator(i32)
iterator(i32)
next(): voidAdvances the iterator by one. Always check isValid() after a next() to ensure have not reached the end of the iterator.
rewind(): voidRewinds the iterator cursor all the way back to first position, which would be the smallest key, or greatest key if inReverse() was called.
Any iterator prefix passed to withPrefix() will be used on rewind. The iterator is rewound by default.
getID(): IDReturns the key string of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (ID)
isValid(): booleanReturns false when the cursor is at the end of the iterator.
- (boolean)
close(): voidCloses the iterator. Any further calls to the iterator will cause an error. May be called multiple times.
getProfile(): ProfileReturns the current profile. It will abort if the cursor has reached the end of the iterator.
Detailed room information.
id(ID): Room ID.name(string): Room name.desc(string): Room description.imageId(ID): Room image ID;isDark(boolean): IsDark flags if other character can be seen or whispered to in the room.isQuiet(boolean): IsQuiet flags if a room is quiet and won't allow communication.isHome(boolean): IsHome flags if the room can be set as home by others.isTeleport(boolean): IsTeleport flags if the room can be added as a teleport node by others.isInstance(boolean): IsInstance flags if the room creates an instance.autosweep(boolean): Autosweep flags if sleepers in the room should be sent home automatically.autosweepDelay(i64): AutosweepDelay is the time in milliseconds until a sleeper is swept.customTeleportMsgs(boolean): CustomTeleportMsgs flags if the room uses custom teleport messages.overrideCharTeleportMsgs(boolean): OverrideCharTeleportMsgs flags if the custom teleport messages should override any set character teleport messages.teleport(Room.MoveMsgs): Custom teleport messages.created(i64): Created time.
Script.broadcast(topic: string, data: string | null = null): voidBroadcasts a message to all scripts listening to this script. Other room scripts in the same room listening to any message will also receive the message. The receiving script will get the message through the onMessage entry point.
To get other scripts to listen for broadcast, see Script.listen.
topic(string): Message topic. May be any kind of string.data(string | null): Additional data. Must be valid JSON.
Script.cancelPost(scheduleId: ID | null): booleanCancel a message previously scheduled with Script.post with a delay.
The post can only be canceled from the same room instance that sent it. The method returns true if the post was successfully canceled, or false if the scheduleId is either null, not sent by the script instance, or if the post was already sent.
scheduleId(ID | null): Schedule ID returned by script.Post.
- (boolean): True if the post was successfully canceled, otherwise false.
Script.getChar(charId: ID): Char | nullGets info on an existing character.
To get character description or image info use Room.getChar instead.
charId(ID): Character ID.
- (Script.Char | null): Script.Char object or null if the character is not found.
Script.listen(addrs: Array<string> | null = null): voidStarts listening for messages and requests, sent with
Script.post, Script.broadcast, and
Script.request, from any of the given addr addresses. If an
address is a non-instance room, it will also listen to posted messages
from any instance of that room.
If no addr is provided, the script will listen to posts and requests
from any source, including scripts and bots controlled by other
players, and also listen for broadcasts by scripts in the same room.
Posts from the current script does not require listening. A script can always post to itself.
To get the address of a room script, use the roomscript command. For
more info, type:
help roomscript
addrs(Array<string> | null)
Script.post(addr: string, topic: string, data: string | null = null, delay: i64 = 0): ID | nullPosts a message to another script with the address addr. The receiving
script will get the message through the onMessage entry
point.
To get the address of a room script, use the roomscript command. For
more info, type:
help roomscript
addr(string): Address of target script. If addr is "#", it will be a post to the current script instance.topic(string): Message topic. May be any kind of string.data(string | null): Additional data. Must be valid JSON.delay(i64): Delay in milliseconds.
- (ID | null): Schedule ID or null if the message was posted without delay of if the receiving script was not listening.
Script.request(addr: string, topic: string, data: string | null = null): ResponseSends a request to another script with the address addr. The receiving
script will get the request through the onRequest entry
point. The requesting script will wait and block until a response is
received, or a timeout occurs.
Errors will be returned as part of the response. The script should call Response.isError to check if an error was returned. In case of errors, calling Response.parseResult will cause the script to abort. Requests to self, or circular requests (A -> B -> A) will always return with an error.
To get the address of a room script, use the roomscript command. For
more info, type:
help roomscript
addr(string): Address of target script. If addr is "#", it will be a post to the current script instance.topic(string): Message topic. May be any kind of string.data(string | null): Additional data to be sent with the request. Must be valid JSON.
- (Response): Response to the request.
Script.unlisten(addrs: Array<string> | null = null): voidStarts listening for posted messages from any of the given addr
addresses. If an address is a non-instance room, it will also listen to
posted messages from any instance of that room.
If no addr is provided, the script will listen to posts from any
source.
To get the address of a room script, use the roomscript command. For
more info, type:
help roomscript
addrs(Array<string> | null)
Realm character.
id(string): Character ID.name(string): Character name.surname(string): Character surname.avatar(ID): Character avatar.species(string): Character species.gender(string): Character gender.state(CharState): Character state.idle(IdleLevel): Character idle status.rp(RPState): Character RP state.
Store.deleteKey<T>(key: T): voidDeletes a key and it's value from the store. If the key does not exist, this is a no-op.
key(T): Stored key.
Store.getBuffer<T>(key: T): ArrayBuffer | nullReturns the stored ArrayBuffer value for the key, or null if the key does not exist.
key(T): Stored key.
- (ArrayBuffer | null)
Store.getString<T>(key: T): string | nullReturns the stored string value for the key, or null if the key does not exist.
key(T): Stored key.
- (string | null)
Store.readOnly(): voidSets the database transaction to read-only during the script call, allowing multiple iterators to be open at the same time.
Must be called before using the store.
Store.setBuffer<T>(key: T, value: ArrayBuffer): voidAdds a key and an ArrayBuffer value to the store, or updates that key's value if it already exists.
key(T): Stored key.value(ArrayBuffer): Stored value.
Store.setString<T>(key: T, value: string): voidAdds a key and a string value to the store, or updates that key's value if it already exists.
key(T): Stored key.value(string): Stored string value.
Store.totalBytes(): i64Returns the total number of bytes used by the store for this script address.
- (i64)
Iterator is an object that iterates over a storage.
new Store.Iterator()Constructor of the Iterator instance.
withPrefix<T>(prefix: T): IteratorSets a prefix to use for calls to seek, rewind, and isValid.
Must be called before using the iterator.
prefix(T): Key prefix used in seek, rewind, and isValid.
- (Store.Iterator): This instance, allowing method chaining.
inReverse(): IteratorSets direction of iteration to be in lexiographcially reversed order.
Must be called before using the iterator.
- (Store.Iterator): This instance, allowing method chaining.
next(): voidAdvances the iterator by one. Always check isValid() after a next() to ensure have not reached the end of the iterator.
seek<T>(key: T): voidSeeks to the provided key if found. If not found, it would seek to the next smallest key greater than the provided key if iterating in the forward direction. Behavior would be reversed if iterating backwards.
Any iterator prefix passed to withPrefix() will be prepended to the key.
key(T)
rewind(): voidRewinds the iterator cursor all the way back to first position, which would be the smallest key, or greatest key if inReverse() was called.
Any iterator prefix passed to withPrefix() will be used on rewind. The iterator is rewound by default.
getKeyString(): stringReturns the key string of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (string)
getKeyBuffer(): ArrayBufferReturns the key ArrayBuffer of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (ArrayBuffer)
getValueString(): stringReturns the string value of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (string)
getValueBuffer(): ArrayBufferReturns the ArrayBuffer value of the current key-value pair. It will abort if the cursor has reached the end of the iterator.
- (ArrayBuffer)
isValid(): booleanReturns false when the cursor is at the end of the iterator.
Any iterator prefix passed to withPrefix() will be used as prefix.
- (boolean)
isValidForPrefix<T>(prefix: T | null): booleanReturns false when the cursor is at the end of the iterator, or when the current key is not prefixed by the specified prefix.
Any iterator prefix passed to withPrefix() will be prepended to the provided prefix.
prefix(T | null)
- (boolean)
close(): voidCloses the iterator. Any further calls to the iterator will cause an error. May be called multiple times.