Messaging API

The Messaging API enables communication between different scripts running in the same story. This allows scripts to coordinate their behavior or share data.

Message Types

Scripts can send two types of messages:

  • Direct messages: Sent to a specific script by its ID
  • Broadcast messages: Sent to all scripts that are listening

Sending Messages

Sending to a Specific Script

To send a message to a specific script, use the api.v1.messaging.send function with the target script’s ID:

await api.v1.messaging.send('target-script-id', {
  type: 'greeting',
  text: 'Hello from another script!'
});

The message can be any serializable object. Complex objects with functions or circular references cannot be sent.

Broadcasting to All Scripts

To send a message to all listening scripts, use the api.v1.messaging.broadcast function:

await api.v1.messaging.broadcast({
  type: 'notification',
  event: 'generation-complete',
  timestamp: Date.now()
});

All scripts that have registered a message handler will receive broadcast messages.

Receiving Messages

Registering a Message Handler

To receive messages, register a handler using the api.v1.messaging.onMessage function:

let unsubscribe = api.v1.messaging.onMessage((message) => {
  api.v1.log(`Received message from ${message.fromScriptId}: ${JSON.stringify(message)}`);
  
  if (message.data.type === 'greeting') {
    api.v1.log(`Greeting message: ${message.data.text}`);
  }
});

The handler function receives a message object containing the message data, the sender’s script ID, and other metadata.

Unsubscribing from Messages

The onMessage function returns an subscription index that can be used to unsubscribe from messages later:

let unsubId = await api.v1.messaging.onMessage((message) => {
  // Handle message
});

// Later, when you want to stop receiving messages:
api.v1.messaging.unsubscribe(unsubId)

Getting Script IDs

To send messages to specific scripts, you need to know their IDs. Each script can access its own ID through api.v1.script.id:

api.v1.log(`My script ID: ${api.v1.script.id}`);

Hard-coding script IDs is not recommended, as they may change. Instead, broadcast messages can be used to discover other scripts dynamically.

See Also