🎯 Actions Guide
Note: This guide is being translated. Some parts may still be in Russian or incomplete.
Complete description of all available actions with their parameters and results.
📋 Table of Contents
- ai_rag_service (4 actions)
- ai_service (2 actions)
- download_service (1 actions)
- invoice_service (7 actions)
- scenario_helper (9 actions)
- scenario_processor (2 actions)
- storage_hub (4 actions)
- telegram_bot_api (5 actions)
- user_hub (8 actions)
- validator (1 actions)
⭐ — extension (additional plugin). For more information contact the developer.
ai_rag_service
Description: RAG extension for AI Service (vector search and embeddings management)
⭐ delete_embedding
Description: Delete data from vector_storage by document_id or processed_at date
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)document_id(string, optional) — Document ID to delete (all chunks); if set, other params ignoreduntil_date(string, optional) — Delete chunks with processed_at <= until_date (YYYY-MM-DD)since_date(string, optional) — Delete chunks with processed_at >= since_date (YYYY-MM-DD)metadata_filter(object, optional) — Metadata filter (JSON); e.g. chat_id, username
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error infocode(string) — Error codemessage(string) — Error message
response_data(object) — Response datadeleted_chunks_count(integer) — Number of deleted chunks
Usage Example:
# In scenario
- action: "delete_embedding"
params:
tenant_id: 123
# document_id: string (optional)
# until_date: string (optional)
# since_date: string (optional)
# metadata_filter: object (optional)📖 Additional Information
Удаление данных из vector_storage:
Способы удаления:
- По
document_id- удаляет все чанки документа (остальные параметры игнорируются) - По дате
processed_at- удаляет чанки по дате обработки - По
metadata_filter- удаляет чанки с определенными метаданными
Параметры даты:
since_date: удалить с даты (включительно)until_date: удалить до даты (включительно)- Можно указать оба параметра (диапазон)
- Формат: 'YYYY-MM-DD' или 'YYYY-MM-DD HH:MM:SS'
Примеры:
# По document_id
data:
document_id: "doc_12345"
# По дате
data:
until_date: "2024-01-01"
# Диапазон дат
data:
since_date: "2024-01-01"
until_date: "2024-12-31"
# По метаданным
data:
metadata_filter: {chat_id: 123}⭐ get_recent_chunks
Description: Get last N chunks by created_at (date-based, not vector search; sorted by created_at)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)limit_chunks(integer, optional, range: 1-200) — Number of chunks (default from search_limit_chunks); works with limit_charslimit_chars(integer, optional, min: 1) — Character limit (applied after limit_chunks)document_type(string|array, optional) — Filter by document type (string or array)document_id(string|array, optional) — Filter by document_id (string or array)until_date(string, optional) — Filter: chunks with processed_at <= until_datesince_date(string, optional) — Filter: chunks with processed_at >= since_datemetadata_filter(object, optional) — Metadata filter (JSON)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error infocode(string) — Error codemessage(string) — Error message
response_data(object) — Response datachunks(array (of object)) — Array of chunks (sorted by created_at DESC)chunks_count(integer) — Number of chunks found
Usage Example:
# In scenario
- action: "get_recent_chunks"
params:
tenant_id: 123
# limit_chunks: integer (optional)
# limit_chars: integer (optional)
# document_type: string|array (optional)
# document_id: string|array (optional)
# until_date: string (optional)
# since_date: string (optional)
# metadata_filter: object (optional)📖 Additional Information
Получение последних чанков по дате (НЕ векторный поиск):
- Возвращает последние N чанков, отсортированных по
created_at(новые первыми, для правильного порядка истории) - Полезно для получения последних сообщений или истории диалога
Параметры:
limit_chunks: количество чанков (по умолчанию 10)limit_chars: лимит по символам (работает поверхlimit_chunks)
Фильтры (комбинируются):
document_type,document_id: строка или массивsince_date,until_date: диапазон дат (формат: 'YYYY-MM-DD' или 'YYYY-MM-DD HH:MM:SS')metadata_filter: JSON объект (например,{chat_id: 123})
Примеры:
# Последние 10 чанков
data:
limit_chunks: 10
# Последние сообщения
data:
document_type: "message"
limit_chunks: 20
# Последние чанки документа
data:
document_id: "doc_123"
limit_chunks: 10
# Последние чанки за период
data:
since_date: "2024-01-01"
until_date: "2024-12-31"
limit_chunks: 50⭐ save_embedding
Description: Save text to vector_storage with chunking and embeddings; supports text-only via generate_embedding=false
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)text(string) — Text to save (cleaned and chunked)document_id(string, optional) — Unique document ID; auto-generated if omitteddocument_type(string, required, values: [knowledge,chat_history,other]) — Document type: knowledge, chat_history, otherrole(string, optional, values: [system,user,assistant]) — OpenAI message role (default user)chunk_metadata(object, optional) — Chunk metadata (JSON): chat_id, username etc.; used for filtering and in contextmodel(string, optional) — Embedding model (default from ai_client)dimensions(integer, optional) — Embedding dimensions (default 1024)chunk_size(integer, optional, range: 100-8000) — Chunk size in characters (default 1000, ~300-400 tokens, adaptively increased for tables)chunk_overlap(integer, optional, range: 0-1000) — Chunk overlap in characters (~20% of chunk_size)replace_existing(boolean, optional) — Replace existing document (default false; ALREADY_EXISTS if exists)generate_embedding(boolean, optional) — Generate embeddings for chunks (default true); false = text onlycreated_at(string, optional) — Creation date (ISO/YYYY-MM-DD); default current time- 🔑
ai_token(string, optional) — AI API key from tenant config; required if generate_embedding=true
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error code: ALREADY_EXISTS, INTERNAL_ERROR, VALIDATION_ERRORmessage(string) — Error messagedetails(array) (optional) — Error details (e.g. field validation errors)
response_data(object) — Response datadocument_id(string) — Saved document ID (provided or generated)document_type(string) — Document typechunks_count(integer) — Number of chunks createdmodel(string) (optional) — Embedding model used (if generate_embedding=true)dimensions(integer) (optional) — Embedding dimensions (if generate_embedding=true)total_tokens(integer) (optional) — Total tokens in chunks (if generate_embedding=true)text_length(integer) — Source text length (after cleaning)
Note:
- 🔑 — field that is automatically taken from tenant configuration (_config) and does not require explicit passing in params
Usage Example:
# In scenario
- action: "save_embedding"
params:
tenant_id: 123
text: "example"
# document_id: string (optional)
document_type: "example"
# role: string (optional)
# chunk_metadata: object (optional)
# model: string (optional)
# dimensions: integer (optional)
# chunk_size: integer (optional)
# chunk_overlap: integer (optional)
# replace_existing: boolean (optional)
# generate_embedding: boolean (optional)
# created_at: string (optional)
# ai_token: string (optional)📖 Additional Information
Автоматическое сохранение текста с разбиением на чанки:
- Очистка текста (лишние пробелы, невидимые символы)
- Разбиение на чанки (гибридный подход: по предложениям/абзацам → по символам)
- Генерация embeddings (параллельно, если
generate_embedding=true) - Сохранение в
vector_storage
Режимы сохранения:
generate_embedding=true(по умолчанию): с эмбеддингами для векторного поискаgenerate_embedding=false: только текст без эмбеддингов (экономит токены, не требуетai_token)
Перекрытие чанков (chunk_overlap):
- Сохраняет контекст на границах для лучшего поиска
- Рекомендуется ~20% от
chunk_size(по умолчанию 100 приchunk_size=512) - Расширяется до целых предложений при разбиении
Генерация document_id:
- Если не указан → генерируется автоматически (детерминированный)
- Seed:
{tenant_id}:{document_type}:{MD5(text)} - Повторная загрузка того же текста вернет тот же ID
Обработка существующих документов:
replace_existing=false(по умолчанию): ошибка ALREADY_EXISTS если документ существуетreplace_existing=true: старые чанки удаляются, создаются новые
Пример:
action: save_embedding
data:
text: "Длинный текст..."
document_type: "knowledge"
chunk_size: 512
chunk_overlap: 100
# Ответ:
result: success
response_data:
document_id: "doc_12345"
chunks_count: 5
total_tokens: 150⭐ search_embedding
Description: Search similar chunks by text or vector (cosine similarity)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)query_text(string, optional) — Query text (converted to embedding); use query_text or query_vectorquery_vector(array, optional) — Precomputed vector (array); use query_text or query_vectorlimit_chunks(integer, optional, range: 1-200) — Number of results (top-k); works with limit_charslimit_chars(integer, optional, min: 1) — Character limit (applied after limit_chunks)min_similarity(number, optional, range: 0.0-1.0) — Min similarity threshold (cosine)document_id(string|array, optional) — Filter by document_id (string or array)document_type(string|array, optional) — Filter by document type (string or array)until_date(string, optional) — Filter: chunks with processed_at <= until_datesince_date(string, optional) — Filter: chunks with processed_at >= since_datemetadata_filter(object, optional) — Metadata filter (JSON)model(string, optional) — Embedding model (if query_text)dimensions(integer, optional) — Embedding dimensions (if query_text)- 🔑
ai_token(string, optional) — AI API key; required if query_text set
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error infocode(string) — Error codemessage(string) — Error message
response_data(object) — Response datachunks(array (of object)) — Array of found chunkschunks_count(integer) — Number of chunks found
Note:
- 🔑 — field that is automatically taken from tenant configuration (_config) and does not require explicit passing in params
Usage Example:
# In scenario
- action: "search_embedding"
params:
tenant_id: 123
# query_text: string (optional)
# query_vector: array (optional)
# limit_chunks: integer (optional)
# limit_chars: integer (optional)
# min_similarity: number (optional)
# document_id: string|array (optional)
# document_type: string|array (optional)
# until_date: string (optional)
# since_date: string (optional)
# metadata_filter: object (optional)
# model: string (optional)
# dimensions: integer (optional)
# ai_token: string (optional)📖 Additional Information
Семантический поиск похожих чанков:
- Поиск по cosine similarity между векторами
- Использует HNSW индекс для быстрого поиска
- Результаты сортируются по убыванию similarity
Запрос (требуется одно из):
query_text: текст (генерируется embedding автоматически)query_vector: готовый вектор (не требует API ключ)
Параметры поиска:
limit_chunks: top-k результатов (по умолчанию 10)limit_chars: лимит по символам (работает поверхlimit_chunks)min_similarity: минимальный порог (0.0-1.0, по умолчанию 0.7)
Фильтры (комбинируются):
document_type,document_id: строка или массивsince_date,until_date: диапазон дат (формат: 'YYYY-MM-DD' или 'YYYY-MM-DD HH:MM:SS')metadata_filter: JSON объект (например,{chat_id: 123})
Примеры:
# Поиск по тексту
data:
query_text: "Как работает RAG?"
limit_chunks: 10
min_similarity: 0.75
# Поиск с фильтрами
data:
query_text: "Вопрос"
document_type: ["message", "document"]
since_date: "2024-01-01"
until_date: "2024-12-31"
# Поиск с лимитом по символам
data:
query_text: "Вопрос"
limit_chunks: 20
limit_chars: 5000ai_service
Description: Service for AI integration in scenarios
completion
Description: AI completion via AI
Input Parameters:
prompt(string) — User request textsystem_prompt(string, optional) — System prompt for contextmodel(string, optional) — AI model (default from settings)max_tokens(integer, optional) — Maximum tokens (default from settings)temperature(float, optional, range: 0.0-2.0) — Generation temperature (default from settings)context(string, optional) — Custom context (added to final user message in ADDITIONAL CONTEXT block with other chunks from rag_chunks)rag_chunks(array (of object), optional) — Array of RAG search chunks for building messages. Types: chat_history, knowledge, other. Format: [{content, document_type, role, processed_at, ...}]json_mode(string, optional, values: [json_object,json_schema]) — JSON mode for structured response: 'json_object' or 'json_schema'json_schema(object, optional) — JSON schema for json_schema mode (required when json_mode='json_schema')tools(array (of object), optional) — Array of tool objects (tool calling). Each item is an object: type 'function', function: { name, description, parameters }. parameters is JSON Schema for the call arguments (OpenAI-compatible format).tool_choice(string, optional) — Tool selection. String: 'none' (do not call), 'auto' (default when tools present), 'required' (must call at least one). Object: force one function — {"type": "function", "function": {"name": "function_name"}}.chunk_format(object, optional) — Chunk display format in context. Templates use $ markers. $content + chunk_metadata. Fallback: $field|fallback:value. Markers apply only to chunk data.- 🔑
ai_token(string) — AI API key from tenant config (_config.ai_token)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, error, timeouterror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details (e.g. field validation errors)
response_data(object) — Response dataresponse_completion(string) — AI completion responseprompt_tokens(integer) — Input tokens (prompt + context)completion_tokens(integer) — Output tokens (generated response)total_tokens(integer) — Total tokens (prompt + completion)model(string) — Model usedresponse_dict(object) (optional) — Parsed dict from JSON response (when using json_mode)tool_calls(array (of object)) (optional) — When using tools — array of call objects. Each item: id, type, function: { name, arguments }. arguments is a JSON string with call parameters (different keys per function); parse in scenario if needed.
Note:
- 🔑 — field that is automatically taken from tenant configuration (_config) and does not require explicit passing in params
Usage Example:
# In scenario
- action: "completion"
params:
prompt: "example"
# system_prompt: string (optional)
# model: string (optional)
# max_tokens: integer (optional)
# temperature: float (optional)
# context: string (optional)
# rag_chunks: array (optional)
# json_mode: string (optional)
# json_schema: object (optional)
# tools: array (optional)
# tool_choice: string (optional)
# chunk_format: object (optional)
ai_token: "example"📖 Additional Information
JSON режимы:
json_object: модель возвращает валидный JSON (парсится вresponse_dict)json_schema: строгая JSON схема (требуетсяjson_schemaпараметр)
Tool Calling:
tools— массив объектов (каждый: type, function.name, function.description, function.parameters по JSON Schema)- Модель решает, какие функции вызвать и с какими параметрами; вызовы возвращаются в
response_data.tool_calls tool_calls— массив объектов: id, type, function.name, function.arguments (JSON-строка); обработка и циклы — в сценарииtool_choice: строка 'none'|'auto'|'required' или объект для принудительного вызова одной функции
Формат чанков (chunk_format):
- Настройка отображения чанков из RAG через шаблоны с маркерами
$ - Доступны:
$content(обязательно) + любые поля изchunk_metadata - Поддерживается fallback:
$field|fallback:значение(если поле пустое/отсутствует) - Маркеры работают только с данными чанка (content + chunk_metadata)
- Примеры:
"[$username]: $content","[$category|fallback:Общее]: $content" - Можно задать разные шаблоны для
chat_history,knowledge,other
embedding
Description: Generate text embedding via AI
Input Parameters:
text(string) — Text for embedding generationmodel(string, optional) — Embedding model (default from ai_client.default_embedding_model)dimensions(integer, optional) — Embedding dimensions (default from ai_client). Supported for OpenAI text-embedding-3-* only- 🔑
ai_token(string) — AI API key from tenant config (_config.ai_token)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details (e.g. field validation errors)
response_data(object) — Response dataembedding(array (of number)) — Embedding vector (list of numbers)model(string) — Model useddimensions(integer) — Embedding dimensionstotal_tokens(integer) — Total tokens
Note:
- 🔑 — field that is automatically taken from tenant configuration (_config) and does not require explicit passing in params
Usage Example:
# In scenario
- action: "embedding"
params:
text: "example"
# model: string (optional)
# dimensions: integer (optional)
ai_token: "example"📖 Additional Information
Генерация векторных представлений текста (embeddings):
- Используется для RAG (Retrieval-Augmented Generation) и векторного поиска
- Возвращает массив чисел (
embedding) - векторное представление текста
Размерность (dimensions):
- По умолчанию 1024 (настраивается в
ai_client.default_embedding_dimensions) - Поддерживается не всеми моделями (для моделей без поддержки размерность фиксирована)
Пример:
action: embedding
data:
text: "Текст для векторизации"
dimensions: 1024
# Ответ:
result: success
response_data:
embedding: [0.123, -0.456, ...] # Вектор из 1024 чисел
dimensions: 1024
total_tokens: 15download_service
Description: Service for downloading files from URLs and extracting text content
⭐ download_and_extract
Description: Download file from URL and extract text content. Supports: PDF, DOCX, TXT, MD, HTML, CSV (incl. Google Sheets). Auto-detects file type via magic bytes, Content-Type or extension
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required for file isolation)url(string) — URL to download file from (direct link, Google Drive, Google Docs/Sheets, etc.)file_type(string, optional, values: [pdf,docx,txt,md,html,csv]) — File type hint (pdf, docx, txt, md, html, csv). If not set - auto-detected via magic bytes, Content-Type or extensionkeep_file(boolean, optional) — Keep downloaded file instead of auto-cleanup (default false - file deleted after extraction)max_file_size_mb(integer, optional, range: 1-500) — Max file size in MB for this specific action (overrides default setting). Checked via HEAD request before downloaddownload_timeout_seconds(integer, optional, range: 10-3600) — Download timeout in seconds for this specific action (overrides default setting)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error code: VALIDATION_ERROR, FILE_TOO_LARGE, DOWNLOAD_FAILED, UNSUPPORTED_FORMAT, EXTRACTION_FAILED, TIMEOUT, INTERNAL_ERRORmessage(string) — Error messagedetails(array) (optional) — Error details (e.g. field validation errors)
response_data(object) — Response datafile_text(string) — Extracted text from filefile_path(string) (optional) — Path to downloaded file (only if keep_file=true, otherwise null)file_metadata(object) — File metadata
Usage Example:
# In scenario
- action: "download_and_extract"
params:
tenant_id: 123
url: "example"
# file_type: string (optional)
# keep_file: boolean (optional)
# max_file_size_mb: integer (optional)
# download_timeout_seconds: integer (optional)invoice_service
Description: Service for invoices (create, manage, process payments)
cancel_invoice
Description: Cancel invoice (set is_cancelled flag)
Input Parameters:
invoice_id(integer, required, min: 1) — Invoice ID (required)
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "cancel_invoice"
params:
invoice_id: 123confirm_payment
Description: Confirm payment (answer pre_checkout_query with confirm)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDbot_id(integer, required, min: 1) — Bot IDpre_checkout_query_id(string, required, min length: 1) — Pre-checkout query ID (required)invoice_payload(string, optional, min length: 1) — Invoice ID from payload (optional, to check status before confirm)error_message(string, optional) — Error message when rejecting payment (optional; when invoice cancelled or already paid)
Output Parameters:
result(string) — Result: success (payment confirmed), failed (rejected by business logic), error (technical error)error(object) (optional) — Error structurecode(string) — Error code: INVOICE_CANCELLED, INVOICE_ALREADY_PAID (when result=failed)message(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "confirm_payment"
params:
tenant_id: 123
bot_id: 123
pre_checkout_query_id: "example"
# invoice_payload: string (optional)
# error_message: string (optional)create_invoice
Description: Create invoice in DB and send/create link
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDbot_id(integer, required, min: 1) — Bot IDtarget_user_id(integer, optional, min: 1) — User ID for invoice (optional, default from event user_id)chat_id(integer, optional) — Chat ID for sending (required for send, not for link)title(string, required, min length: 1) — Product/service title (required)description(string) — Product/service descriptionamount(integer, required, min: 1) — Star amount (required, integer)currency(string, optional) — Currency (default XTR for stars)as_link(boolean, optional) — Create as link instead of send (default false)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response datainvoice_id(integer) — Created invoice IDinvoice_message_id(integer) (optional) — Sent message ID with invoice (when as_link=false)invoice_link(string) (optional) — Invoice link (when as_link=true)
Usage Example:
# In scenario
- action: "create_invoice"
params:
tenant_id: 123
bot_id: 123
# target_user_id: integer (optional)
# chat_id: integer (optional)
title: "example"
description: "example"
amount: 123
# currency: string (optional)
# as_link: boolean (optional)get_invoice
Description: Get invoice info
Input Parameters:
invoice_id(integer, required, min: 1) — Invoice ID (required)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response datainvoice(object) — Invoice data
Usage Example:
# In scenario
- action: "get_invoice"
params:
invoice_id: 123get_user_invoices
Description: Get all user invoices
Input Parameters:
target_user_id(integer, optional, min: 1) — User ID for invoices (optional; default from event user_id)include_cancelled(boolean, optional) — Include cancelled invoices (default false)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response datainvoices(array (of object)) — Array of user invoices
Usage Example:
# In scenario
- action: "get_user_invoices"
params:
# target_user_id: integer (optional)
# include_cancelled: boolean (optional)mark_invoice_as_paid
Description: Mark invoice as paid (payment_successful event handler)
Input Parameters:
invoice_payload(string, required, min length: 1) — ID инвойса из payload события (обязательно)telegram_payment_charge_id(string, required, min length: 1) — ID платежа в Telegram (обязательно)paid_at(string, optional) — Дата оплаты (опционально, по умолчанию текущая дата)
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "mark_invoice_as_paid"
params:
invoice_payload: "example"
telegram_payment_charge_id: "example"
# paid_at: string (optional)reject_payment
Description: Reject payment (answer pre_checkout_query with reject)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDbot_id(integer, required, min: 1) — Bot IDpre_checkout_query_id(string, required, min length: 1) — Pre-checkout query ID (required)error_message(string, optional) — Error message (optional)
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "reject_payment"
params:
tenant_id: 123
bot_id: 123
pre_checkout_query_id: "example"
# error_message: string (optional)scenario_helper
Description: Helper utilities for scenario execution management
check_value_in_array
Description: Check if value exists in array
Input Parameters:
array(array) — Массив для проверкиvalue(any) — Значение для поиска в массиве
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Результат: success (найдено), not_found (не найдено), error (ошибка)error(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
response_index(integer) — Порядковый номер (индекс) первого вхождения значения в массиве (только при result: success)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "check_value_in_array"
params:
array: []
value: "value"choose_from_array
Description: Pick random items from array without repeats
Input Parameters:
array(array) — Исходный массив для выбора элементовcount(integer, required, min: 1) — Количество элементов для выбора (без повторений)seed(any, optional) — Seed для детерминированной генерации (опционально, может быть числом, строкой или другим типом)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
random_list(array) — Массив выбранных элементов (без повторений) random_seed(string) (optional) — Использованный seed (если был передан, сохраняется как есть)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "choose_from_array"
params:
array: []
count: 123
# seed: any (optional)format_data_to_text
Description: Format structured data (JSON/YAML) to text for prompts and messages
Input Parameters:
format_type(string, required, values: [list,structured]) — Тип форматирования: 'list' (простой список с шаблоном через $), 'structured' (структурированный формат с заголовками и вложенными блоками)input_data(any) — Массив объектов для форматированияtitle(string, optional) — Заголовок для списка (опционально)item_template(string, optional, min length: 1) — Шаблон элемента для формата 'list' через $ (например: '- "$id" - $description'). Обязателен при format_type: 'list'
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
formatted_text(string) — Отформатированный текст
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "format_data_to_text"
params:
format_type: "example"
input_data: "value"
# title: string (optional)
# item_template: string (optional)📖 Additional Information
Форматы:
list— простой список с шаблоном через$structured— структурированный формат:name — description, блокПараметры:с деталями
Примеры:
# Формат list
- action: "format_data_to_text"
params:
format_type: "list"
title: "Доступные намерения:"
item_template: '- "$id" - $description'
input_data: "{storage_values.ai_router.intents}"
# Результат в _cache.format_data_to_text.formatted_text:
# Доступные намерения:
# - "random_user" - Выбрать случайного пользователя
# Формат structured
- action: "format_data_to_text"
params:
format_type: "structured"
title: "Доступные действия:"
input_data: "{storage_values.ai_router.actions}"
# Результат в _cache.format_data_to_text.formatted_text:
# Доступные действия:
# call_random_user — Выбрать N пользователей из группы
# Параметры:
# - count (integer) — Количество пользователей. По умолчанию: 1Важно:
- Шаблон для
listиспользует$вместо{}для избежания конфликта с плейсхолдерами - Результат сохраняется в
_cache.format_data_to_text.formatted_text(по умолчанию) - Если указан
_namespaceв params, результат будет в_cache.{_namespace}.formatted_text
generate_array
Description: Generate array of random numbers in range (default no repeats)
Input Parameters:
min(integer) — Minimum value (inclusive)max(integer) — Maximum value (inclusive)count(integer, required, min: 1) — Количество чисел для генерацииseed(any, optional) — Seed для детерминированной генерации (опционально, может быть числом, строкой или другим типом)allow_duplicates(boolean, optional) — Разрешить повторения в массиве (по умолчанию false - без повторений)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
random_list(array (of integer)) — Массив сгенерированных чисел random_seed(string) (optional) — Использованный seed (если был передан, сохраняется как есть)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "generate_array"
params:
min: 123
max: 123
count: 123
# seed: any (optional)
# allow_duplicates: boolean (optional)generate_int
Description: Generate random integer in range
Input Parameters:
min(integer) — Minimum value (inclusive)max(integer) — Maximum value (inclusive)seed(any, optional) — Seed для детерминированной генерации (опционально, может быть числом, строкой или другим типом)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
random_value(integer) — Generated random number random_seed(string) (optional) — Использованный seed (если был передан, сохраняется как есть)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "generate_int"
params:
min: 123
max: 123
# seed: any (optional)generate_unique_id
Description: Generate unique ID via DB autoincrement (deterministic; same seed = same ID). If no seed, random UUID
Input Parameters:
seed(string, optional, min length: 1) — Seed для генерации ID. При повторном запросе с тем же seed вернется тот же ID. Если не указан, генерируется случайный UUID
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
unique_id(integer) — Уникальный ID (гарантированно уникальный, при одинаковых входных данных возвращается тот же ID)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "generate_unique_id"
params:
# seed: string (optional)modify_array
Description: Modify array: add, remove items or clear
Input Parameters:
operation(string, required, values: [add,remove,clear]) — Операция: 'add' (добавить элемент), 'remove' (удалить элемент), 'clear' (очистить массив)array(array) — Исходный массив для модификацииvalue(any, optional) — Значение для добавления или удаления (обязательно для операций 'add' и 'remove')skip_duplicates(boolean, optional) — Пропускать дубликаты при добавлении (по умолчанию true - не добавлять если элемент уже есть)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Результат: success (успешно), not_found (элемент не найден при операции remove), error (ошибка)error(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
modified_array(array) — Модифицированный массив
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "modify_array"
params:
operation: "example"
array: []
# value: any (optional)
# skip_duplicates: boolean (optional)set_cache
Description: Set temporary data in scenario cache. All params returned in response_data and go to flat _cache by default.
Input Parameters:
cache(object) — Объект с данными для установки в кэш. Все переданные параметры будут доступны в последующих шагах сценария через {_cache.ключ} (плоский доступ по умолчанию)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Все переданные параметры из объекта cache возвращаются в response_data и автоматически попадают в плоский _cache по умолчанию.*(any) — Динамические ключи из переданного объекта cache. Все ключи доступны через {_cache.имя_ключа} (плоский доступ по умолчанию)
Usage Example:
# In scenario
- action: "set_cache"
params:
cache: {}📖 Additional Information
Пример использования:
step:
- action: "set_cache"
params:
cache:
selected_user: "@username"
reason: "Случайный выбор"
metadata:
timestamp: "2024-01-15"
source: "ai_router"
- action: "send_message"
params:
text: |
Пользователь: {_cache.selected_user}
Причина: {_cache.reason}
Время: {_cache.metadata.timestamp}
Источник: {_cache.metadata.source}Важно:
- Данные должны быть переданы в ключе
cacheв params - Это позволяет явно указать, что именно нужно кэшировать
- Весь контекст сценария (user_id, chat_id, bot_id и др.) не попадет в кэш
Доступ к данным:
- Все переданные параметры доступны через плейсхолдеры
{_cache.ключ}(плоский доступ по умолчанию) - Поддерживаются вложенные структуры:
{_cache.metadata.timestamp} - Данные автоматически очищаются после завершения выполнения сценария
sleep
Description: Delay execution for given seconds
Input Parameters:
seconds(float, required, min: 0.0) — Seconds to delay (float allowed, e.g. 0.5, 22.5)
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "sleep"
params:
seconds: "value"scenario_processor
Description: Service for processing events by scenarios
execute_scenario
Description: Execute scenario or array of scenarios by name
Input Parameters:
scenario(string|array) — Scenario name (string) or array of scenario namestenant_id(integer, required, min: 1) — Tenant ID (passed from context)return_cache(boolean, optional) — Return _cache from executed scenario (default true). Only for single scenario (string), ignored for array
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response data with scenario execution resultscenario_result(string) — Scenario result: success, error, abort, break, stop_cache(object) (optional) — Cache from executed scenario (single scenario only, when return_cache=true). Data in _cache[action_name]
Usage Example:
# In scenario
- action: "execute_scenario"
params:
scenario: "value"
tenant_id: 123
# return_cache: boolean (optional)wait_for_action
Description: Wait for async action by action_id. Returns main action result AS IS
Input Parameters:
action_id(string, required, min length: 1) — Unique async action ID to wait fortimeout(integer, optional, min: 0.0) — Wait timeout in seconds (optional). On timeout returns timeout error; scenario continues; async action keeps running in background.
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result from main action on success, or wait error (timeout/error) on wait failureerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response data from main action on success; absent on wait error
Usage Example:
# In scenario
- action: "wait_for_action"
params:
action_id: "example"
# timeout: integer (optional)storage_hub
Description: Service for managing tenant storage
delete_storage
Description: Delete values or groups from storage. If key or key_pattern set - delete value, else delete group
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)group_key(string, optional) — Group key (exact match, takes priority over group_key_pattern)group_key_pattern(string, optional, min length: 1) — Pattern for group search (ILIKE, used when group_key not specified)key(string, optional) — Attribute key (exact match). If set - delete value, else delete groupkey_pattern(string, optional, min length: 1) — Pattern for key (ILIKE). If set - delete value, else delete group
Output Parameters:
result(string) — Result: success, error, not_founderror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "delete_storage"
params:
tenant_id: 123
# group_key: string (optional)
# group_key_pattern: string (optional)
# key: string (optional)
# key_pattern: string (optional)get_storage
Description: Get storage values for tenant. Supports full values, group, single value, and pattern search
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)group_key(string, optional) — Group key (exact match, takes priority over group_key_pattern)group_key_pattern(string, optional, min length: 1) — Pattern for group search (ILIKE, used when group_key not specified)key(string, optional) — Attribute key (exact match, priority over key_pattern). Only when group_key or group_key_pattern specifiedkey_pattern(string, optional, min length: 1) — Pattern for key search (ILIKE, used when key not specified). Only when group_key or group_key_pattern specifiedformat(boolean, optional) — If true, returns additional formatted_text field with YAML data
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, error, not_founderror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
storage_values(any) — Requested data. If group_key and key set - raw value. If only group_key - group structure {key: value}. If none - full structure {group_key: {key: value}} formatted_text(string) (optional) — Formatted text in YAML (returned only when format=true)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_storage"
params:
tenant_id: 123
# group_key: string (optional)
# group_key_pattern: string (optional)
# key: string (optional)
# key_pattern: string (optional)
# format: boolean (optional)get_storage_groups
Description: Get list of unique group keys for tenant. Returns group_key list only (limited by storage_groups_max_limit)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
group_keys(array (of string)) — List of unique group keys (limited by storage_groups_max_limit) is_truncated(boolean) (optional) — Flag that list was truncated (true if more groups than limit)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_storage_groups"
params:
tenant_id: 123set_storage
Description: Set storage values for tenant. Supports full structure via values or partial via group_key/key/value
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant ID (required)group_key(string, optional) — Group key (placeholder support). If set, mixed approach is usedkey(string, optional) — Value key (placeholder support). Used with group_keyvalue(any, optional) — Value to set. Used with group_key and keyvalues(object, optional) — Structure to set. If group_key set - group {key: value}, else full {group_key: {key: value}}format(boolean, optional) — If true, returns additional formatted_text field with YAML data
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
storage_values(any) — Set data. Single value returns raw value; group returns {key: value}; full returns {group_key: {key: value}} formatted_text(string) (optional) — Formatted text in YAML (returned only when format=true)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "set_storage"
params:
tenant_id: 123
# group_key: string (optional)
# key: string (optional)
# value: any (optional)
# values: object (optional)
# format: boolean (optional)telegram_bot_api
Description: Service for executing actions via Telegram Bot API
answer_callback_query
Description: Answer callback query (popup notification)
Input Parameters:
bot_id(integer, required, min: 1) — Bot IDcallback_query_id(string, required, min length: 1) — Callback query ID from Telegramtext(string, optional, max length: 200) — Notification textshow_alert(boolean, optional) — Show as alert instead of notificationcache_time(integer, optional, range: 0-3600) — Answer cache time (seconds)
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "answer_callback_query"
params:
bot_id: 123
callback_query_id: "example"
# text: string (optional)
# show_alert: boolean (optional)
# cache_time: integer (optional)build_keyboard
Description: Build keyboard from ID array using templates
Input Parameters:
items(array) — Array of IDs for button generationkeyboard_type(string, required, values: [inline,reply]) — Keyboard type (inline or reply)text_template(string, required, min length: 1) — Text template with $value$ placeholdercallback_template(string, optional, min length: 1) — Callback data template for inline (required for inline)buttons_per_row(integer, optional, range: 1-8) — Buttons per row
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Build resulterror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Keyboard datakeyboard(array) — Array of button rowskeyboard_type(string) — Keyboard typerows_count(integer) — Number of rowsbuttons_count(integer) — Number of buttons
Usage Example:
# In scenario
- action: "build_keyboard"
params:
items: []
keyboard_type: "example"
text_template: "example"
# callback_template: string (optional)
# buttons_per_row: integer (optional)delete_message
Description: Delete message by bot
Input Parameters:
bot_id(integer, required, min: 1) — Bot IDdelete_message_id(integer, optional, min: 1) — Message ID to delete
Output Parameters:
result(string) — Delete resulterror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "delete_message"
params:
bot_id: 123
# delete_message_id: integer (optional)restrict_chat_member
Description: Restrict a user in a supergroup (permission groups: messages, attachments, other, management)
Input Parameters:
bot_id(integer, required, min: 1) — Bot IDchat_id(integer|string) — Chat ID (supergroup)target_user_id(integer) — User ID to restrict (target; does not conflict with context user_id)messages(boolean, optional) — Allow text messages, contacts, locations, etc. If omitted — not sent to APIattachments(boolean, optional) — Allow audio, documents, photos, videos, video notes, voice. If omitted — not sent to APIother(boolean, optional) — Allow polls, stickers, games, inline, link previews. If omitted — not sent to APImanagement(boolean, optional) — Allow change info, invite users, pin messages, manage topics. If omitted — not sent to APIuntil_date(integer, optional, min: 0) — Unix time when restrictions are lifted; 0 or omit — forever
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "restrict_chat_member"
params:
bot_id: 123
chat_id: "value"
target_user_id: 123
# messages: boolean (optional)
# attachments: boolean (optional)
# other: boolean (optional)
# management: boolean (optional)
# until_date: integer (optional)send_message
Description: Send message by bot
Input Parameters:
bot_id(integer, required, min: 1) — Bot IDtarget_chat_id(integer|array|string, optional) — Chat ID or array of chat IDstext(string, optional) — Message textparse_mode(string, optional, values: [HTML,Markdown,MarkdownV2]) — Parse mode (HTML, Markdown, MarkdownV2)message_edit(integer|boolean|string, optional) — Message ID to edit or flagmessage_reply(integer|boolean|string, optional) — Reply to message: true (reply to current event message), integer/string (message ID)inline(array, optional) — Inline keyboardreply(array, optional) — Reply keyboardattachment(array, optional) — Attachments
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Send resulterror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response datalast_message_id(integer) — Sent message ID
Usage Example:
# In scenario
- action: "send_message"
params:
bot_id: 123
# target_chat_id: integer|array|string (optional)
# text: string (optional)
# parse_mode: string (optional)
# message_edit: integer|boolean|string (optional)
# message_reply: integer|boolean|string (optional)
# inline: array (optional)
# reply: array (optional)
# attachment: array (optional)user_hub
Description: Central service for managing user states
clear_user_state
Description: Clear user state
Input Parameters:
user_id(integer, required, min: 1) — Telegram user IDtenant_id(integer, required, min: 1) — Tenant ID
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "clear_user_state"
params:
user_id: 123
tenant_id: 123delete_user_storage
Description: Delete values from user storage
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDuser_id(integer, required, min: 1) — Telegram user IDkey(string, optional) — Key to delete (exact). If key and key_pattern both unset - delete all user recordskey_pattern(string, optional, min length: 1) — Pattern for keys to delete (ILIKE). If both unset - delete all
Output Parameters:
result(string) — Result: success, error, not_founderror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details (e.g. field validation errors)
Usage Example:
# In scenario
- action: "delete_user_storage"
params:
tenant_id: 123
user_id: 123
# key: string (optional)
# key_pattern: string (optional)get_tenant_users
Description: Get list of all user_id for tenant
Input Parameters:
tenant_id(integer) — Tenant ID
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
user_ids(array (of integer)) — Array of Telegram user IDs user_count(integer) — Number of users
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_tenant_users"
params:
tenant_id: 123get_user_state
Description: Get user state with expiry check
Input Parameters:
user_id(integer, required, min: 1) — Telegram user IDtenant_id(integer, required, min: 1) — Tenant ID
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response data- 🔀
user_state(string) (optional) — User state or None if expired/not set user_state_expired_at(string) (optional) — State expiry time (ISO) or None if not set
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_user_state"
params:
user_id: 123
tenant_id: 123get_user_storage
Description: Get user storage values. Supports full values, single key, or key_pattern search
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDuser_id(integer, required, min: 1) — Telegram user IDkey(string, optional) — Key for single value (exact match, priority over key_pattern)key_pattern(string, optional, min length: 1) — Pattern for key search (ILIKE, used when key not set)format(boolean, optional) — If true, returns formatted_text with YAML data
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, error, not_founderror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
user_storage_values(any) — Requested data. If key set - raw value. If none - full formatted_text(string) (optional) — Formatted YAML text (only when format=true)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_user_storage"
params:
tenant_id: 123
user_id: 123
# key: string (optional)
# key_pattern: string (optional)
# format: boolean (optional)get_users_by_storage_value
Description: Find users by storage key and value (e.g. users with subscription)
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDkey(string, required, min length: 1) — Storage key to searchvalue(string|integer|float|boolean|array|object) — Value to search (primitive or JSON object)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
user_ids(array (of integer)) — Array of Telegram user IDs where storage[key] == value user_count(integer) — Number of users found
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "get_users_by_storage_value"
params:
tenant_id: 123
key: "example"
value: "value"set_user_state
Description: Set user state
Input Parameters:
user_id(integer, required, min: 1) — Telegram user IDtenant_id(integer, required, min: 1) — Tenant IDstate(string, optional) — User state (None or empty to clear)expires_in_seconds(integer, optional, min: 0) — Expiry in seconds (None or 0 = forever)
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching).
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) — Response datauser_state(string) (optional) — User state or None if expired/not setuser_state_expired_at(string) (optional) — State expiry time (ISO) or None if not set
Usage Example:
# In scenario
- action: "set_user_state"
params:
user_id: 123
tenant_id: 123
# state: string (optional)
# expires_in_seconds: integer (optional)set_user_storage
Description: Set user storage. Full structure via values or partial via key/value
Input Parameters:
tenant_id(integer, required, min: 1) — Tenant IDuser_id(integer, required, min: 1) — Telegram user IDkey(string, optional) — Value key (placeholder support). If set, mixed approachvalue(any, optional) — Value to set. Used with keyvalues(object, optional) — Full structure to set {key: value}. Only when key not setformat(boolean, optional) — If true, returns formatted_text with YAML data
⚙️ Additional Parameters
_namespace(string) (optional) — Custom key for creating nesting in_cache. If specified, data is saved in_cache[_namespace]instead of flat cache. Used to control overwriting on repeated calls of the same action. Access via{_cache._namespace.field}. By default, data is merged directly into_cache(flat caching)._response_key(string) (optional) — Custom name for main result field (marked 🔀). If specified, main field will be saved in_cacheunder specified name instead of standard. Access via{_cache.{_response_key}}. Works only for actions that support renaming main field.
Output Parameters:
result(string) — Result: success, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
response_data(object) —- 🔀
user_storage_values(any) — Set data. Single value or full {key: value} structure formatted_text(string) (optional) — Formatted YAML text (only when format=true)
- 🔀
Note:
- 🔀 — field that can be renamed via
_response_keyparameter for convenient data access
Usage Example:
# In scenario
- action: "set_user_storage"
params:
tenant_id: 123
user_id: 123
# key: string (optional)
# value: any (optional)
# values: object (optional)
# format: boolean (optional)validator
Description: Service for validating conditions in scenarios
validate
Description: Validate condition and return result
Input Parameters:
condition(string, required, min length: 1) — Condition to validate (supports all condition_parser operators)
Output Parameters:
result(string) — Result: success, failed, errorerror(object) (optional) — Error structurecode(string) — Error codemessage(string) — Error messagedetails(array) (optional) — Error details
Usage Example:
# In scenario
- action: "validate"
params:
condition: "example"📖 Additional Information
Поддерживаемые операторы: ==, !=, >, <, >=, <=, in, not in, ~, !~, regex, is_null, not is_null
Плейсхолдеры:
- ✅
condition: "{_cache.storage_values.tenant_owner|exists} == True and {_cache.storage_values.tenant_owner|length} > 0" - ✅
condition: "{_cache.storage_values.tenant_id} == 137" - ✅
condition: "{_cache.storage_values.tenant_id} > 100"
Маркеры:
- ✅
condition: "$user_id > 100" - ✅
condition: "$_cache.storage_values.tenant_owner not is_null" - ✅
condition: "$event_type == 'message' and $user_id > 100"