Skip to content

Session Context Variables

The session variables property provides variable resolution and data management for the current action context. It allows plugins to store, retrieve, and manipulate data across different scopes (session-local, state-specific, database items, level configuration, etc.) using a dot-notation syntax.

The Variables Chapter describes how data is used and manipulated when creating games with the adaptor:ex editor and how the notation works.

Access: Available as session.variables in functions and plugin action functions

Type: Variables instance

Action Data Management

store(data, persistent)

Stores data for the current action that can be retrieved later.

Parameters:

  • data (*) - Data to store
  • persistent (boolean, optional) - If true, data persists even when action is retriggered

Returns: Promise<Object> - MongoDB update result

Description:

Stores data at session.state_data[state_name][action_name]. Top-level object properties are merged with existing data. If persistent=true, also stores at session.persistent_state_data[state_name][action_name].

Example:

async function runAction(payload, session) {
  // Store action data
  await session.variables.store({ counter: 1, timestamp: Date.now() })

  // Store persistent data (survives action retrigger)
  await session.variables.store({ total_runs: 5 }, true)
}

load()

Retrieves data previously stored with store().

Parameters: None

Returns: Promise<*> - Previously stored data (persistent data takes priority)

Example:

async function runAction(payload, session) {
  const previousData = await session.variables.load()
  if (previousData) {
    console.log('Last counter:', previousData.counter)
  }
}

Data Manipulation

set(variable, value, options)

Sets a variable to a new value.

Parameters:

  • variable (string) - Variable reference (e.g., 'Player.name' or '[[local_var]]')
  • value (*) - Value to set
  • options (Object, optional)
    • multiple (boolean, default: true) - Allow updating multiple documents

Returns: Promise<Object> - Update result with changed count

Description:

If variable references an item or object, you can update one or more of the fields by providing an object as value.

Example:

// Set a field in a referenced item
await session.variables.set('Player.score', 100)

// Update multiple fields
await session.variables.set('Player', { score: 100, level: 5 })

// Set local variable
await session.variables.set('[[counter]]', 42)

// Update single document only
await session.variables.set('Player.status', 'active', { multiple: false })

push(variable, value, options)

Appends a value to an array variable.

Parameters:

  • variable (string) - Variable reference to array
  • value (* or Array) - Value(s) to append
  • options (Object, optional)
    • multiple (boolean, default: true) - Allow updating multiple documents

Returns: Promise<Object> - Update result

Description:

If value is an array, elements are added individually (not as nested array).

Example:

// Add single item
await session.variables.push('Player.inventory', 'sword')

// Add multiple items
await session.variables.push('Player.inventory', ['shield', 'potion'])

add(variable, value, options)

Appends a value to an array only if it's not already present (avoids duplicates).

Parameters: Same as push()

Returns: Promise<Object> - Update result

Example:

// Add unique tag
await session.variables.add('Player.tags', 'quick')

// Won't add duplicate
await session.variables.add('Player.tags', 'quick') // No effect if already present

pull(variable, value, options)

Removes value(s) from an array variable.

Parameters:

  • variable (string) - Variable reference to array
  • value (* or Array) - Value(s) to remove
  • options (Object, optional)
    • multiple (boolean, default: true) - Allow updating multiple documents

Returns: Promise<Object> - Update result

Example:

// Remove single item
await session.variables.pull('Player.inventory', 'sword')

// Remove multiple items
await session.variables.pull('Player.inventory', ['shield', 'potion'])

update(variable, data, options)

Performs a MongoDB-style update operation on a variable.

Parameters:

  • variable (string) - Variable reference
  • data (Object) - MongoDB update query (e.g., { $inc: { score: 10 } })
  • options (Object, optional)
    • multiple (boolean, default: true) - Allow updating multiple documents

Returns: Promise<void>

Description:

Allows complex MongoDB update operations like $inc, $mul, $rename, etc.

Example:

// Increment score
await session.variables.update('Player', { $inc: { score: 10 } })

// Multiple operations
await session.variables.update('Player', {
  $inc: { score: 10 },
  $set: { last_active: new Date() },
  $push: { achievements: 'first_win' }
})

create(collection, variables, reference)

Creates a new item in a collection.

Parameters:

  • collection (string) - Collection name
  • variables (Object) - Item data (variables will be resolved)
  • reference (string, optional) - Reference name for accessing in current session

Returns: Promise<Object> - Creation result

  • created_id - ID of created item
  • created_at - Creation timestamp
  • created_by - Creator username

Description:

Variables in the variables object are automatically resolved before insertion. If a reference is provided, the new item is automatically referenced in the session.

Example:

// Create item with reference
const result = await session.variables.create(
  'players',
  {
    name: 'Bob',
    score: 0,
    level: 1
  },
  'new_player'
)

// Access created item
const newPlayer = await session.variables.get('new_player')

// Create with resolved variables
await session.variables.create(
  'game_events',
  {
    player_id: '[[Player._id]]',
    event: 'level_complete',
    timestamp: new Date()
  }
)

delete(variable, options)

Deletes a variable field or entire document.

Parameters:

  • variable (string) - Variable reference
  • options (Object, optional)
    • multiple (boolean, default: true) - Allow deleting multiple documents

Returns: Promise<Object | string> - Deletion result

Description:

  • If variable references a field: Removes the field from document(s)
  • If variable references an item: Deletes the entire document(s)

Example:

// Delete a field
await session.variables.delete('Player.temporary_data');

// Delete entire item
await session.variables.delete('Temporary_thing');

// Delete single document only
await session.variables.delete('Old_data', { multiple: false });

Data Retrieval

get(variable, return_empty)

Retrieves a single document based on variable reference.

Parameters:

  • variable (string) - Variable reference
  • return_empty (boolean, optional) - If true, returns undefined instead of throwing error when not found

Returns: Promise<Object> - First matching document

Throws: Error if no document found (unless return_empty=true)

Example:

// Get referenced item
const player = await session.variables.get('Player')
console.log('Player name:', player.name)

// Get with query
const highScorer = await session.variables.get('players.{score:{$gt:1000}}')

// Return undefined if not found
const optional = await session.variables.get('OptionalRef', true)
if (optional) {
  // Use optional data
}

getMany(variable, return_empty)

Retrieves multiple documents based on variable reference.

Parameters:

  • variable (string) - Variable reference or query
  • return_empty (boolean, optional) - If true, returns empty array instead of throwing error

Returns: Promise<Array<Object>> - Array of matching documents (sorted by reference index if applicable)

Throws: adaptor.NotFoundError if no documents found (unless return_empty=true)

Example:

// Get all referenced items
const inventory = await session.variables.getMany('inventory_items')

inventory.forEach(item => {
  console.log('Item:', item.name)
})

// Get with query
const activePlayers = await session.variables.getMany('players.{status:"active"}')

// Return empty array if none found
const optional = await session.variables.getMany('OptionalItems', true)

getItem(variable)

Retrieves the class instance (not just document) for a variable.

Parameters:

  • variable (string) - Variable reference

Returns: Promise<Object> - Plugin item instance, Session instance, or Game instance

Description:

Returns actual class instances for:

  • Plugin items (PluginItem instances)
  • Sessions (Session instances)
  • Game (Game instance)
  • Data items (uses topic's queryItem() method)

Example:

// Get session instance
const otherSession = await session.variables.getItem('sessions.session_123')
await otherSession.quit()

// Get plugin item instance
const telegram = await session.variables.getItem('telegram.client.MyClient')
await telegram.sendMessage('Hello')

// Get game instance
const game = await session.variables.getItem('game')
console.log('Active plugins:', game.setup.plugins)

getValue(path)

Resolves a dot-notation path to its value.

Parameters:

  • path (string) - Dot-notation path (without [[]])

Returns: Promise<*> - Resolved value

Description:

Core resolution method. Handles:

  • Variable references (documents or fields)
  • Function calls (functions.name(args))

Example:

// Get field value
const score = await session.variables.getValue('Player.score')

// Call function
const random = await session.variables.getValue('functions.random(1,100)')

// Nested access
const firstItem = await session.variables.getValue('Player.inventory.0.name')

Variable Resolution

review(str)

Replaces [[variable]] placeholders in a string with their values.

Parameters:

  • str (string) - String containing [[variable]] placeholders

Returns: Promise<string | *> - String with variables replaced, or direct value if entire string was a single variable

Description:

If the entire string is a single variable reference (e.g., '[[Player.score]]'), returns the value in its original type (not stringified).

Example:

const message = await session.variables.review(
  'Hello [[Player.name]], your score is [[Player.score]]'
)
// Returns: "Hello Alice, your score is 100"

// Single variable returns original type
const score = await session.variables.review('[[Player.score]]')
// Returns: 100 (number, not string)

// Works with functions
const greeting = await session.variables.review(
  'Random number: [[functions.random(1,10)]]'
)

findAndReplace(element, parseJSON)

Recursively finds and replaces variables in strings, arrays, or objects.

Parameters:

  • element (string | Array | Object) - Element to process
  • parseJSON (boolean, optional) - Try to parse strings starting with { as JSON

Returns: Promise<*> - Element with all variables replaced

Description: Walks through nested structures and replaces all [[variable]] references.

Example:

// Object with variables
const data = {
  greeting: 'Hello [[Player.name]]',
  stats: {
    score: '[[Player.score]]',
    level: '[[Player.level]]'
  }
}

const resolved = await session.variables.findAndReplace(data, true)
// Returns: {
//   greeting: 'Hello Alice',
//   stats: { score: 100, level: 5 }
// }

// Array
const messages = [
  'Player: [[Player.name]]',
  'Score: [[Player.score]]'
]
const resolvedArray = await session.variables.findAndReplace(messages)

Utility Methods

getReference(path)

Parses a variable path into a database reference.

Parameters:

  • path (string) - Dot-notation path (without [[]])

Returns: VariableReference - Reference object

  • collection (string) - Collection name
  • topic (string) - Topic name
  • query (Object) - MongoDB query
  • field (string, optional) - Field path within document
  • source (string) - Descriptive source name

Example:

const ref = session.variables.getReference('Player.score')
// Returns: {
//   collection: 'players',
//   topic: 'players',
//   query: { sessions: { $elemMatch: { _id: sessionId, reference: 'Player' } } },
//   field: 'score',
//   source: 'Player'
// }

getVariableReference(variable)

Gets a variable reference, handling [[]] encapsulation and nested variables.

Parameters:

  • variable (string) - Variable with or without [[]]

Returns: Promise<VariableReference> - Reference object with variable field added

Description:

More flexible than getReference():

  • Removes outer [[]] if present
  • Resolves nested variables using review()
  • Adds original variable string to result

Example:

// All of these work:
const ref1 = await session.variables.getVariableReference('Player.score')
const ref2 = await session.variables.getVariableReference('[[Player.score]]')
const ref3 = await session.variables.getVariableReference('Player.[[field_name]]')

parseQuery(query) (static)

Parses a query string into a MongoDB query object.

Parameters:

  • query (string | Object) - Query string or object

Returns: Object - MongoDB query object

Description:

  • If string contains {} or : → Parses as JSON5
  • If plain string → Returns { name: query }
  • Converts regex notation /pattern/flags to MongoDB regex format

Example:

// Plain string
Variables.parseQuery('Alice')
// Returns: { name: 'Alice' }

// JSON5 string
Variables.parseQuery("{score: 30, status: 'active'}")
// Returns: { score: 30, status: 'active' }

// With regex
Variables.parseQuery("{name: /^A/i}")
// Returns: { name: { $regex: '^A', $options: 'i' } }

parseJSON(json_string, force_json) (static)

Parses JSON5 strings to JavaScript objects.

Parameters:

  • json_string (string) - JSON string to parse
  • force_json (boolean, optional) - Add {} if missing and parse anything with :

Returns: Object | * - Parsed object or original value

Description:

Uses JSON5 for more lenient parsing (allows trailing commas, unquoted keys, etc.).

Throws: adaptor.InvalidError if there is json style but it is invalid JSON5

Example:

// Standard JSON5
const obj = Variables.parseJSON("{name: 'Alice', score: 100}")

// Force mode
const obj2 = Variables.parseJSON("name: 'Alice', score: 100", true)
// Adds {} automatically

// Non-JSON returns as-is
const str = Variables.parseJSON('plain string')
// Returns: 'plain string'

getPath(obj, path)

Accesses nested object properties using dot notation.

Parameters:

  • obj (Object) - Object to traverse
  • path (string) - Dot-notation path

Returns: * | undefined - Value at path or undefined

Example:

const data = {
  user: { profile: { name: 'Alice' } }
}

const name = session.variables.getPath(data, 'user.profile.name')
// Returns: 'Alice'