Baza wiedzy GetMyBot

Formulas

Calculate a total or discount, or choose an answer based on a condition. When to use a formula in text and when to use the Compute action.

Na tej stronie

Formulas let your bot calculate and choose values. For example, if the price is 500 and the quantity is 3, {{= price * qty}} produces 1500. Save price and qty in customer parameters or the reaction's temporary data first.

For a simple calculation, write an expression in the message. To work with lists, dates, or functions with Russian names, add the Compute action. GetMyBot has two formula languages, with different syntax:

  • Expressions: a short language for arithmetic, comparisons, and simple strings. It works in {{= expression}} directly in text, in the "Formula" mode of the "Compute" action, and in decision-table conditions.
  • Advanced formula: a spreadsheet-style language for lists, JSON data, dates, hashes (checksums of text), LAMBDA, and Russian function names. It works in the "Advanced formula" mode of the "Compute" action, in answer validation by formula, and in the tester.

Where formulas work

WhereLanguage
{{= expression}} in message textexpressions
"Compute", "Formula" mode (expr)expressions
"Compute", "Decision table" mode (rules)expressions in "when" conditions; "then" and the default value are plain text with {{...}} substitutions
"Compute", "Advanced formula" mode (formula)advanced formula
Answer validation "Matches formula"advanced formula
Formula tester (test_formula)advanced formula

The "Compute" action

The action has three modes, and exactly one is used per action:

  • Formula (expr): a single expression.
  • Decision table (rules + default): a list of "when → then" rules. The value of the first rule whose condition is true is returned, otherwise the default value.
  • Advanced formula (formula): a formula in the full language.

Choose where to save the result: in the reaction's temporary data, ctx ("Save to ctx", save_to_ctx), or in the customer's profile ("Save to parameter", save_to_param). You can choose both, but at least one is required. For example, a result saved under discount in ctx is available as {{ctx.discount}}.

Limits: an expression, rule condition, or rule value can take up to 4096 bytes; an advanced formula up to 16384 bytes; and a decision table up to 64 rules. Length is measured in bytes: a Cyrillic letter takes 2 bytes.

Example action parameters with an advanced formula:

{"type":"compute","params":{"formula":"IF({total} > 1000; \"wholesale\"; \"retail\")","save_to_ctx":"segment"}}

Expressions

Syntax

  • Operators: arithmetic + - * / %, comparisons == != < > <= >=, logic && || !, ternary condition ? yes : no, parentheses ( ).
  • Values written in the formula: numbers (42, 3.14), quoted text ("hello" or 'hello'), and Boolean values (true, false).
  • Data: a name is written without braces and is looked up in subscriber parameters and ctx: price * qty, ctx.total, param.total. An unknown name yields an empty string.
  • Function call: name(argument1, argument2), arguments separated by commas.

Functions

Only these, and only in lowercase: len, upper, lower, trim, concat, round, floor, ceil, abs, min, max. min and max take exactly two arguments, concat takes any number. len and LEN in an advanced formula count characters the way a reader sees them: an accented letter, a flag or an emoji built from several code points (for example, the family 👨‍👩‍👧‍👦) is one character.

Expressions have no Russian aliases. If {{= }} contains an unknown function, the construct stays in the text unchanged.

Advanced formula

Advanced formula syntax

  • Arguments are separated by semicolons: IF({total} > 1000; "wholesale"; "retail").
  • Operators: arithmetic + - * /, string concatenation &, comparisons = != <> < > <= >= (equality is a single =). Logic is done with the AND, OR, and NOT functions.
  • Strings go in double or single quotes. "" inside a string is not an escaped quote: if you need a quote inside the text (for example, in an HTML attribute), use the other kind of quotes: "<a href='tg://user?id=" & r.user_id & "'>profile</a>".
  • Data is substituted in single braces: {key} is a value from ctx (and {text} or {answer} is the incoming message text), {user:key} is a subscriber parameter, {global:key} is a bot-wide global parameter.
  • LAMBDA: LAMBDA(r; expression) defines how to process each list item for FILTER, FOREACH, ARRAYFIND, and REDUCE. JSON object fields are read with a dot: r.user_id.
  • The result is converted to text. Store a list with TOJSON and read it back in the next formula with FROMJSON.
  • Function names are case-insensitive and understand Russian aliases.

Advanced formula functions

Names below use their canonical English form. A Russian alias appears in parentheses where available. Names are case-insensitive. These functions are available only in advanced formulas.

Math

SUM (СУММ), AVERAGE (СРЗНАЧ), MAX (МАКС), MIN (МИН), MOD (ОСТАТ), POW (СТЕПЕНЬ), SQRT (КОРЕНЬ), PI (ПИ), ROUND (ОКРУГЛ), CEIL (ОКРВВЕРХ), FLOOR (ОКРВНИЗ), TRUNC (ОТБР), ABS, RANDBETWEEN (СЛУЧМЕЖДУ).

Text

LEN (ДЛСТР), LEFT (ЛЕВСИМВ), RIGHT (ПРАВСИМВ), MID (ПСТР), LOWER (СТРОЧН), UPPER (ПРОПИСН), UPPERFIRST (ПРОПИСНПЕРВ), REPEAT (ПОВТОР), CONCAT (СЦЕПИТЬ), SUBSTITUTE (ПОДСТАВИТЬ), FIND (НАЙТИ), SEARCH (ПОИСК), FIELD (ПОЛЕ), TRIM, LTRIM, RTRIM, PADLEFT, PADRIGHT, SPLIT, JOIN, STARTSWITH, ENDSWITH, CONTAINS, NL.

Logic

IF (ЕСЛИ), AND (И), OR (ИЛИ), NOT (НЕ), EMPTY, ISNUMBER (ЕЧИСЛО), COALESCE.

Lists

SORT, RSORT, UNIQUE, FILTER, FOREACH, REDUCE, INDEX, SLICE, COUNTA (СЧЁТЗ), COUNTUNIQUE, ARRAYADD, ARRAYREMOVE, ARRAYREPLACE, ARRAYFIND, PAIRUP (СОСТАВИТЬПАРЫ).

PAIRUP(items; idField; seed [; tagsField]) groups participants into pairs for "random coffee". If the participant count is odd, one group has three people. The function tries to put people with shared tags ("|a|b|" string or array) in different groups. With the same input data and seed, it produces the same groups. Limits: up to 10 000 participants and 64 tags per participant (see Platform limits). For very large lists with many shared tags, avoiding every overlap may be impossible, but everyone is still grouped. The "Find records" action can read up to 10 000 rows at once, and an advanced formula result can take up to 4 MB.

Date and time

TODAY (СЕГОДНЯ), NOW (ТДАТА), DATEADD, DATESUB, DATEDIF (РАЗНДАТ), DATEFORMAT, DATEVALUE, WEEKDAY (ДЕНЬНЕД).

JSON

TOJSON, FROMJSON, JSONPATH, JP, JSONOBJECT, JSONARRAY, KEYS, VALUES.

Cryptography and encoding

HASH (ХЭШ), TOBASE64, FROMBASE64, FROMJWT, FROMJWK.

Parameters

PARAMID, PARAMREPLACE, PARAMREMOVE.

Examples

Expressions in text:

  • Order total: {{= price * qty}}.
  • A third of the total, rounded: {{= round(total / 3)}}.
  • Condition: {{= param.total > 1000 ? "wholesale" : "retail"}}.
  • String assembly: {{= concat("Order #", ctx.order_id)}}.

Advanced formula in the "Compute" action:

  • 10% discount: ROUND({user:total} * 0.9).
  • Size of a list from ctx: COUNTA(FROMJSON({items})).
  • A stable pseudo-random order of the records that the "Find records" action put into ctx under the rows key: the order stays the same between runs until you change the "salt".
{"type":"compute","params":{"formula":"TOJSON(SORT(FOREACH(FROMJSON({rows}); LAMBDA(r; HASH(\"sha256\"; r.user_id & \"-salt\") & \"|\" & r.user_id))))","save_to_ctx":"order"}}

Answer validation "Matches formula": the formula returns the error text, and an empty result means the answer is accepted. For example, IF(ISNUMBER({answer}); ""; "Enter a number").

Formula tester

The tester checks an advanced formula and returns the result or a syntax error without saving anything:

  • in the editor: in the "Matches formula" answer-validation block, enter a sample in the "Sample answer" field and click "Test";
  • via the API: POST /api/bots/{botID}/reactions/test-formula with the body {"formula": "…", "sample_text": "…"};
  • via MCP: the test_formula tool with the bot_id, formula, and sample fields.

Response: ok (the formula evaluated), result, error, and matches (true when the result is empty, i.e. the answer would pass validation).

The formula is evaluated in an empty context: ctx, subscriber parameters, and global parameters are empty, so {key} and {user:key} yield an empty string. Only the sample text is available: {text}, {answer}, or {received_message}. Expressions ({{= }}, the "Formula" mode, decision tables) are not checked by the tester.

What's next