.top-button {
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/baseline_keyboard_arrow_up_white_18dp.png) !important;
		background-position: center;
		background-color: #47a7f5 !important;
		background-repeat: no-repeat;
		box-shadow: -1px 1.5px 3px #999;
		color: #47a7f5 !important;
		border-radius:50px !important;
        position: fixed;
        bottom: 45px;
        left: 93.5%;
        width: 50px;
		height: 50px !important;
        font-size: 12px !important;
        padding: 14.5px !important;
		z-index: 2;
}
.top-button:hover{
		background-color: #65b9ff !important;
        color: #65b9ff !important;
}
.page-header{
		background-color: #232838;
	    background-repeat: no-repeat;
	    background-position: center;
		width: auto;
    	height: 100px;
		background-image: url(https://confluence.twin24.ai/download/attachments/23986188/logo_twin-02.png);
		background-size: 10em;
        color: #fff;
        font-size: 20px;
        padding: 20px;
}
.page-footer{
		background-color: #232838;
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/decorated-pattern-dark.png);
		width: auto;
    	height: 10px;
        color: #fff;
		text-align: end;
    	font: small-caption;
    	padding-inline-end: 30px;
    	padding-top: 200px;
    	padding-bottom: 30px;
}
.page-headline{
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/Solid256dot8_2changed.png);
    	background-repeat: no-repeat;
    	background-position-x: -227px;
    	background-position-y: center;
    	padding: 20px;
		background-color: #007bff;
		width: auto;
    	height: 10px;
        color: #fff;
		text-align: center;
    	font: caption;
    	font-weight: 600;
}
.tabs-menu{
    	padding-left: 85% !important;
}

На этой странице:

Для тестирования сценариев, содержащих BPL-операции, необходимо использовать веб-виджет или интеграцию с каким-либо мессенджером, так как данные операции не работают в тестовом чате внутри редактора.

Как создать тестовый виджет: Создание тестового виджета

Функции общего назначения

del(varName string)

Назначение: удаление локальной или модульной переменной.

Аргументы:

  1. varName – название переменной в виде строки. Может начинаться с префикса области видимости переменной. Если префикс опущен то считается, что переменная локальная.

Возвращаемое значение: отсутствует.

$localVar = 123
#moduleVar = true
del("$localVar")   // Удаляет локальную переменную $localVar
del("localVar")    // Тоже самое что и del("$localVar")
del("#moduleVar")  // Удаляет переменную с областью видимости в пределах модуля 

setClientTimezoneOffset(offset int)

Назначение: изменяет текущее смещение временной зоны собеседника бота.

Аргументы:

  1. offset – смещение временной зоны в минутах.

Возвращаемое значение: отсутствует.

Примечание: вызов этой функции также приведёт к изменению значений системных переменных now, today и time согласно новой временной зоне.

setClientTimezoneOffset(-1800)

asBool(obj any) bool

Назначение: преобразует аргумент к булеву значению.

Аргументы:

  1. obj любое значение для преобразования.

Возвращаемое значение: булево значение.

Примечание: в BPL все значения могут быть преобразованы к булеву типу.

$bool = asBool(nil) // $bool содержит false
$bool = asBool("")  // $bool содержит false
$bool = asBool(0)   // $bool содержит false
$bool = asBool([])  // $bool содержит true
$bool = asBool(123) // $bool содержит true

asString(obj any) string

Назначение: преобразует аргумент к строковому значению.

Аргументы:

  1. obj любое значение для преобразования.

Возвращаемое значение: строковое значение.

Примечание: в BPL все значения могут быть преобразованы к строковому типу.

$str = asString(123)  // $str равно "123"
$str = asString(1.23) // $str равно "1.23"
$str = asString(true) // $str равно "true"
$str = asString({1: "a b c", 2: 0.5}) // $str равно "{1: "a b c", 2: 0.5}"

asInt(obj any) int

Назначение: преобразует аргумент к целочисленному значению.

Аргументы:

  1. obj любое значение для преобразования.

Возвращаемое значение: целочисленное значение, 0 в случае невозможности преобразования.

$int = asInt(5.67)  // $int равно 5
$int = asInt("123") // $int равно 123
$int = asInt(true)  // $int равно 1
$int = asInt(nil)   // $int равно 0
$int = asInt("abc") // $int равно 0

asFloat(obj any) float

Назначение: преобразует аргумент к вещественному числу.

Аргументы:

  1. obj любое значение для преобразования.

Возвращаемое значение: вещественное число, 0 в случае невозможности преобразования.

$float = asFloat("5.67") // $float равно 5.67
$float = asFloat(123)    // $float равно 123.0
$float = asfloat(true)   // $float равно 1.0
$float = asfloat(nil)    // $float равно 0.0
$float = asFloat("abc")  // $float равно 0.0

Математические функции

math.pos(num mixed) number

Назначение: фактически преобразует аргумент к числу. Эквивалент унарной операции "+".

Аргументы:

  1. num – произвольное значение, которое будет преобразовано к числу.

Возвращаемое значение: число.

$a = math.pos(true)  // $a будет равно 1
$a = math.pos(false) // $a будет равно 0
$a = math.pos(nil)   // $a будет равно 0
$a = +true           // $a будет равно 1, то же, что и math.pos(true)

math.neg(num number) number

Назначение: меняет знак числа. Эквивалент унарной операции "-".

Аргументы:

  1. num – произвольное число, у которого изменится знак на противоположный.

Возвращаемое значение: число со знаком обратному исходному.

$a = math.neg(-1) // $a будет равно 1
$a = math.neg(1)  // $a будет равно -1
$a = math.neg(0)  // $a будет равно 0
$a = -(-10)       // $a будет равно 10, то же, что и math.neg(-10)

math.inv(num number) number

Назначение: инверсия бит числа. Эквивалент унарной операции "~".

Аргументы:

  1. num – произвольное число, у которого инвертируются биты.

Возвращаемое значение: инвертированное число.

$a = math.inv(5) // $a равно -6
$a = ~5          // то же, что и предыдущая строка

math.not(num number) bool

Назначение: логическое отрицание числа. Эквивалент унарной операции "!".

Аргументы:

  1. num – произвольное число.

Возвращаемое значение: true, если num не равно 0 и false в противном случае.

$a = math.not(5) // $a равно false
$a = math.not(0) // $a равно true
$a = !0          // то же, что и предыдущая строка

math.add(num1 number, num2 number, precision int = 12) number

Назначение: сложение чисел. Эквивалент бинарной операции "+".

Аргументы:

  1. num1 – первое слагаемое.
  2. num2 – второе слагаемое.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: сумма чисел.

$a = math.add(1.5, 3.5)         // $a равно 5
$a = 1.5 + 3.5                  // то же, что и предыдущая строка
$a = math.add(1.000006, 2.1, 5) // $a равно 3.10001

math.sub(num1 number, num2 number, precision int = 12) number

Назначение: разность чисел. Эквивалент бинарной операции "-".

Аргументы:

  1. num1 – уменьшаемое.
  2. num2 – вычитаемое.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: разность чисел.

$a = math.sub(1.5, 3.5)         // $a равно -2
$a = 1.5 - 3.5                  // то же, что и предыдущая строка
$a = math.sub(2.100006, 1.1, 5) // $a равно 1.00001

math.mul(num1 number, num2 number, precision int = 12) number

Назначение: произведение чисел. Эквивалент бинарной операции "*".

Аргументы:

  1. num1 – первый множитель.
  2. num2 – второй множитель.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: произведение чисел.

$a = math.mul(1.5, 3.5)         // $a равно 5.25
$a = 1.5 * 3.5                  // то же, что и предыдущая строка
$a = math.mul(1.2345, 1.234, 5) // $a равно 1.52337

math.div(num1 number, num2 number, precision int = 12) number

Назначение: частное чисел. Эквивалент бинарной операции "/".

Аргументы:

  1. num1 – делимое.
  2. num2 – делитель.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: частное чисел.

$a = math.div(1.5, 3.5) // $a равно 0.428571428571
$a = 1.5 / 3.5          // то же, что и предыдущая строка
$a = math.div(1, 3, 5)  // $a равно 0.33333

math.idiv(num1 number, num2 number) int

Назначение: целочисленное деление чисел. Эквивалент бинарной операции "\".

Аргументы:

  1. num1 – делимое.
  2. num2 – делитель.

Возвращаемое значение: целая часть частного чисел.

$a = math.idiv(2.5, 0.3) // $a равно 8
$a = 2.5 \ 0.3           // то же, что и предыдущая строка

math.mod(num1 number, num2 number, precision int = 12) number

Назначение: остаток от деления двух чисел. Эквивалент бинарной операции "%".

Аргументы:

  1. num1 – делимое.
  2. num2 – делитель.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: остаток от деления.

$a = math.mod(3.5, 1.5)    // $a равно 0.5
$a = 3.5 % 1.5             // то же, что и предыдущая строка
$a = math.mod(1/3, 2/7, 5) // $a равно 0.04762

math.pow(base number, power number, precision int = 12) number

Назначение: возведение числа base в степень power. Эквивалент бинарной операции "**".

Аргументы:

  1. base – основание.
  2. power – степень.
  3. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: результат возведения в степень.

$a = math.pow(1.5, 3.5)    // $a равно 4.133513940947
$a = 1.5 ** 3.5            // то же, что и предыдущая строка
$a = math.pow(1.3, 7.1, 5) // $a равно 0.44166

math.sqrt(num number, precision int = 12) number

Назначение: извлечение квадратного корня.

Аргументы:

  1. num – число, из которого извлекается корень.
  2. precision – точность вычислений, количество цифр после запятой. Значение по умолчанию 12, максимальное – 14.

Возвращаемое значение: квадратный корень либо ошибка, если число отрицательное.

$a = math.sqrt(3.14)   // $a равно 1.772004514667
$a = math.sqrt(1.7, 5) // $a равно 0.30384

math.round(num number, precision int) number

Назначение: округление числа до требуемого знака после запятой.

Аргументы:

  1. num – число для округления.
  2. precision – точность округления, количество цифр после запятой. Максимальное значение – 14.

Возвращаемое значение: округлённое с заданной точностью число.

$a = math.round(3.14159265358979323846264338327950288419716, 17) // $a равно 3.1415926535898
$a = math.round(3.14159265358979323846264338327950288419716, 2)  // $a равно 3.14
$a = math.round(3.14159265358979323846264338327950288419716, 0)  // $a равно 3

math.rand(min int, max int) int

Назначение: генерация псевдослучайного числа в диапазоне от min до max включительно.

Аргументы:

  1. min - минимальное значение числа.
  2. max - максимальное значение числа.

Возвращаемое значение: число в диапазоне от min до max.

$r = math.rand(-10, 10)

Функции для работы со строками

str.len(str string) int

Назначение: определение длины строки в символах.

Аргументы:

  1. str – строка, длину которой необходимо определить.

Возвращаемое значение: целое число, равное количеству символов в строке.

$str = "Какая-то строка"
$len = str.len($str) // $len будет содержать 15

str.lower(str string) string

Назначение: преобразование символов строки в нижний регистр.

Аргументы:

  1. str – строка, которую необходимо преобразовать.

Возвращаемое значение: строка, все символы которой находятся в нижнем регистре.

$str = "СтРоКа"
$lower = str.lower($str) // $lower будет содержать "строка" 

str.upper(str string) string

Назначение: преобразование символов строки в верхний регистр.

Аргументы:

  1. str – строка, которую необходимо преобразовать.

Возвращаемое значение: строка, все символы которой находятся в верхнем регистре.

$str = "СтРоКа"
$upper = str.upper($str) // $lower будет содержать "СТРОКА" 

str.ucfirst(str string) string

Назначение: преобразование первого символа строки в верхний регистр.

Аргументы:

  1. str – строка, первый символ которой необходимо преобразовать.

Возвращаемое значение: строка, в которой первый символ записан в верхнем регистре.

$str = str.ucfirst("строка") // $str будет содержать "Строка" 

str.lcfirst(str string) string

Назначение: преобразование первого символа строки в нижний регистр.

Аргументы:

  1. str – строка, первый символ которой необходимо преобразовать.

Возвращаемое значение: строка, в которой первый символ записан в нижнем регистре.

$str = str.ucfirst("Строка") // $str будет содержать "строка" 

str.letter(str string, index int) string

Назначение: получение указанного символа строки.

Аргументы:

  1. str – строка, символ которой требуется получить.
  2. index – целое число, определяющее позицию символа в строке, начиная с 0. Если это число отрицательное, то отсчёт начинается с конца строки.

Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.

$str = "Слово"
$firstLetter = str.letter($str, 0)  // Первая буква
$lastLetter = str.letter($str, -1)  // Последняя буква

str.first(str string, index int = 0) string

Назначение: получение указанного символа строки, начиная с начала строки.

Аргументы:

  1. str – строка, символ которой требуется получить.
  2. index – целое число, определяющее позицию символа с начала строки, начиная с 0. При этом знак числа игнорируется. Значение по умолчанию – 0 (первый символ).

Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.

$str = "Слово"
$firstLetter = str.first($str)      // Первая буква
$secondLetter = str.first($str, 1)  // Вторая буква

str.last(str string, index int = 0) string

Назначение: получение указанного символа строки, начиная с конца строки.

Аргументы:

  1. str – строка, символ которой требуется получить.
  2. index – целое число, определяющее позицию символа с конца строки, начиная с 0. При этом знак числа игнорируется. Значение по умолчанию – 0 (последний символ).

Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.

$str = "Слово"
$lastLetter = str.last($str)       // Последняя буква
$penultLetter = str.last($str, 1)  // Предпоследняя буква

str.concat(str1 string, str2 string) string

Назначение: объединяет две строки в одну.

Аргументы:

  1. str1 – строка, которая объединяется.
  2. str2 – строка, с которой объединяются.

Возвращаемое значение: новая строка, состоящая из первой строки, справа от которой добавлена вторая строка.

$str1 = "один"
$str2 = "два"
$str = str.concat($str1, $str2) // $str будет содержать "одиндва" 

str.sub(str string, offset int, length int = nil) string

Назначение: возвращает подстроку строки str, начинающейся с offset символа по счету и длиной length символов.

Аргументы:

  1. str – исходная строка.
  2. offset – если offset неотрицательный, то возвращаемая подстрока начинается с позиции offset от начала строки, считая от нуля.
    Если offset отрицательный, то возвращаемая подстрока начинается с позиции, отстоящей на offset символов от конца строки str.
    Если str меньше offset символов, то будет возвращена пустая строка.
  3. length – если length положительный, то возвращаемая строка будет не длиннее length символов, начиная с параметра offset (в зависимости от длины string).
    Если length отрицательный, то будет отброшено указанное этим аргументом число символов с конца строки string (после того как будет вычислена стартовая позиция, если offset отрицательный). Если при этом позиция начала подстроки, определяемая аргументом offset, находится в отброшенной части строки или за ней, то возвращается пустая строка. 
    Если параметр length задан и равен 0, то будет возвращена пустая строка.
    Если параметр length опущен или nil, то будет возвращена подстрока, начинающаяся с позиции, указанной параметром offset и длящейся до конца строки.

Возвращаемое значение: часть str или пустая строка.

$sub = str.sub("abcdef", 1)      // $sub равен bcdef
$sub = str.sub("abcdef", 1, 3)   // $sub равен bcd
$sub = str.sub("abcdef", 0, 4)   // $sub равен abcd
$sub = str.sub("abcdef", 0, 8)   // $sub равен abcdef
$sub = str.sub("abcdef", -1, 1)  // $sub равен f
$sub = str.sub("abcdef", -1)     // $sub равен f
$sub = str.sub("abcdef", -2)     // $sub равен ef
$sub = str.sub("abcdef", -3, 1)  // $sub равен d
$sub = str.sub("abcdef", 0, -1)  // $sub равен abcde
$sub = str.sub("abcdef", 2, -1)  // $sub равен cde
$sub = str.sub("abcdef", 4, -4)  // $sub равен пустой строке
$sub = str.sub("abcdef", -3, -1) // $sub равен de

str.join(arr Collection, separator string = "") string

Назначение: объединяет элементы коллекции (кортежа, списка или ассоциативного массива) в строку.

Аргументы:

  1. arr – коллекция элементов для объединения.
  2. separator – разделитель элементов коллекции. По умолчанию равен пустой строке.

Возвращаемое значение: новая строка, составленная из всех элементов коллекции отделённых между собой разделителем.

$str = str.join([1, 2, 3, 4, 5], "-")             // $str будет содержать "1-2-3-4-5"
$str = str.join(("a", "b", "c"))                  // $str будет содержать "abc"
$str = str.join({"a": "один", "b": "два"}, " + ") // $str будет содержать "один + два"
$str = str.join(["одно"], "/")                    // $str будет содержать "одно"
$str = str.join([], "/")                          // $str будет содержать ""

str.split(str string, separator string = "", limit int = 0) List

Назначение: разбивает строку на части, используя separator в качестве разделителя.

Аргументы:

  1. str – строка для разделения.
  2. separator – разделитель. Если равен пустой строке, то разбиение происходит посимвольно.
  3. limit – необязательный параметр, равный максимальному количеству частей, на которые будет разбита строка. Если limit равен 0, то без ограничений. Если limit является положительным, возвращаемый список будет содержать максимум limit элементов. При этом последний элемент будет содержать остаток строки str. Если limit отрицательный, то будут возвращены все компоненты, кроме последних limit.

Возвращаемое значение: список подстрок, на которые была разбита строка.

$letters = str.split("абвгде")             // Получили список букв слова
$words = str.split("один два три", " ")    // Получили список слов
$words = str.split("один два три", " ", 1) // words содержит ["один", "два три"]

str.replace(str string, search string, replace string) string

Назначение: ищет все вхождения подстроки в строке и заменяет их на заданное значение.

Аргументы:

  1. str – строка для преобразования.
  2. search – подстрока, которая ищется в исходной строке. 
  3. replace – строка замены.

Возвращаемое значение: новая строка, в которой все search заменены на replace.

$str = str.replace("мама мыла раму", "рам", "Даш") // $str содержит "мама мыла Дашу"

str.match(str string, pattern string) bool

Назначение: выполняет проверку данной строки регулярному выражению.

Аргументы:

  1. str – строка для сопоставления с регулярным выражением.
  2. pattern – шаблон регулярного выражения. 

Возвращаемое значение: возвращает true, если строка соответствует регулярному выражению и false в противном случае.

<b>Примечание:</b> в качестве регулярных выражений используются <a href="http://ru.wikipedia.org/wiki/PCRE" target="_blank">Perl совместимые регулярные выражения (PCRE)</a>. 
<a href="http://www.shtogrin.com/library/web/pcre/" target="_blank">Ссылка на документацию и примеры регулярных выражений.</a> 
<a href="http://myregexp.com/" target="_blank">Онлайн редактор регулярных выражений.</a>
$isIntNumber = str.match("1.234", "/^[0-9]+$/") // $isIntNumber будет равен false
$isIntNumber = str.match("1234", "/^[0-9]+$/")  // $isIntNumber будет равен true

str.distance(str1 string, str2 string) number

Назначение: вычисляет степень сходства двух строк.

Аргументы:

  1. str1 – первая строка для сравнения.
  2. str2 – вторая строка для сравнения. 

Возвращаемое значение: возвращает число от 0 до 1 включительно, определяющее степень сходства двух строк: 1 – строки эквивалентны, 0 – строки абсолютно разные.

<b>Примечание:</b> функция фактически вычисляет
<a href="https://en.wikipedia.org/wiki/Word_error_rate" target="_blank">Word Error Rate.</a>
$d = str.distance("", "abc")              // $d равен 0
$d = str.distance("Да", "да")             // $d равен 1
$d = str.distance("корыто", "открыто")    // $d равен 0.571
$d = str.distance("Да, верно", "таверна") // $d равен 0.625
$d = str.distance("жутко косые бананы", "жуй кокосы, ешь бананы") // $d равен 0.714
$d = str.distance("сошел с ума от раны", "Пошел он в пусурманы")  // $d равен 0.45
$d = str.distance("ёж", "дезоксирибонуклеиновая кислота")         // $d равен 0

Функции хэширования

hash.of(text string, algo string = "md5", binary bool = false) string

Назначение: вычисляет хэш строки согласно указанному алгоритму.

Аргументы:

  1. text – произвольная строка для хэширования.
  2. algo – название алгоритма хэширования. По умолчанию используется алгоритм md5.
  3. binary – когда установлено в true, выводит необработанные двоичные данные. При false выводит данные в шестнадцатеричной кодировке в нижнем регистре. По умолчания равен false.

Возвращаемое значение: возвращает строку, содержащую вычисленный хеш-код в шестнадцатеричной кодировке в нижнем регистре. Если binary задан как true, то возвращается хеш-код в виде бинарных данных. В случае ошибки (например, если указан недопустимый алгоритм хэширования) возвращает пустую строку.

Допустимые значения алгоритмов хэширования:

  • md2
  • md4
  • md5
  • sha1
  • sha224
  • sha256
  • sha384
  • sha512/224
  • sha512/256
  • sha512
  • sha3–224
  • sha3–256
  • sha3–384
  • sha3–512
  • ripemd128
  • ripemd160
  • ripemd256
  • ripemd320
  • whirlpool
  • tiger128,3
  • tiger160,3
  • tiger192,3
  • tiger128,4
  • tiger160,4
  • tiger192,4
  • snefru
  • snefru256
  • gost
  • gost–crypto
  • adler32
  • crc32
  • crc32b
  • crc32c
  • fnv132
  • fnv1a32
  • fnv164
  • fnv1a64
  • joaat
  • murmur3a
  • murmur3c
  • murmur3f
  • xxh32
  • xxh64
  • xxh3
  • xxh128
  • haval128,3
  • haval160,3
  • haval192,3
  • haval224,3
  • haval256,3
  • haval128,4
  • haval160,4
  • haval192,4
  • haval224,4
  • haval256,4
  • haval128,5
  • haval160,5
  • haval192,5
  • haval224,5
  • haval256,5

Примечание: если третий параметр true, то передавать возвращаемое функцией значение в качестве сообщения бота или его части нельзя. Это приведёт к падению бота.

$hash = hash.of("Наглый коричневый лисёнок прыгает вокруг ленивой собаки.")                 // $hash будет содержать bff8b4bc8b5c1c1d5b3211dfb21d1e76
$hash = hash.of("Наглый коричневый лисёнок прыгает вокруг ленивой собаки.", "ripemd160")    // $hash будет содержать 8817ca339f7f902ad3fb456150a1bb9b4cb5dde9
$hash = hash.of("Наглый коричневый лисёнок прыгает вокруг ленивой собаки.", "sha256", true) // $hash будет содержать бинарную строку (содержащую неотображаемые символы)

Функции кодирования/декодирования

codec.base64Encode(str string) string

<b>Назначение:</b> кодирует заданную строку в <a href="https://ru.wikipedia.org/wiki/Base64" target="_blank">Base64</a>.

Аргументы:

  1. str – произвольная строка для кодирования.

Возвращаемое значение: возвращает строку, закодированную в Base64.

$encoded = codec.base64Encode("Привет!") // $encoded будет содержать строку "0J/RgNC40LLQtdGCIQ=="

codec.base64Decode(str string) ?string

<b>Назначение:</b> декодирует заданную в 
<a href="https://ru.wikipedia.org/wiki/%D0%A0%D0%B0%D1%81%D1%81%D1%82%D0%BE%D1%8F%D0%BD%D0%B8%D0%B5_%D0%94%D0%B0%D0%BC%D0%B5%D1%80%D0%B0%D1%83_%E2%80%94_%D0%9B%D0%B5%D0%B2%D0%B5%D0%BD%D1%88%D1%82%D0%B5%D0%B9%D0%BD%D0%B0" target="_blank">Base64</a> строку.

Аргументы:

  1. str – строка, закодированная в Base64.

Возвращаемое значение: возвращает раскодированную строку либо nil, если закодированная строка содержит символы, не входящие в алфавит символов Base64 кодировки.

$decoded = codec.base64Decode("0J/RgNC40LLQtdGCIQ==") // $decoded будет содержать строку "Привет!"
$failed = codec.base64Decode("Привет!")               // $failed будет равен nil

codec.jsonEncode(value any) string

<b>Назначение:</b> кодирует заданное значение в <a href="https://ru.wikipedia.org/wiki/JSON" target="_blank">json</a>.

Аргументы:

  1. value – произвольное значение для кодирования.

Возвращаемое значение: возвращает значение в формате json.

$encoded = codec.jsonEncode((1, true, "a", {"a": 1, "b": 2})) // $encoded будет содержать строку '[1, true, "a", {"a": 1, "b": 2}]'

codec.jsonDecode(value string) any

<b>Назначение:</b> декодирует заданное в 
<a href="https://ru.wikipedia.org/wiki/JSON" target="_blank">json</a> значение.

Аргументы:

  1. value – значение, закодированное в json.

Возвращаемое значение: возвращает раскодированное значение либо nil, в случае невозможности его раскодирования.

$decoded = codec.jsonDecode('[1, true, "a", {"a": 1, "b": 2}]') // $decoded будет содержать список [1, true, "a", {"a": 1, "b": 2}]

Функции для работы с датой и временем

dt.add(d1 int|string, d2 int|string) string

Назначение: складывает две даты, заданные в виде строки либо как число секунд.

  • Если хотя бы один из аргументов функции число секунд, то это число будет прибавлено к числу секунд другой даты.
  • Если обе даты заданы строкой, то результат определяется по формуле d1 + abs(secondsOf(d1) - secondsOf(d2)), где abs – модуль числа (положительное значение), secondsOf – это дата, представленная как количество секунд, прошедших с начала 1970 года (даты до этого времени представлены отрицательным значением). 

Аргументы:

  1. d1 – строка, представляющая собой дату в одном из допустимых форматов, или целое число, соответствующее количеству секунд.
  2. d2 – аналогично первому аргументу.

Возвращаемое значение: возвращает новую дату и время в виде строки.

$d = dt.add("2022-01-01 12:30:00", 59)                    // $d содержит строку "2022-01-01 12:30:59" 
$d = dt.add(3600, "2022-01-01 12:30:00")                  // $d содержит строку "2022-01-01 13:30:00"
$d = dt.add("2022-01-02 02:00:00", "2022-01-01 01:00:00") // $d содержит строку "2022-01-03 03:00:00"

dt.sub(d1 int|string, d2 int|string) int|string

Назначение: вычисляет разность двух дат, заданных в виде строк либо количеством секунд.

  • Если обе даты заданы количеством секунд, то функция вернёт их разность в виде числа секунд.
  • Если обе даты заданы строкой, то будет возвращено целое число, равное разности между датами в секундах.
  • Если первый аргумент задан строкой даты, а второй – числом секунд, то результатом будет новая дата, равная разности даты и числа секунд.
  • Если второй аргумент задан строкой даты, а первый числом секунд, то результатом будет ошибка.

Аргументы:

  1. d1 – строка, представляющая собой дату в одном из допустимых форматов, или целое число, соответствующее количеству секунд.
  2. d2 – аналогично первому аргументу.

Возвращаемое значение: возвращает новую дату и время в виде строки либо число секунд – разность дат.

$d = dt.sub(100, 50)                                      // $d содержит 50
$d = dt.sub("2022-01-01 12:30:00", 3600)                  // $d содержит строку "2022-01-01 11:30:00"
$d = dt.sub(3600, "2022-01-01 12:30:00")                  // Такой вызов недопустим и приведёт к остановке программы
$d = dt.sub("2022-01-01 01:00:00", "2022-01-01 00:00:00") // $d содержит 3600

dt.format(dt int|string, format string) string

Назначение: форматирует дату согласно заданному формату.

Аргументы:

  • dt – дата, заданная строкой или числом секунд.
  • format – строка, определяющая формат даты и времени.

Возвращаемое значение: строка даты в заданном формате.

Допустимые параметры форматирования:

Символ в строке formatОписаниеПример возвращаемого значения
Год
yПолное числовое представление года, не менее 4 цифр1999, 2012, 10208
yyДве последние цифры года c дополнением нулями, если необходимо99, 05
Месяц
MПорядковый номер месяца без ведущего нуляот 1 до 12
MMПорядковый номер месяца с ведущим нулёмот 01 до 12
День
dДень месяца без ведущего нуляот 1 до 31
ddДень месяца, 2 цифры с ведущим нулёмот 01 до 31
Час
hЧасы в 12-часовом формате без ведущего нуляот 1 до 12
hhЧасы в 12-часовом формате с ведущим нулёмот 01 до 12
HЧасы в 24-часовом формате без ведущего нуляот 0 до 23
HHЧасы в 24-часовом формате с ведущим нулёмот 00 до 23
Минуты
mМинуты без ведущего нуляот 0 до 59
mmМинуты с ведущим нулёмот 00 до 59
Секунды
sСекунды без ведущего нуляот 0 до 59
ssСекунды с ведущим нулёмот 00 до 59

Примечание: если строка формата содержит символы, совпадающие с вышеперечисленными, но не являющиеся параметрами форматирования, то их следует экранировать с помощью символа обратного слэша "\".

$dt = dt.format('2022-12-20 08:34:05', 'y.MM.dd h-mm-ss')    // $dt будет содержать строку "22.12.20 8-34-05"
$dt = dt.format('16:30:47', '\Hour\s an\d \minute\s: HH/mm') // $dt будет содержать строку "Hours and minutes: 16/30"

dt.year(dt int|string) int

Назначение: возвращает полное числовое представление года, не менее 4 цифр.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее год аргумента даты dt.

Примечание: если в аргумент dt передано только время, то в качестве даты будет расцениваться 1 января 1970 года, и таким образом возвращаемое функцией значение будет равно 1970.

$dt = dt.year('2022-12-20 08:34:05') // $dt будет содержать число 2022
$dt = dt.year('08:34:05') // $dt будет содержать число 1970

dt.month(dt int|string) int

Назначение: возвращает порядковый номер месяца.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее месяц аргумента даты dt.

Примечание: если в аргумент dt передано только время, то в качестве даты будет расцениваться 1 января 1970 года, и таким образом возвращаемое функцией значение будет равно 1.

$dt = dt.month('2022-12-20 08:34:05') // $dt будет содержать число 12
$dt = dt.month('08:34:05') // $dt будет содержать число 1

dt.day(dt int|string) int

Назначение: возвращает день месяца.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее день месяца аргумента даты dt.

Примечание: если в аргумент dt передано только время, то в качестве даты будет расцениваться 1 января 1970 года, и таким образом возвращаемое функцией значение будет равно 1.

$dt = dt.day('2022-12-20 08:34:05') // $dt будет содержать число 20
$dt = dt.day('08:34:05') // $dt будет содержать число 1

dt.hour(dt int|string) int

Назначение: возвращает часы в 24-часовом формате .

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее часы аргумента даты dt.

Примечание: если в аргумент dt передана дата без времени, то возвращаемое значение будет равно нулю.

// Допустим сейчас 2023-01-01
$dt = dt.hour('2022-12-20 08:34:05') // $dt будет содержать число 8
$dt = dt.hour('2022-12-20') // $dt будет содержать число 0

dt.minute(dt int|string) int

Назначение: возвращает минуты.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее минуты аргумента даты dt.

Примечание: если в аргумент dt передана дата без времени, то возвращаемое значение будет равно нулю.

// Допустим сейчас 2023-01-01
$dt = dt.minute('2022-12-20 08:34:05') // $dt будет содержать число 34
$dt = dt.minute('2022-12-20') // $dt будет содержать число 0

dt.second(dt int|string) int

Назначение: возвращает секунды.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее секунды аргумента даты dt.

Примечание: если в аргумент dt передана дата без времени, то возвращаемое значение будет равно нулю.

// Допустим сейчас 2023-01-01
$dt = dt.second('2022-12-20 08:34:05') // $dt будет содержать число 5
$dt = dt.second('2022-12-20') // $dt будет содержать число 0

dt.weekday(dt int|string) int

Назначение: возвращает порядковый номер дня недели.

Аргументы:

  1. dt – дата, заданная строкой или числом секунд.

Возвращаемое значение: возвращает число, представляющее номер дня недели аргумента даты dt, от 0 (понедельник) до 6 (воскресенье).

Примечание: если в аргумент dt передано только время, то в качестве даты будет расцениваться 1 января 1970 года, и таким образом возвращаемое функцией значение будет равно 3 (четверг).

$dt = dt.weekday('2022-12-20 08:34:05') // $dt будет содержать число 1
$dt = dt.weekday('08:34:05') // $dt будет содержать число 3

date.nearFuture(day int) string

Назначение: возвращает ближайшую будущую к текущей дату по заданному дню.

Аргументы:

  1. day – число дней для определения ближайшей в будущем даты.

Возвращаемое значение: возвращает ближайшую к day дату.

// Допустим сейчас 2022-12-20
$d = date.nearFuture(25) // $d содержит 2022-12-25
$d = date.nearFuture(10) // $d содержит 2023-01-10

date.nearPast(day int) string

Назначение: возвращает ближайшую прошлую к текущей дату по заданному дню.

Аргументы:

  1. day – число дней для определения ближайшей в прошлом даты.

Возвращаемое значение: возвращает ближайшую к day дату.

// Допустим сейчас 2022-12-20
$d = date.nearPast(25) // $d содержит 2022-11-25
$d = date.nearPast(10) // $d содержит 2023-12-10

date.future(day int) string

Назначение: возвращает дату, соответствующую указанному дню в следующем месяце.

Аргументы:

  1. day – число дней для определения даты в будущем.

Возвращаемое значение: дата в будущем.

// Допустим сейчас 2022-12-20
$d = date.future(25) // $d содержит 2023-01-25
$d = date.future(10) // $d содержит 2023-01-10

date.past(day int) string

Назначение: возвращает дату, соответствующую указанному дню в прошлом месяце.

Аргументы:

  1. day – число дней для определения даты в прошлом.

Возвращаемое значение: дата в прошлом.

// Допустим сейчас 2022-12-20
$d = date.past(25) // $d содержит 2022-11-25
$d = date.past(10) // $d содержит 2022-11-10

time.nearFuture(minute int) string

Назначение: возвращает ближайшее будущее к текущему время по заданному количеству минут.

Аргументы:

  1. minute – число минут для определения ближайшего в будущем времени.

Возвращаемое значение: возвращает ближайшее к minute время.

// Допустим сейчас 23:30:00
$t = time.nearFuture(45) // $t содержит 23:45:00
$t = time.nearFuture(15) // $t содержит 00:15:00

time.nearPast(minute int) string

Назначение: возвращает ближайшее прошлое к текущему время по заданному количеству минут.

Аргументы:

  1. minute – число минут для определения ближайшего в прошлом времени.

Возвращаемое значение: возвращает ближайшее к minute время.

// Допустим сейчас 23:30:00
$t = time.nearPast(45) // $t содержит 22:45:00
$t = time.nearPast(15) // $t содержит 23:15:00

time.future(minute int) string

Назначение: возвращает время, соответствующее указанному числу минут в следующем часе.

Аргументы:

  1. minute – число минут для определения времени в будущем.

Возвращаемое значение: время в будущем.

// Допустим сейчас 23:30:00
$t = time.future(45) // $t содержит 00:45:00
$t = time.future(15) // $t содержит 00:15:00

time.past(minute int) string

Назначение: возвращает время, соответствующее указанному числу минут в прошедшем часе.

Аргументы:

  1. minute – число минут для определения времени в прошлом.

Возвращаемое значение: время в прошлом.

// Допустим сейчас 23:30:00
$t = time.past(45) // $t содержит 22:45:00
$t = time.past(15) // $t содержит 22:15:00

Функции по работе с очередью сообщений пользователя

queue.size() int

Назначение: определение размера очереди сообщений пользователя.

Аргументы: отсутствуют.

Возвращаемое значение: число сообщений пользователя.

$messageCount = queue.size() // $messageCount содержит число сообщений пользователя за всё время диалога

queue.last() ?UserMessage

Назначение: возвращает последнее сообщение пользователя либо nil, если очередь сообщений пуста.

Аргументы: отсутствуют.

Возвращаемое значение: объект UserMessage или nil.

$lastMessage = queue.last() // $lastMessage содержит последнее на данный момент сообщение пользователя

queue.first() ?UserMessage

Назначение: возвращает первое сообщение пользователя либо nil, если очередь сообщений пуста.

Аргументы: отсутствуют.

Возвращаемое значение: объект UserMessage или nil.

$firstMessage = queue.first() // $firstMessage содержит первое сообщение пользователя за всё время диалога

queue.nth(index int) ?UserMessage

Назначение: возвращает сообщение пользователя по его порядковому номеру, начиная с 1.

Аргументы:

  1. index – порядковый номер сообщения пользователя.

Возвращаемое значение: объект UserMessage или nil.

$message = queue.nth(1) // $message содержит первое сообщение пользователя
$message = queue.nth(5) // $message содержит пятое сообщение пользователя

queue.lastNth(index int) ?UserMessage

Назначение: возвращает сообщение пользователя по его порядковому номеру, считая с конца очереди. Последнее сообщение соответствует порядковому номеру 1.

Аргументы:

  1. index – порядковый номер сообщения пользователя, считая с конца очереди.

Возвращаемое значение: объект UserMessage или nil.

$message = queue.lastNth(1) // $message содержит последнее сообщение пользователя
$message = queue.lastNth(5) // $message содержит пятое с конца очереди сообщение пользователя

Функции для работы с фактами

fact.save(context string, factName string, factValue mixed, botId string = nil, clientId string = nil)

Назначение: сохраняет факт в базе фактов.

Аргументы:

  1. context – строка, определяющая контекст, в рамках которого существует факт.
  2. factName – строка, определяющая название факта.
  3. factValue – любое значение, определяющее содержимое факта.
  4. botId – идентификатор бота. По умолчанию не задан.
  5. clientId – идентификатор клиента. По умолчанию не задан.

Возвращаемое значение: отсутствует.

fact.save("место", "город", "Екатеринбург")                    // Факт, доступный всем ботам компании       
fact.save("место", "город", "Екатеринбург", nil, @clientId)    // Факт с привязкой к клиенту
fact.save("место", "город", "Екатеринбург", @botId)            // Факт с привязкой к боту
fact.save("место", "город", "Екатеринбург", @botId, @clientId) // Факт с привязкой к боту и клиенту

fact.load(context string, factName string, botId string = nil, clientId string = nil) mixed

Назначение: извлекает факт из базы фактов.

Аргументы:

  1. context – строка, определяющая контекст, в рамках которого существует факт.
  2. factName – строка, определяющая название факта.
  3. botId – идентификатор бота. По умолчанию не задан.
  4. clientId – идентификатор клиента. По умолчанию не задан.

Возвращаемое значение: содержимое факта.

fact.save("место", "город", "Екатеринбург", @botId, @clientId) // Сохраняет факт с привязкой к боту и клиенту
$city = fact.load("место", "город", @botId, @clientId)         // Загружаем факт в переменную. $city содержит "Екатеринбург"

fact.delete(context string, factName string, botId string = nil, clientId string = nil)

Назначение: удаляет факт из базы фактов.

Аргументы:

  1. context – строка, определяющая контекст, в рамках которого существует факт.
  2. factName – строка, определяющая название факта.
  3. botId – идентификатор бота. По умолчанию не задан.
  4. clientId – идентификатор клиента. По умолчанию не задан.

Возвращаемое значение: отсутствует.

fact.save("место", "город", "Екатеринбург", @botId, @clientId) // Сохраняет факт с привязкой к боту и клиенту
$city = fact.load("место", "город", @botId, @clientId)         // Загружаем факт в переменную. $city содержит "Екатеринбург"
fact.delete("место", "город", @botId, @clientId)               // Удаляем факт
$city = fact.load("место", "город", @botId, @clientId)         // Пытаемся загрузить удалённый факт. Теперь $city содержит nil.

fact.query() FactQuery

Назначение: возвращает экземпляр FactQuery для построения и выполнения запросов к базе фактов.

Аргументы: отсутствуют.

Возвращаемое значение: объект FactQuery.

// Добавили пару фактов в базу
fact.save("место", "страна", "Россия")
fact.save("место", "город", "Екатеринбург")

// Загрузили в $places список мест, отсортированных по имени факта в порядке убывания:
// [{"name": "город", "value": "Россия"}, {"name": "страна", "value": "Екатеринбург"}]
$places = fact.query().
    select("name,value").
    where("context", "=", "место").
    sortBy("-name").
    rows()

fact.cond() FactQueryCondition

Назначение: возвращает экземпляр FactQueryCondition для построения составных условий в запросах к базе фактов.

Аргументы: отсутствуют.

Возвращаемое значение: объект FactQueryCondition.

// Добавили факты в базу
fact.save("города", "екатеринбург", "Екатеринбург")
fact.save("города", "москва", "Москва")
fact.save("города", "санкт-петербург", "Санкт-Петербург")
fact.save("города", "новосибирск", "Новосибирск")

// Найдём один город, начинающийся с буквы "м" или с буквы "т" и не равный городам "Екатеринбург" и "Новосибирск"
$city = fact.query().
    select("value").
    where("context", "=", "города").
    where(fact.cond().
        where("name", "^@", "м").
        orWhere("name", "^@", "т")).
    where("name", "not in", ("екатеринбург", "новосибирск")).
    one()

Функции для работы с таймером

timer.start(time int, nodeId string) string

Назначение: запускает таймер обратного отсчёта. По истечении указанного времени бот осуществит переход на указанный узел (блок).

Аргументы:

  1. time – время в секундах.
  2. nodeId – идентификатор блока для перехода после завершения отсчёта.

Возвращаемое значение: идентификатор таймера.

$timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2") // $timerId содержит уникальный идентификатор таймера на 60 секунд

timer.stop(timerId string)

Назначение: останавливает (удаляет) таймер обратного отсчёта.

Аргументы:

  1. timerId – идентификатор таймера.

Возвращаемое значение: отсутствует.

$timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2")
timer.stop($timerId) // останавливаем (удаляем) таймер

timer.stopAll()

Назначение: останавливает (удаляет) все таймеры обратного отсчёта.

Аргументы: отсутствуют.

Возвращаемое значение: отсутствует.

// запускаем два таймера
timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2")
timer.start(120, "760b9732-4bfb-4846-a348-faae5138fcb2")
// останавливаем все таймеры
timer.stopAll($timerId) 

Функции для работы с текстом на естественном языке (NLP)

nlp.parse(message string|UserMessage) Sentence

Назначение: парсит текст на естественном языке. 

Аргументы:

  1. message – текст на естественном языке или объект UserMessage.

Возвращаемое значение: объект Sentence, содержащий информацию о всех намерениях и сущностях исходного сообщения.

Примечание: данная функция извлекает из текста только сущности. Для работы с намерениями используйте функцию nlu.parse.

$sentence = nlp.parse(queue.first()) // парсим первое сообщение пользователя

nlp.join(message1 string|UserMessage, message2 string|UserMessage) Sentence

Назначение: объединяет два текста на естественном языке в одно и затем парсит его.

Аргументы:

  1. message1 – текст на естественном языке или объект UserMessage.
  2. message2 – текст на естественном языке или объект UserMessage.

Возвращаемое значение: объект Sentence, содержащий информацию о всех намерениях и сущностях объединённого сообщения.

$sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) // объединяем предпоследнее и последнее сообщения пользователя и затем парсим его  

nlp.setPerception($sentence Sentence)

Назначение: позволяет установить сообщение пользователя для обработки в других узлах (блоках) схемы бота. 

Аргументы:

  1. sentence – объект Sentence, содержащий информацию о намерениях и сущностях некоторого сообщения.

Возвращаемое значение: отсутствует.

$sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) // объединяем предпоследнее и последнее сообщения пользователя и затем парсим его
nlp.setPerception($sentence)                             // Теперь остальные узлы схемы будут работать с cообщением $sentence

Функции для "понимания" естественного языка.

nlu.parse(text string, agentId string, timezoneOffset int = 0, version int = 1) Sentence

Purpose: разбор текста на естественном языке. Выявление намерений и сущностей.

Arguments:

  1. text текст для разбора.
  2. agentId – идентификатор (uuid) агента (нейросети), производящего разбор текста.
  3. timezoneOffset – смещение временной зоны, необходимое для правильного выявления временных сущностей. По умолчанию используется смещение для UTC.
  4. version – версия NLU. Может быть числом 1 (для сценариев из старого ЛК) или 11 (для сценариев из нового ЛК).

Возвращаемое значение: объект Sentence.

$sentence = nlu.parse("Доброе утро Вася!", "d926726a-5acb-4233-8c1e-ce4300921de0")

Функции для работы с HTTP

http.sendRequest(url string, method string, body any = nil, headers Map = nil) Response

Назначение: отправляет HTTP запрос на указанный URL. 

Аргументы:

  1. url – URL-адрес, на который будет оправлен запрос.
  2. method – HTTP-метод. Допустимые значения: GET, POST, PUT, DELETE, PATCH, HEAD и OPTIONS.
  3. body – тело запроса. Может быть представлено скалярным значением, списком или ассоциативным массивом.
  4. headers – HTTP-заголовки запроса. По умолчанию устанавливается заголовок Content-Type: application/json

Возвращаемое значение: объект HTTP-ответа.

// Выполняем запрос на получение списка юзеров
$response = http.sendRequest("https://iam.twin24.ai/api/v1/users", "GET", {"limit": 15, "offset": 5}, {"Authorization": "Bearer authToken"})

// Извлекаем информацию о запросе
$statusCode = $response.statusCode
$body = $response.body
$headers = $response.headers
$error = $response.error

Примечание: для типов содержимого запроса json или xml значение body если оно является списком или ассоциативным массивом автоматически конвертируется в строку соответствующего формата. То же касается и тела ответа: если тип содержимого ответа json или xml, то строка тела ответа будет автоматически преобразована в список или ассоциативный массив. Ниже показаны типовые примеры преобразования:

// Тело Json запроса в виде структур данных BPL
$requestBody = [
    {
        "param1": "value1",
        "param2": 123,
    },
    {
        "param3": ["a", "b", "c"],
    },
]
// Это тело автоматически будет преобразовано в строку
// [
//     {
//         "param1": "value1",
//         "param2": 123
//     },
//     {
//         "param3": ["a", "b", "c"]
//     }
// ]
$response = http.sendRequest("http://some.url", "POST", $requestBody, {"Content-Type": "application/json"})

// Если тип содержимого ответа json, то тело ответа будет автоматически преобразовано в структуру BPL (в переменной $body).
$body = $response.body
// Тело Xml запроса в виде структур данных BPL
$requestBody = [
    {
        "tag": "xml",
        "value": [
            {
                "tag": "head",
                "value": [
                    {
                        "tag": "title",
                        "value": "chapter 2",
                    },
                ],
            },
            {
                "tag": "body",
                "value": [
                    {
                        "tag": "div",
                        "attributes": {
                            "class": "color",
                            "style": "display:block;",
                        },
                        "value": [
                            "Some",
                             {
                                 "tag": "br",
                             },
                             "text",
                        ],
                    },
                    {
                        "tag": "div",
                        "attributes": {
                            "id": "a12",
                        },
                        "value": [
                            {
                                "tag": "i",
                                "value": "Another text",
                            },
                            {
                                "tag": "span",
                                "expand": true, // если true, то тэг с пустым значением будет иметь закрывающий тэг
                            },
                        ],
                    },
                ],
            },
        ],
    },
]
// Это тело автоматически будет преобразовано в строку
// <xml><head><title>Chapter 2</title></head><body><div class="color" style="display:block;">Some<br />text</div><div id="a12"><i>Another text</i><span></span></div></body></xml>
$response = http.sendRequest("http://some.url", "POST", $requestBody, {"Content-Type": "text/xml"})

// Если тип содержимого ответа xml, то тело ответа будет автоматически преобразовано в структуру BPL (в переменной $body).
$body = $response.body

http.request(url string = "", method string = "POST", body any = nil) Request

Назначение: формирует новый объект HTTP-запроса.

Аргументы:

  1. url – строка URL.
  2. method – название HTTP-метода.
  3. body – содержимое тела запроса.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request("https://some.url", "POST", {"param1": 123, "param2": true}).
                 headers({"Content-Type": "application/json"}).
                 timeout(300).
                 send()

Объект Request

timeout(timeout int) Request

Назначение: задаёт максимально допустимое время запроса в секундах. Если запрос отрабатывается дольше указанного времени, то его выполнение прерывается.

Аргументы:

  1. timeout – допустимое время запроса в секундах.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request("https://some.url", "GET").
                 timeout(300).
                 send()

url(url string) Request

Назначение: задаёт URL запроса.

Аргументы:

  1. url – строка URL.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("GET").
                 send()

method(method string) Request

Назначение: задаёт HTTP-метод запроса.

Аргументы:

  1. method – название HTTP-метода.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("GET").
                 send()

body(body any) Request

Назначение: задаёт тело запроса.

Аргументы:

  1. body – тело запроса.

Возвращаемое значение: объект, содержащий информацию о HTTP запросе.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2")
                 method("PUT").
                 body("some body").
                 send()

header(header string, value string) Request

Назначение: добавляет HTTP заголовок.

Аргументы:

  1. header – название HTTP-заголовка.
  2. value – значение HTTP-заголовка.

Возвращаемое значение: объект, содержащий информацию о HTTP запросе.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("POST").
                 header("Content-Type", "application/json").
                 header("Accept-Language", "en-US,en;q=0.5").
                 send()

headers(headers Map) Request

Назначение: задаёт HTTP-заголовки.

Аргументы:

  1. headers – HTTP-заголовки.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("PUT").
                 body("some body").
                 headers({"Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.5"}).
                 send()

file(fileId string, name string = "") Request

Назначение: добавляет файл для отправки по HTTP.

Аргументы:

  1. fileId – идентификатор ранее загруженного файла.
  2. name – название параметра запроса. Если параметр не задан, то его имя будет совпадать с идентификатором файла.

Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.

$response = http.request().
                 url("http://some.url").
                 method("POST").
                 header("Content-Type", "multipart/form-data").
                 file($fileId, "file").
                 send()

send() Response

Назначение: отправляет сформированный запрос.

Возвращаемое значение: объект ответа сервера.

$response = http.request("http://some.url?p1=v1&p2=v2", "PUT", "some body").
                 headers({"header1": "...", "header2": "...").
                 send()

Объект Response

statusCode int

Назначение: код статуса ответа.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$code = $response.statusCode

body any

Назначение: тело ответа.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$body = $response.body

headers Map

Назначение: заголовки ответа.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$headers = $response.headers

error string

Назначение: значение элемента error тела ответа или пустая строка, если такого элемента нет.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$error = $response.error

isError() bool

Назначение: определение успешности ответа.

Возвращаемое значение: возвращает true, если свойство error не пустое или код статуса больше или равен 400, иначе возвращает false.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isError = $response.isError()

isSuccessful() bool

Назначение: определение успешности ответа.

Возвращаемое значение: возвращает true, если свойство error пустое и код статуса меньше 400, иначе возвращает false.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isSuccessful = $response.isSuccessful()

hasHeader(header string) bool

Назначение: определение наличия заголовка.

Аргументы:

  1. header – название заголовка.

Возвращаемое значение: true, если заголовок с указанным именем существует, и false в противном случае.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$hasContentType = $response.hasHeader("Content-Type")

header(header string) string

Назначение: получение значения заголовка.

Аргументы:

  1. header – название заголовка.

Возвращаемое значение: значение заголовка с указанным именем или пустую строку, если такого заголовка нет.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$contentType = $response.header("Content-Type")

toFile() string

Назначение: получение файла из HTTP-ответа.

Возвращаемое значение: идентификатор загруженного файла.

$response = http.sendRequest("http://some.url", "GET")
$fileId = $response.toFile()

Системные функции

sys.sleep(microseconds int)

Назначение: останавливает работу бота на указанное количество микросекунд. Если количество микросекунд превышает 1 минуту, то пауза будет уменьшена до 1 минуты.

Аргументы:

  1. microseconds – число микросекунд паузы.

Возвращаемое значение: отсутствует.

sys.sleep(3_000_000) // Пауза в 3 секунды

Функции для работы с GPT-3.5 turbo (устаревшее)

gpt3.ask(text string, temperature float = 0.7, useContext bool = false, maxTokens int = 0, timeout int = 0) string

<b>Назначение:</b> отправляет сообщение в нейросеть <a href="https://openai.com/blog/chatgpt" target="_blank">ChatGPT3</a> и возвращает её ответ.

Аргументы:

  1. text – запрос к нейросети на русском языке.
  2. temperature - число от 0 до 1 обозначающее степень достоверности и вариативности ответов нейросети (0 - максимальная достоверность и минимальная вариативность, 1 - минимальная достоверность и максимальная вариативность).
  3. useContext - определяет следует ли использовать предыдущий контекст разговора или нет.
  4. maxTokens - если больше нуля, то определяет максимальное число токенов в ответе нейросети. Если меньше или равно нулю, то не используется.
  5. timeout - если больше нуля, то ограничивает время выполнения запроса (в секундах). Если меньше или равно, то не используется. 

Возвращаемое значение: ответ нейросети в виде строки.

Примечание: в случае использования контекста текущее сообщение отправленное chat gpt будет добавлено в переменную список $gpt3Context. Все предыдущие сообщения из этого списка будут переданы в качестве контекста запроса.
Если параметр useContext равен false, то текущее сообщение не добавляется в список. Сам список сообщений (значение переменной $gpt3Context) доступен для редактирования.

$answer = gpt3.ask("Есть ли жизнь на Марсе?", 0.5, true, 500, 10) // В $answer будет ответ нейросети на заданный вопрос

Функции для работы с GPT-4 (устаревшее)

gpt4.ask(text string, temperature float = 0.7, useContext bool = false, maxTokens int = 0, timeout int = 0) string

<b>Назначение:</b> отправляет сообщение в нейросеть <a href="https://openai.com/blog/chatgpt" target="_blank">ChatGPT4</a> и возвращает её ответ.

Аргументы:

  1. text – запрос к нейросети на русском языке.
  2. temperature - число от 0 до 1 обозначающее степень достоверности и вариативности ответов нейросети (0 - максимальная достоверность и минимальная вариативность, 1 - минимальная достоверность и максимальная вариативность).
  3. useContext - определяет следует ли использовать предыдущий контекст разговора или нет.
  4. maxTokens - если больше нуля, то определяет максимальное число токенов в ответе нейросети. Если меньше или равно нулю, то не используется.
  5. timeout - если больше нуля, то ограничивает время выполнения запроса (в секундах). Если меньше или равно, то не используется. 

Возвращаемое значение: ответ нейросети в виде строки.

Примечание: в случае использования контекста текущее сообщение отправленное chat gpt будет добавлено в переменную список $gpt4Context. Все предыдущие сообщения из этого списка будут переданы в качестве контекста запроса.
Если параметр useContext равен false, то текущее сообщение не добавляется в список. Сам список сообщений (значение переменной $gpt4Context) доступен для редактирования.

$answer = gpt4.ask("Есть ли жизнь на Марсе?", 0.5, true, 500, 10) // В $answer будет ответ нейросети на заданный вопрос

Функции для работы с GPT

gpt.ask(model string, text string, temperature float = 0.7, useContext bool = false, maxTokens int = 0, timeout int = 0) string

<b>Назначение:</b> отправляет сообщение в нейросеть <a href="https://openai.com/blog/chatgpt" target="_blank">ChatGPT</a> и возвращает её ответ.

Аргументы:

  1. model - название конкретной модели нейросети. 
  2. text – запрос к нейросети на русском языке.
  3. temperature - число от 0 до 1 обозначающее степень достоверности и вариативности ответов нейросети (0 - максимальная достоверность и минимальная вариативность, 1 - минимальная достоверность и максимальная вариативность).
  4. useContext - определяет следует ли использовать предыдущий контекст разговора или нет.
  5. maxTokens - если больше нуля, то определяет максимальное число токенов в ответе нейросети. Если меньше или равно нулю, то не используется.
  6. timeout - если больше нуля, то ограничивает время выполнения запроса (в секундах). Если меньше или равно, то не используется. 

Возвращаемое значение: ответ нейросети в виде строки.

Примечание: в случае использования контекста текущее сообщение отправленное chat gpt будет добавлено в переменную список $"context.{MODEL}". Все предыдущие сообщения из этого списка будут переданы в качестве контекста запроса.
Если параметр useContext равен false, то текущее сообщение не добавляется в список. Сам список сообщений (значение переменной $"context.{MODEL}") доступен для редактирования.

$answer = gpt.ask("gpt-4-1106-preview", "Есть ли жизнь на Марсе?", 0.5, true, 500, 10) // В $answer будет ответ нейросети на заданный вопрос

gpt.createThread() string

<b>Назначение:</b> создаёт разговорную сессию с GPT ассистентом.

Аргументы: отсутствуют.

Возвращаемое значение: идентификатор чат сессии с ассистентом.

$threadId = gpt.createThread()

gpt.deleteThread(threadId string)

<b>Назначение:</b> удаляет разговорную сессию с GPT ассистентом.

Аргументы:

  1. threadId - идентификатор чат сессии.

Возвращаемое значение: отсутствует.

gpt.deleteThread($threadId)

gpt.assist(assistantId string, threadId string, messages string|Collection, model string = '', instructions string = '', additionalInstructions string = '', temperature float = 0.7, maxTokens int = 0, timeout int = 0) string

<b>Назначение:</b> отправляет сообщение в ассистента чат GPT и возвращает его ответ.

Аргументы:

  1. assistantId - идентификатор ассистента.
  2. threadId - идентификатор чат сессии с ассистентом подученный с помощью функции gpt.createThread()
  3. messages – запрос к нейросети, может быть как строкой, так и списком из нескольких сообщений.
  4. model - название модели, которая будет применяться взамен той модели которая была указана при создании ассистента.
  5. instructions - указание для ассистента взамен той инструкции что была указана при его создании.
  6. additionalInstructions - дополнительная инструкция которая будет добавлена в конец инструкции ассистента.
  7. temperature - число от 0 до 1 обозначающее степень достоверности и вариативности ответов нейросети (0 - максимальная достоверность и минимальная вариативность, 1 - минимальная достоверность и максимальная вариативность).
  8. maxTokens - если больше нуля, то определяет максимальное число токенов в ответе нейросети. Если меньше или равно нулю, то не используется.
  9. timeout - если больше нуля, то ограничивает время выполнения запроса (в секундах). Если меньше или равно, то не используется. 

Возвращаемое значение: ответ нейросети в виде строки.

$answer = gpt.assist($assistId, $threadId, "Есть ли жизнь на Марсе?", "gpt-3.5-turbo-1106", "", "", 0.5, 500, 10) // В $answer будет ответ нейросети на заданный вопрос

Функции для работы с YandexGPT

ygpt.ask(model string, text string, temperature float = 0.7, maxTokens int = 0, timeout int = 0) string

<b>Назначение:</b> отправляет сообщение в нейросеть <a href="https://ya.ru/ai/gpt-3" target="_blank">YandexGPT</a> и возвращает её ответ.

Аргументы:

  1. model - название модели.
  2. text – запрос к нейросети на русском языке.
  3. temperature - число от 0 до 1 обозначающее степень достоверности и вариативности ответов нейросети (0 - максимальная достоверность и минимальная вариативность, 1 - минимальная достоверность и максимальная вариативность).
  4. maxTokens - если больше нуля, то определяет максимальное число токенов в ответе нейросети. Если меньше или равно нулю, то не используется.
  5. timeout - если больше нуля, то ограничивает время выполнения запроса (в секундах). Если меньше или равно, то не используется. 

Возвращаемое значение: ответ нейросети в виде строки.

Примечание: возможны следующие значения для параметра model:

  • yandexgpt - для YandexGPT Pro
  • yandexgpt-lite - для YandexGPT Lite
  • summarization - для формирования краткого пересказа текста
  • ds://<идентификатор_дообученной_модели> - для моделей дообученных в Yandex DataSphere

Кроме того к модели можно приписать справа через / её версию или указать latest для самой последней версии:

$answer = ygpt.ask("yandexgpt/latest", "Есть ли жизнь на Марсе?", 0.5, 500, 15) // В $answer будет ответ нейросети на заданный вопрос

Функции для работы с атрибутами клиента

clients.setAttributes (clientId string, attributes array)

Назначение: установка атрибутов клиента

Аргументы:

  1. clientId – идентификатор (uuid) клиента
  2. attributes  – атрибуты клиента в формате {"attribute_uuid": "attribute_value", ...}
    Идентификаторы допустимых для компании атрибутов берутся в API сервиса чатов в GET /clients/attributes

Возвращаемое значение: void

clients.setAttributes(@clientId, {"74eb7a40-36d5-4db9-b4a1-abe435fd5f0d": "Firstame", "b87e9a3e-21ad-4b42-aab1-fdc52a13c769": "Lastname", "d5443075-e79d-4d1c-bdca-1c0a1965a078": "example@email.com"});


Функции для работы с YCLIENTS


Для работы с функциями yclients у вас должно быть установлено наше приложение: https://yclients.com/e/mp_364_twin/

yclients.createRecord(salonId int, params Map) ?int

Назначение: записывает клиента на услугу.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. params Map – параметры записи.
    • staffId int идентификатор сотрудника (обязательный параметр).

    • services List список услуг (обязательный параметр).

      где каждый элемент это ассоциативный массив:

          id int идентификатор услуги

    • client Map информация о клиенте (обязательный параметр).

              phone string номер телефона клиента (обязательный параметр).

              name string имя клиента (обязательный параметр, если это новый клиент).

              email string email клиента

    • datetime string - дата и время (обязательный параметр).

    • seanceLength int - длительность сеанса, сек (обязательный параметр).

    • saveIfBusy bool - сохранять ли запись если время занято или нерабочее (по умолчанию false)

    • sendSms bool - отправлять ли смс с деталями записи клиенту (по умолчанию false)

    • comment string - комментарий к записи

    • smsRemainHours int - за сколько часов до визита следует выслать смс напоминание клиенту (0 - если не нужно, по умолчанию 1)

    • emailRemainHours int - за сколько часов до визита следует выслать email напоминание клиенту (0 - если не нужно, по умолчанию 12)

    • attendance int - статус записи (2 - Пользователь подтвердил запись, 1 - Пользователь пришел, услуги оказаны, 0 - ожидание пользователя, -1 - пользователь не пришел на визит, по умолчанию 0)

    • customFields Map - ассоциативный массив дополнительных полей, заполняется согласно настроенным полям в филиале

    • recordLabels List - список идентификаторов категорий записи

    • customColor string|nil - цвет записи (по умолчанию null)

    • apiId string|nil - идентификатор внешней системы (по умолчанию null)

Возвращаемое значение: int, если удалось создать запись и nil в случае ошибки.

$recordId = yclients.createRecord(25344, {"staffId": 2303331, "services": [{"id": 11428840}], "client": {"phone": "79876543210", "name": "Семён", "email": "semen@gmail.com"}, "datetime": "2023-06-07 15:00", "seanceLength": 3600,"saveIfBusy": false, "sendSms": false, "comment": "Комментарий к записи", "smsRemainHours": 1, "emailRemainHours": 12, "attendance": 2, "customFields": {"priority":"high"}, "recordLabels": ["67345", "78549"], "customColor": nil, "apiId": "7894"});

yclients.recordDetails(salonId int, recordId int) ?Map

Назначение: получает данные о записи.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. recordId int – идентификатор записи.

Возвращаемое значение: ассоциативный массив если запись существует и nil в случае ошибки.

$record = yclients.recordDetails(25344, 52157914);
// $record будет содержать:
// {
//    "id": 52157914,
//    "client": {
//        "id": 167359987,
//        "name": "Семён",
//        "surname": "",
//        "phone": "+79876543210",
//        "card": "",
//        "email": "semen@gmail.com"
//    },
//    "staff": {
//        "id": 2303331,
//        "name": "Анисимова Полина",
//        "specialization": "специалист",
//        "position": {
//            "id": 231647,
//            "title": "Парикмахер"
//        }
//    },
//    "services": [
//        {
//            "id": 11440288,
//            "title": "Стрижка",
//            "cost": 1000,
//            "costToPay": 0,
//            "manualCost": 0,
//            "costPerUnit": 0,
//            "discount": 0,
//            "firstCost": 0,
//            "amount": 1
//        }
//    ],
//    "date": "2023-06-03T14:33:00+00:00",
//    "createDate": "2023-05-31T05:51:44+00:00",
//    "comment": "",
//    "attendance": 2,
//    "length": 4200,
//    "lastChangeDate": "2023-06-02T10:26:50+00:00",
//    "prepaid": false,
//    "prepaidConfirmed": false,
//    "deleted": true,
//    "apiId": "7894"
//}

yclients.rescheduleRecord(salonId int, recordId int, datetime string) bool

Назначение: переносит запись на новое время.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. recordId int – идентификатор записи.
  3. datetime string – новая дата и время в формате (y-MM-dd HH:mm)

Возвращаемое значение: true в случае успеха и false в случае ошибки

$success = yclients.rescheduleRecord(25344, 52157914, "2023-06-07 16:00");

yclients.confirmRecord(salonId int, recordId int) bool

Назначение: подтверждает запись.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. recordId int – идентификатор записи.

Возвращаемое значение: true в случае успеха и false в случае ошибки

$success = yclients.confirmRecord(25344, 52157914);

yclients.deleteRecord(salonId int, recordId int) bool

Назначение: удаляет запись.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. recordId int – идентификатор записи.

Возвращаемое значение: true в случае успеха и false в случае ошибки

$success = yclients.deleteRecord(25344, 52157914);

yclients.searchRecords(salonId int, filters Map) ?List

Назначение: поиск записей по филиалу.

Аргументы:

  1. salonId  int – идентификатор филиала
  2. filters Map - фильтры поиска
    • staffId int идентификатор сотрудника.
    • clientId int идентификатор клиента.
    • createdUserId int - идентификатор пользователя, создавшего запись.
    • startDate string - дата сеанса, возвращает записи начиная с указаной даты
    • endDate string - дата сеанса, возвращает записи до указаной даты
    • cStartDate string - дата создания записи, возвращает записи созданные начиная с указаной даты
    • cEndDate string - дата создания записи, возвращает записи созданные до указаной даты
    • changedAfter string - дата создания/изменения записи, возвращает записи начиная с указаной даты
    • changedBefore string -дата создания/изменения записи, возвращает записи до указаной даты

Возвращаемое значение: List в случае успеха и nil в случае ошибки

$records = yclients.searchRecords(25344);


//$records будет содержать:
//[
//    {
//        "id": 52157914,
//        "companyId": 25344,
//        "staffId": 2303331,
//        "services": [
//			  {
//				  "id": 11440288,
//				  "title": "Стрижка",
//				  "cost": 1000,
//				  "manualCost": 1000,
//				  "costPerUnit": 1000,
//				  "discount": 0,
//				  "firstCost": 1000,
//				  "amount": 1
//		  	  }
//		  ],
//        "staff": {
//            "id": 2303331,
//            "name": "Сотрудник 2",
//            "specialization": "мужской мастер",
//            "position": {
//                "id": 264317,
//                "title": "Парикмахер"
//            },
//            "avatar": "",
//            "avatarBig": "",
//            "rating": 0,
//            "votesCount": 0
//        },
//        "date": "2023-08-13T07:40:00+00:00",
//        "datetime": "2023-08-13T04:40:00+00:00",
//        "createDate": "2023-08-08T11:18:04+00:00",
//        "comment": "",
//        "online": false,
//        "visitAttendance": 0,
//        "attendance": 0,
//        "confirmed": true,
//        "seanceLength": 3600,
//        "length": 3600,
//        "smsBefore": true,
//        "smsNow": false,
//        "smsNowText": "",
//        "emailNow": false,
//        "notified": false,
//        "masterRequest": true,
//        "apiId": "",
//        "fromUrl": "",
//        "reviewRequested": false,
//        "visitId": 0,
//        "createdUserId": 787095,
//        "paidFull": 1,
//        "prepaid": false,
//        "prepaidConfirmed": false,
//        "lastChangeDate": "2023-08-08T11:18:04+00:00",
//        "customColor": "",
//        "customFontColor": "",
//        "recordLabels": [
//			  {
//			  	  "id": 104474,
//				  "title": "категория",
//				  "color": "#3b2c54"
//				  "icon": "icon"
//				  "fontColor": "#ffffff"
//			  }
//		  ],
//        "activityId": 0,
//        "documents": [
//            {
//                "id": 8172893,
//                "typeId": 7,
//                "storageId": 0,
//                "userId": 787095,
//                "companyId": 25344,
//                "number": 8172893,
//                "comment": "",
//                "dateCreated": "2023-08-13T06:40:00+00:00",
//                "categoryId": 0,
//                "visitId": 0,
//                "recordId": 52157914,
//                "typeTitle": "Визит"
//            }
//        ],
//        "smsRemainHours": null,
//        "emailRemainHours": null,
//        "bookformId": 0,
//        "recordFrom": "",
//        "isMobile": false,
//        "isSaleBillPrinted": false
//	  }
//]

yclients.recordsByVisits(salonId int, filters Map) ?List

Назначение: поиск записей по истории посещений клиента.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. filters Map - фильтры поиска
    • clientId int идентификатор клиента.
    • clientPhone string - телефон клиента (обязателен при отсутствии clientId)
    • from string - дата начала периода
    • to string - дата окончания периода
    • paymentStatuses List - статус оплаты визита ("not_paid", "paid_not_full", "paid_full", "paid_over")
    • attendance int - статус посещения (-1 - клиент не пришёл; 0 - ожидание клиента; 1 - клиент пришёл; 2 - клиент подтвердил запись.)

Возвращаемое значение:  List в случае успеха и nil в случае ошибки

Примечание: для использования функции необходимо передать clientId или clientPhone, чтобы идентифицировать клиента.

$records = yclients.recordsByVisits(25344, {"clientId": 2303331});


//$records будет содержать:
//[
//    {
//        "id": 52157914,
//        "comment": "",
//        "date": "2023-06-21T15:00:00+00:00",
//        "visitId": 550229870,
//        "attendance": 0,
//        "services": [
//            {
//                "id": 11440288,
//                "title": "Стрижка",
//                "firstCost": 1000,
//                "discountPercent": 0,
//                "costToPay": 1000,
//                "paidSum": 0,
//                "paymentStatus": "not_paid"
//            }
//        ],
//        "staff": {
//            "id": 2331303,
//            "name": "Сотрудник 1",
//            "companyId": 25344,
//            "specialization": "специалист",
//            "avatar": "",
//            "avatarBig": "",
//            "position": {
//                "id": 264317,
//                "title": "Парикмахер"
//            }
//        },
//        "company": {
//            "id": 25344,
//            "title": "Twin"
//        },
//        "tips": {
//            "hasTips": false,
//            "sum": null
//        },
//        "comer": null
//	  }
//]

yclients.bookingDates(salonId int, serviceIds List = nil, staffId int = nil, date string = nil) ?Map

Назначение: запрашивает даты доступные для бронирования.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. serviceIds List – список идентификаторов услуг.
  3. staffId int – идентификатор сотрудника.
  4. date string – дата в формате (y-MM-dd).

Возвращаемое значение: Map в случае успеха и nil в случае ошибки

Формат ответа:

  • bookingDays – массив дней, которые доступны для бронирования на указанные услуги.
  • bookingDates – массив дат, когда есть свободные сеансы на услугу к выбранному сотруднику/организации.
  • workingDays – массив рабочих дней сгруппированных по месяцам (рабочие дни сотрудника/организации).
  • workingDates – массив дат, когда работает сотрудник/организация.


// Запрашивает даты доступные для бронирования
$dates = yclients.bookingDates(25344);

// Запрашивает даты доступные для бронирования с фильтром по услугам
$dates = yclients.bookingDates(25344, [75426, 58654]);

// Запрашивает даты доступные для бронирования с фильтром по сотруднику
$dates = yclients.bookingDates(25344, nil, 2303331);

// Запрашивает даты доступные для бронирования с фильтром по дате
$dates = yclients.bookingDates(25344, nil, nil, "2023-06-08");

// Запрашивает даты доступные для бронирования с фильтром по сотруднику и дате
$dates = yclients.bookingDates(25344, nil, 2303331, "2023-06-08");

// Запрашивает даты доступные для бронирования с фильтром по услугам и дате
$dates = yclients.bookingDates(25344, [75426, 58654], nil, "2023-06-08");

// $dates будет содержать:
// {
//    "bookingDays": {
//        "6": [
//            20,
//            21,
//            22,
//            23,
//            24,
//            25,
//            26,
//            27,
//            28,
//            29,
//            30
//        ],
//        "7": [
//            1,
//            2,
//            3,
//            4,
//            8,
//            9,
//            12,
//            14,
//            20,
//            26,
//            28
//        ],
//        "8": [
//            1,
//            5,
//            7
//        ]
//    },
//    "bookingDates": [
//        "2023-06-20",
//        "2023-06-21",
//        "2023-06-22",
//        "2023-06-23",
//        "2023-06-24",
//        "2023-06-25",
//        "2023-06-26",
//        "2023-06-27",
//        "2023-06-28",
//        "2023-06-29",
//        "2023-06-30",
//        "2023-07-01",
//        "2023-07-02",
//        "2023-07-03",
//        "2023-07-04",
//        "2023-07-08",
//        "2023-07-09",
//        "2023-07-12",
//        "2023-07-14",
//        "2023-07-20",
//        "2023-07-26",
//        "2023-07-28",
//        "2023-08-01",
//        "2023-08-05",
//        "2023-08-07"
//    ],
//    "workingDays": {
//        "6": [
//            20,
//            21,
//            22,
//            23,
//            24,
//            25,
//            26,
//            27,
//            28,
//            29,
//            30
//        ],
//        "7": [
//            1,
//            2,
//            3,
//            4,
//            8,
//            9,
//            12,
//            14,
//            20,
//            26,
//            28
//        ],
//        "8": [
//            1,
//            5
//        ]
//    },
//    "workingDates": [
//        "2023-06-20",
//        "2023-06-21",
//        "2023-06-22",
//        "2023-06-23",
//        "2023-06-24",
//        "2023-06-25",
//        "2023-06-26",
//        "2023-06-27",
//        "2023-06-28",
//        "2023-06-29",
//        "2023-06-30",
//        "2023-07-01",
//        "2023-07-02",
//        "2023-07-03",
//        "2023-07-04",
//        "2023-07-08",
//        "2023-07-09",
//        "2023-07-12",
//        "2023-07-14",
//        "2023-07-20",
//        "2023-07-26",
//        "2023-07-28",
//        "2023-08-01",
//        "2023-08-05"
//    ]
//  }

yclients.bookingServices(salonId int, serviceIds List = nil, staffId int = nil, date string = nil) ?Map

Назначение: запрашивает услуги доступные для бронирования.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. serviceIds List – список идентификаторов услуг, при использовании будут возвращены как выбранные услуги так и дополнительно доступные на основе фильтров.
  3. staffId int – идентификатор сотрудника.
  4. date string – дата в формате (y-MM-dd).

Возвращаемое значение: Map в случае успеха и nil в случае ошибки

Формат ответа:

  • services List – список услуг доступных для бронирования.
  • categories List – список категорий услуг (забронировать категорию нельзя).


// Запрашивает доступные услуги
$services = yclients.bookingServices(25344);

// Запрашивает доступные услуги с учетом только необходимых
$services = yclients.bookingServices(25344, [75426, 58654]);

// Запрашивает доступные услуги сотрудника
$services = yclients.bookingServices(25344, nil, 2303331);

// Запрашивает доступные услуги на определенную дату
$services = yclients.bookingServices(25344, nil, nil, "2023-06-08");

// Запрашивает доступные услуги сотрудника на определенную дату
$services = yclients.bookingServices(25344, nil, 2303331, "2023-06-08");

// $services будет содержать:
// {
//    "services": [
//        {
//            "id": 11440288,
//            "title": "Стрижка",
//            "categoryId": 11440287,
//            "priceMin": 1000,
//            "priceMax": 2000,
//            "discount": 0,
//            "comment": "",
//            "weight": 2,
//            "active": 1,
//            "sex": 0,
//            "image": "",
//            "prepaid": "forbidden",
//            "seanceLength": 3600, // в секундах. возвращается если задан фильтр по сотруднику, в ином случае вернется null
//            "abonementRestriction": 0,
//            "prepaidSettings": {
//                "status": "forbidden",
//                "prepaidFull": {
//                    "amount": 1000,
//                    "currency": "RUB"
//                },
//                "prepaidMin": {
//                    "amount": 1000,
//                    "percent": 100,
//                    "currency": "RUB"
//                }
//            }
//        },
//        {
//            "id": 12685752,
//            "title": "Окрашивание",
//            "categoryId": 11440287,
//            "priceMin": 3000,
//            "priceMax": 3000,
//            "discount": 0,
//            "comment": "",
//            "weight": 0,
//            "active": 1,
//            "sex": 0,
//            "image": "",
//            "prepaid": "forbidden",
//            "seanceLength": null,
//            "abonementRestriction": 0,
//            "prepaidSettings": {
//                "status": "forbidden",
//                "prepaidFull": {
//                    "amount": 3000,
//                    "currency": "RUB"
//                },
//                "prepaidMin": {
//                    "amount": 3000,
//                    "percent": 100,
//                    "currency": "RUB"
//                }
//            }
//        }
//    ],
//    "categories": [
//        {
//            "id": 11440287,
//            "title": "Категория услуг",
//            "sex": 0,
//            "apiId": 0,
//            "weight": 1
//        }
//    ]
// }

yclients.bookingStaff(salonId int, serviceIds List = nil, date string = nil) ?List

Назначение: запрашивает сотрудников доступных для бронирования.

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. serviceIds List – список идентификаторов услуг.
  3. date string – дата в формате (y-MM-dd).

Возвращаемое значение: List в случае успеха и nil в случае ошибки


// Запрашивает доступных сотрудников
$staff = yclients.bookingStaff(25344);

// Запрашивает доступных сотрудников с учетом услуг
$staff = yclients.bookingStaff(25344, [75426, 58654]);

// Запрашивает доступных сотрудников с учетом даты
$staff = yclients.bookingStaff(25344, nil, "2023-06-08");

// Запрашивает доступных сотрудников на определенную дату с учетом услуг
$staff = yclients.bookingStaff(25344, [75426, 58654], "2023-06-08");

// $staff будет содержать:
// [
//    {
//        "id": 2631363,
//        "apiId": null,
//        "name": "Сотрудник 2",
//        "specialization": "мужской мастер",
//        "rating": 0,
//        "showRating": 1,
//        "userId": null,
//        "avatar": "https://be.cdn.yclients.com/images/no-master-sm.png",
//        "avatarBig": "https://be.cdn.yclients.com/images/no-master.png",
//        "commentsCount": 0,
//        "votesCount": 0,
//        "bookable": true,
//        "information": "",
//        "positionId": 263147,
//        "scheduleTill": "2023-08-31",
//        "weight": 2,
//        "fired": 0,
//        "status": 0,
//        "hidden": 0,
//        "user": null,
//        "prepaid": "forbidden",
//        "position": {
//            "id": 217643,
//            "title": "Парикмахер"
//        }
//    },
//    {
//        "id": 2331303,
//        "apiId": null,
//        "name": "Сотрудник 1",
//        "specialization": "специалист",
//        "rating": 0,
//        "showRating": 1,
//        "userId": null,
//        "avatar": "https://be.cdn.yclients.com/images/no-master-sm.png",
//        "avatarBig": "https://be.cdn.yclients.com/images/no-master.png",
//        "commentsCount": 0,
//        "votesCount": 0,
//        "bookable": true,
//        "information": "",
//        "positionId": 231647,
//        "scheduleTill": "2023-07-02",
//        "weight": 1,
//        "fired": 0,
//        "status": 0,
//        "hidden": 0,
//        "user": null,
//        "prepaid": "forbidden",
//        "position": {
//            "id": 217643,
//            "title": "Парикмахер"
//        }
//    }
// ]

yclients.bookingStaffSeances(salonId int, staffId int, serviceIds List = nil, date string = nil) ?Map

Назначение: запрашивает ближайшие доступные сеансы сотрудника

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. staffId int - иднтификатор сотрудника
  3. serviceIds List – список идентификаторов услуг.

Возвращаемое значение: Map в случае успеха и nil в случае ошибки

// Запрашивает доступные сеансы сотрудника
$staffSeances = yclients.bookingStaffSeances(25344, 2331303);

// Запрашивает доступные сеансы сотрудника с учетом услуг
$staffSeances = yclients.bookingStaffSeances(25344, 2331303, [75426, 58654]);

// $staffSeances будет содержать:
// {
//    "seanceDate": "2023-06-20",
//    "seances": [
//        {
//            "time": "13:00",
//            "seanceLength": 3600,
//            "sumLength": 3600,
//            "datetime": "2023-06-20T10:00:00+00:00"
//        },
//        {
//            "time": "13:30",
//            "seanceLength": 3600,
//            "sumLength": 3600,
//            "datetime": "2023-06-20T10:30:00+00:00"
//        }
//    ]
// }

yclients.bookingTimes(salonId int, staffId int, date string, serviceIds List = nil) ?List

Назначение: запрашивает список сеансов доступных для бронирования

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. staffId int - иднтификатор сотрудника
  3. date string – дата в формате (y-MM-dd).
  4. serviceIds List – список идентификаторов услуг.

Возвращаемое значение: List в случае успеха и nil в случае ошибки

// Запрашивает доступные сеансы сотрудника
$times = yclients.bookingTimes(25344, 2331303, "2023-06-20");

// Запрашивает доступные сеансы сотрудника на определенные услуги
$times = yclients.bookingTimes(25344, 2331303, "2023-06-20", [75426, 58654]);

// $times будет содержать:
// [
//    {
//        "time": "6:00",
//        "seanceLength": 3600,
//        "sumLength": 3600,
//        "datetime": "2023-06-21T03:00:00+00:00"
//    },
//    {
//        "time": "6:30",
//        "seanceLength": 3600,
//        "sumLength": 3600,
//        "datetime": "2023-06-21T03:30:00+00:00"
//    },
//    {
//        "time": "19:00",
//        "seanceLength": 3600,
//        "sumLength": 3600,
//        "datetime": "2023-06-21T16:00:00+00:00"
//    }
// ]

yclients.searchClient(salonId int, filters Map) ?int

Назначение: производит поиск клиента по передаваемым фильтрам

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. filters Map - фильтры поиска
    • phone string телефон клиента (необязательный параметр).
    • email string почта клиента (необязательный параметр).

Возвращаемое значение: int, если клиент найден и nil, если клиент не найден.

// Поиск клиента по номеру телефона
$clientId = yclients.searchClient(1, {'phone': '11111111111'});


// Поиск клиента по почте
$clientId = yclients.searchClient(1, {'email': 'test@mail.com'});

yclients.clientDetails(salonId int, clientId int) ?Map

Назначение: получает данные о клиенте

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. clientId int - идентификатор клиента

Возвращаемое значение: Map, если клиент найден и nil, если клиент не найден.

$client = yclients.clientDetails(1, 1);

// $client будет содержать:
// {
// 		"id": 1,
// 		"email": "test@mail.com",
// 	    "name": "name",
// 	    "surname": "",
// 	    "patronymic": "",
// 	    "phone": "+111111111",
// 	    "categories": [],
// 	    "sex": "Неизвестно",
// 	    "discount": 0,
// 	    "importance": "Без класса важности",
// 	    "card": "",
// 	    "birthDate": "",
// 	    "comment": "",
// 	    "smsCheck": false,
// 	    "smsNot": false,
//      "spent": 0,
//      "balance": 0,
//      "visits": 0,
//      "lastChangeDate": "2022-12-19T10:47:21+0400",
//      "customFields": []
//}

yclients.createClient(salonId int, params Map) ?int

Назначение: создает нового клиента

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. params Map - параметры клиента
    • name string имя клиента (обязательный параметр).
    • phone string телефон клиента (обязательный параметр).
    • email string почта клиента (необязательный параметр).
    • sexId int пол клиента (1 - мужской, 2 - женский, 0 - не известен).
    • importanceId int класс важности клиента (0 - нет, 1 - бронза, 2 - серебро, 3 - золото).
    • discount int скидка клиента.
    • card string номер карты клиента.
    • birthDate string дата рождения клиента в формате yyyy-mm-dd.
    • spent int сколько потратил средств в компании на момент добавления.
    • smsCheck int статус sms уведомлений. 1 - Поздравлять с Днем Рождения по SMS, 0 - не поздравлять.
    • categories List список идентификаторов категорий клиента.
    • customFields Map массив дополнительных полей клиента в виде пар "api-key": "value".

Возвращаемое значение: int, если клиент создан и nil, если нет.

$clientId = yclients.createClient(1, {'name': 'Имя', 'phone': '1111111111111', 'email': 'testclient@mail.com', 'sexId': 1, 'birthDate': '1999-01-01'});

yclients.updateClient(salonId int, clientId int, params Map) bool

Назначение: редактирует информацию клиента

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. clientId  int – идентификатор клиента.
  3. params Map - параметры клиента
    • name string имя клиента (обязательный параметр).
    • phone string телефон клиента (обязательный параметр).
    • email string почта клиента.
    • sexId int пол клиента (1 - мужской, 2 - женский, 0 - не известен).
    • importanceId int класс важности клиента (0 - нет, 1 - бронза, 2 - серебро, 3 - золото).
    • discount int скидка клиента.
    • card string номер карты клиента.
    • birthDate string дата рождения клиента в формате yyyy-mm-dd.
    • spent int сколько потратил средств в компании на момент добавления.
    • smsCheck int статус sms уведомлений. 1 - Поздравлять с Днем Рождения по SMS, 0 - не поздравлять.
    • customFields Map массив дополнительных полей клиента в виде пар "api-key": "value".

Возвращаемое значение: true, если клиент успешно отредактирован и false, если нет.

$client = yclients.updateClient(1, 1, {'name': 'Имя', 'phone': '1111111111111', 'email': 'updateclient@mail.com'});

yclients.createClientComment(salonId int, clientId int, text string) ?int

Назначение: добавляет комментарий к клиенту

Аргументы:

  1. salonId  int – идентификатор филиала.
  2. clientId  int – идентификатор клиента.
  3. text string - текст комментария

Возвращаемое значение: int, если комментарий создан и nil, если нет.

$commentId = yclients.createClientComment(1, 1, 'text');

Объект FactQuery

Используя методы этого объекты, вы можете выполнять и строить разнообразные запросы к базе фактов. База фактов представляет собой список записей. Каждая запись представляет собой единичный факт, состоящий из следующих частей (полей):

  • Контекст (context). Произвольная строка, длина которой не превышает 255 символов. Обозначает некоторую предметную область, в рамках которой существует факт. Может участвовать в поиске.
  • Имя факта (name). Произвольная строка, длина которой не превышает 255 символов. Служит для идентификации факта в заданном контексте. Может участвовать в поиске.
  • Значение факта (value). Любое значение. Это и есть та информация, которую мы трактуем как факт. Не может участвовать в поиске (технически может, но результат не определен).
  • Идентификатор бота (botId). Может быть задан при сохранении факта с целью привязки факта к боту. Может участвовать в поиске.
  • Идентификатор клиента (clientId). Может быть задан при сохранении факта с целью привязки факта к клиенту. Может участвовать в поиске.

select(fields string|Collection) FactQuery

Назначение: задаёт список полей из базы фактов, значения которых следует вернуть в результате запроса. Если метод select не вызывался, то будут возвращены поля context, name и value.

Аргументы:

  1. fields – строка, содержащая список необходимых полей, разделённых запятой либо коллекция этих полей.

Возвращаемое значение: тот же объект FactQuery.

$facts = fact.query().rows()                               // select не вызван возвращаем все поля.
$facts = fact.query().select(["value", "context"]).rows()  // Возвращаем список фактов, для которых нам нужны только value и context.
$facts = fact.query().select("botId").rows()               // Возвращаем только поле botId, к которому привязаны факты.

where(field string, operator string, value mixed) FactQuery

Назначение: задаёт условие поиска фактов. Несколько методов where объединяются по принципу логического "И". Т.е. все условия должны быть выполнены. Метод where равносилен методу andWhere(field, operator, value).

Аргументы:

  1. field – название поля, для которого задаётся условие (т.е. первый аргумент операции operator).
  2. operator – оператор, обозначающий операцию, выполняющуюся над field. Список доступных операций смотри ниже.
  3. value – второй аргумент операции.

Возвращаемое значение: тот же объект FactQuery.

Список доступных операций:

  1. "=" проверка, что field равно value.
  2. "!=" или "<>" проверка на неравенство, что field не равно value.
  3. ">" проверяет, что field больше value.
  4. "<" проверяет, что field меньше value.
  5. ">=" проверяет, что field больше или равно value.
  6. "<=" проверяет, что field меньше или равно value.
  7. "^@" или "startsWith" ищет совпадение строки value с началом field. Поиск регистрозависимый.
  8. "~" проверяет соответствие field регулярному выражению value. Поиск регистрозависимый.
  9. "!~" проверяет несоотвествие field регулярному выражению value. Поиск регистрозависимый.
  10. "~*" проверяет соответствие field регулярному выражению value. Поиск регистронезависимый.
  11. "!~*" проверяет несоотвествие field регулярному выражению value. Поиск регистронезависимый.
  12. "in" проверяет совпадение field хотя бы с одним значением в коллекции value
  13. "not in" проверяет несовпадение field со всеми значениями из коллекции value.
// Ищем факты, у которых context содержит подстроку test
$facts = fact.query().
    select("name,value").
    where("context", "~", "^.*test.*$").
    rows()

andWhere(field string, operator string, value mixed) FactQuery

Эквивалентен where(field, operator, value).

orWhere(field string, operator string, value mixed) FactQuery

Аналогичен where с той лишь разницей, что несколько вызовов этого метода объединяются по принципу логического "ИЛИ" (т.е. должно выполняться хотя бы одно условие).

where(cond FactQueryCondition) FactQuery

Назначение: задаёт сложное (вложенное) условие. Несколько вызвов метода объединяются по принципу логического "И". Эквивалентен методу andWhere(cond).

Аргументы:

  1. cond – объект FactQueryCondition, определяющий сложносоставное условие.

Возвращаемое значение: тот же объект FactQuery.

// Ищем факты, у которых context содержит подстроку test, и при этом name равен "слово", или name начинается на "оп".
$facts = fact.query().
    select("name,value").
    where("context", "~", "^.*test.*$").
    andWhere(fact.cond().
        where("name", "=", "слово").
        orWhere("name", "^@", "оп")).
    rows()

andWhere(cond FactQueryCondition) FactQuery

Эквивалентен where(cond).

orWhere(cond FactQueryCondition) FactQuery

Аналогичен where(cond), с той лишь разницей, что несколько вызовов этого метода объединяются по принципу логического "ИЛИ", т.е. должно выполняться хотя бы одно условие.

sortBy(fields string|Collection) FactQuery

Назначение: задаёт сортирову фактов по указанным полям.

Аргументы:

  1. fields – строка, содержащая список полей (через запятую), по которым следует отсортировать факты, либо коллекция, содержащая названия полей. Каждое поле может содержать префикс "+" для сортировки по возрастанию или "-" для сортировки по убыванию. Если префикс не указан, то используется сортировка по возрастанию. 

Возвращаемое значение: тот же объект FactQuery. 

// Получаем все факты для бота с двойной сортировкой: 
// Сначала по контексту по возрастанию (т.е. в алфавитном порядке)
// И далее по имени факта по убыванию.
$facts = fact.query().
    select("name,value").
    where("botId", "=", @botId)
    sortBy("+context,-name"). // Можно также использовать коллеции. Например, sortBy(["+context", "-name"])
    rows()

limit(limit int) FactQuery

Назначение: ставит ограничение на максимальное количество извлекаемых фактов.

Аргументы:

  1. limit – целое число, определяющее лимит на количество извлекаемых фактов.

Возвращаемое значение: тот же объект FactQuery

// Получаем первые 10 фактов
$facts = fact.query().
    select("name,value").
    sortBy("name").
    limit(10).
    rows()

skip(count int) FactQuery

Назначение: задаёт количество фактов, которые следует пропустить при поиске.

Аргументы:

  1. count – целое число, определяющее количество фактов для пропуска.

Возвращаемое значение: тот же объект FactQuery

// Пропускаем 5 первых фактов и извлекаем следующие 10
$facts = fact.query().
    select("name,value").
    sortBy("name").
    skip(5).
    limit(10).
    rows()

one() mixed

Назначение: возвращает первое указанное через select поле первого найденного факта.

Аргументы: отсутствуют.

Возвращаемое значение: значение поля.

// Извлекает имя первого найденного факта
$firstFactName = fact.query().
    select("name,value").        // value хоть и указано, но будет проигнорировано
    one()

column() List

Назначение: возвращает список, состоящий из всех значений первого выбранного поля найденных фактов.

Аргументы: отсутствуют.

Возвращаемое значение: список значений поля.

// Извлекает список имён всех найденных фактов
$names = fact.query().
    select("name,value").        // value хоть и указано, но будет проигнорировано
    column()

row() Map

Назначение: возвращает все выбранные поля в виде ассоциативного массива для первого найденного факта.

Аргументы: отсутствуют.

Возвращаемое значение: значения всех полей первого факта.

// Извлекает имя и значение первого найденного факта
$names = fact.query().
    select("name,value").
    row()

rows() List<Map>

Назначение: возвращает список всех найденных фактов. Каждый факт возвращается как ассоциативный массив, ключами которого являются поля факта, а значениями – значения полей.

Аргументы: отсутствуют.

Возвращаемое значение: значения всех полей всех фактов.

// Извлекает имя и значение всех фактов
$names = fact.query().
    select("name,value").
    rows()

Объект FactQueryCondition

Используйте методы этого объекта, чтобы строить сложные вложенные условия к базе фактов.

where(field string, operator string, value mixed) FactQueryCondition

Аналогичен методу where(field string, operator string, value mixed) объекта FactQuery.

andWhere(field string, operator string, value mixed) FactQueryCondition

Аналогичен методу andWhere(field string, operator string, value mixed) объекта FactQuery.

orWhere(field string, operator string, value mixed) FactQueryCondition

Аналогичен методу orWhere(field string, operator string, value mixed) объекта FactQuery.

and(field string, operator string, value mixed) FactQueryCondition

Аналогичен методу andWhere(field string, operator string, value mixed) объекта FactQuery.

or(field string, operator string, value mixed) FactQueryCondition

Аналогичен методу orWhere(field string, operator string, value mixed) объекта FactQuery.

where(cond FactQueryCondition) FactQueryCondition

Аналогичен методу where(cond FactQueryCondition) объекта FactQuery.

andWhere(cond FactQueryCondition) FactQueryCondition

Аналогичен методу andWhere(cond FactQueryCondition) объекта FactQuery.

orWhere(cond FactQueryCondition) FactQueryCondition

Аналогичен методу orWhere(cond FactQueryCondition) объекта FactQuery.

and(cond FactQueryCondition) FactQueryCondition

Аналогичен методу andWhere(cond FactQueryCondition) объекта FactQuery.

or(cond FactQueryCondition) FactQueryCondition

Аналогичен методу orWhere(cond FactQueryCondition) объекта FactQuery.

Объект UserMessage

message string

Назначение: оригинальный текст сообщения.

$msg = queue.last().message // $msg содержит текст последнего сообщения пользователя

attachments List<string>

Назначение: список идентификаторов файлов, приложенных к сообщению.

$attachments = queue.first().attachments // $attachments содержит список вложений первого сообщения пользователя.

isEmpty() bool

Назначение: определяет пустое ли сообщение.

Аргументы: отсутствуют.

Возвращаемое значение: true, если сообщение пустое, и false в противном случае.

$isEmpty = queue.last().isEmpty() // $isEmpty содержит true, если последнее сообщение пользователя пустое, и false в противном случае

hasAttachments() bool

Назначение: определяет, есть ли вложения в данном сообщении.

Аргументы: отсутствуют.

Возвращаемое значение: true, если сообщение имеет вложения, и false в противном случае.

$hasAttachments = queue.first().hasAttachments() // $hasAttachments содержит true, если первое сообщение пользователя имеет вложения, и false в противном случае

Объект Sentence

intent string

Назначение: распознанное намерение.

$sentence = nlu.parse("Привет Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$intent = $sentence.intent   // $intent содержит "greeting"

intentConfidence number

Назначение: степень достоверности распознанного намерения (1 – однозначное распознавание, 0 – намерение фактически нераспознанно).

$sentence = nlu.parse("Привет Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$confidence = $sentence.intentConfidence   // $confidence содержит 0.98

entities List<Tuple>

Назначение: список распознанных сущностей. Каждый элемент списка содержит кортеж из трёх элементов: тип сущности (string), значение сущности (строка), достоверность распознавания сущности (number).

$sentence = nlu.parse("Доброе утро Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$entities = $sentence.entities // $entities содержит [("human-name", "Вася", 0.96), ("time", "2023-01-09 23:30:00", 0.87)]
$first = $entities.get(0)      // $first содержит ("human-name", "Вася", 0.96)
$type = $first.get(0)          // $type содержит "human-name"

.top-button {
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/baseline_keyboard_arrow_up_white_18dp.png) !important;
		background-position: center;
		background-color: #47a7f5 !important;
		background-repeat: no-repeat;
		box-shadow: -1px 1.5px 3px #999;
		color: #47a7f5 !important;
		border-radius:50px !important;
        position: fixed;
        bottom: 45px;
        left: 93.5%;
        width: 50px;
		height: 50px !important;
        font-size: 12px !important;
        padding: 14.5px !important;
		z-index: 2;
}
.top-button:hover{
		background-color: #65b9ff !important;
        color: #65b9ff !important;
}
.page-header{
		background-color: #232838;
	    background-repeat: no-repeat;
	    background-position: center;
		width: auto;
    	height: 100px;
		background-image: url(https://confluence.twin24.ai/download/attachments/23986188/logo_twin-02.png);
		background-size: 10em;
        color: #fff;
        font-size: 20px;
        padding: 20px;
}
.page-footer{
		background-color: #232838;
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/decorated-pattern-dark.png);
		width: auto;
    	height: 10px;
        color: #fff;
		text-align: end;
    	font: small-caption;
    	padding-inline-end: 30px;
    	padding-top: 200px;
    	padding-bottom: 30px;
}
.page-headline{
		background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/Solid256dot8_2changed.png);
    	background-repeat: no-repeat;
    	background-position-x: -227px;
    	background-position-y: center;
    	padding: 20px;
		background-color: #007bff;
		width: auto;
    	height: 10px;
        color: #fff;
		text-align: center;
    	font: caption;
    	font-weight: 600;
}
.tabs-menu{
    	padding-left: 85% !important;
}

On this page:

BPL operations work only in chats and incoming calls. To test scenarios with BPL operations, use chats in the widget.

Also see <a href="https://confluence.twin24.ai/pages/viewpage.action?pageId=137790002" target="_blank">Creating a test widget</a>.

General functions

del(varName string)

Purpose: deletion of a local or module variable.

Arguments:

  1. varName is the name of the variable as a string. The name can start with a variable scope prefix. If the prefix is ​​omitted, then the variable is regarded to be local.

Returned value: none.

$localVar = 123
#moduleVar = true
del("$localVar")   // Deletes the local variable $localVar
del("localVar")    // Result is the same as for del("$localVar")
del("#moduleVar")  //  Deletes a variable visiable within a module

setClientTimezoneOffset(offset int)

Назначение: changes bot collocutor's timezone offset.

Аргументы:

  1. offset – timezone offset in minutes.

Возвращаемое значение: none.

Примечание: call of this function leads to change of environment variables now, today and time according to the set timezone.

setClientTimezoneOffset(-1800)

Math functions

math.pos(num mixed) number

Purpose: converts the argument to a number. The function acts as equivalent to the unary "+" operator.

Arguments:

  1. num – arbitrary value that will be converted to a number.

Returned value: number.

$a = math.pos(true)  // $a will be equal tо 1
$a = math.pos(false) // $a will be equal to 0
$a = math.pos(nil)   // $a will be equal to 0
$a = +true           // $a will be equal to 1, same as math.pos(true)

math.neg(num number) number

Purpose: changes the sign of a number. The function acts as equivalent to the unary operation "-".

Arguments:

  1. num – an arbitrary number whose sign changes to the opposite.

Returned value: the same number with the opposite sign.

$a = math.neg(-1) // $a will be equal to 1
$a = math.neg(1)  // $a will be equal to -1
$a = math.neg(0)  // $a will be equal to 0
$a = -(-10)       // $a will be equal to 10, same as math.neg(-10)

math.inv(num number) number

Purpose: bit number inversion. This function is equivalent to the unary operator "~".

Arguments:

  1. num – an arbitrary number with invertible bits.

Returned value: inverted number.

$a = math.inv(5) // $a is equal to -6
$a = ~5          // same as previous line

math.not(num number) bool

Purpose: logical negation of a number. This function is equivalent to the unary operation "!".

Arguments:

  1. num – an arbitrary number.

Returned value: true if num is not equal to 0; otherwise false.

$a = math.not(5) // $a is equal to false
$a = math.not(0) // $a is equal to true
$a = !0          // same as previous line

math.add(num1 number, num2 number, precision int = 12) number

Purpose: addition of numbers.  This function is equivalent to the binary operation "+".

Arguments:

  1. num1 – the first part
  2. num2 – the second part.
  3. precision – the accuracy of calculation, the number of digits after the decimal point. The default value is 12. The maximum value is 14.

Returned value: sum of numbers.

$a = math.add(1.5, 3.5)         // $a is equal to 5
$a = 1.5 + 3.5                  // same as previous line
$a = math.add(1.000006, 2.1, 5) // $a is equal to 3.10001

math.sub(num1 number, num2 number, precision int = 12) number

Purpose: difference of numbers. This function is equivalent to the binary operation "-".

Arguments:

  1. num1 – minuend.
  2. num2 – subtrahend.
  3. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: difference of numbers.

$a = math.sub(1.5, 3.5)         // $a is equal to -2
$a = 1.5 - 3.5                  // same as previous line
$a = math.sub(2.100006, 1.1, 5) // $a is equal to 1.00001

math.mul(num1 number, num2 number, precision int = 12) number

Purpose: multiplication. This function is equivalent to the binary operation "*".

Arguments:

  1. num1 – first multiplier.
  2. num2 – second multiplier.
  3. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: multiplication.

$a = math.mul(1.5, 3.5)         // $a is equal to 5.25
$a = 1.5 * 3.5                  // same as previous line
$a = math.mul(1.2345, 1.234, 5) // $a is equal to 1.52337

math.div(num1 number, num2 number, precision int = 12) number

Purpose: quotient of numbers. Equivalent to the binary operation "/".

Arguments:

  1. num1 – dividend.
  2. num2 – divider.
  3. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: quotient of numbers.

$a = math.div(1.5, 3.5) // $a is equal to 0.428571428571
$a = 1.5 / 3.5          // same as previous line
$a = math.div(1, 3, 5)  // $a is equal to 0.33333

math.idiv(num1 number, num2 number) int

Purpose: integer division of numbers. This function is equivalent to the binary operation "\".

Arguments:

  1. num1 – dividend.
  2. num2 – divider.

Returned value: integer part of private numbers.

$a = math.idiv(2.5, 0.3) // $a is equal to 8
$a = 2.5 \ 0.3           // same as previous line

math.mod(num1 number, num2 number, precision int = 12) number

Purpose: remainder after dividing two numbers. This function is equivalent to the binary operation "%".

Arguments:

  1. num1 – dividend.
  2. num2 – divider.
  3. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: remainder of the division.

$a = math.mod(3.5, 1.5)    // $a is equal to 0.5
$a = 3.5 % 1.5             // same as previous line
$a = math.mod(1/3, 2/7, 5) // $a is equal to 0.04762

math.pow(base number, power number, precision int = 12) number

Purpose: raising the number base to the power. This function is equivalent to the binary operation "**".

Arguments:

  1. base – base.
  2. power – degree.
  3. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: result of exponentiation.

$a = math.pow(1.5, 3.5)    // $a is equal to 4.133513940947
$a = 1.5 ** 3.5            // same as previous line
$a = math.pow(1.3, 7.1, 5) // $a is equal to 0.44166

math.sqrt(num number, precision int = 12) number

Purpose: extracting the square root.

Arguments:

  1. num – the number from which the root is taken.
  2. precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 14.

Returned value: square root or error if the number is negative.

$a = math.sqrt(3.14)   // $a is equal to 1.772004514667
$a = math.sqrt(1.7, 5) // $a is equal to 0.30384

math.round(num number, precision int) number

Purpose: rounding the number to the required decimal place.

Arguments:

  1. num – number to round.
  2. precision – calculation accuracy, the number of digits after the decimal point. The maximum is 14.

Returned value: number rounded with a given precision.

$a = math.round(3.14159265358979323846264338327950288419716, 17) // $a is equal to 3.1415926535898
$a = math.round(3.14159265358979323846264338327950288419716, 2)  // $a is equal to 3.14
$a = math.round(3.14159265358979323846264338327950288419716, 0)  // $a is equal to 3

math.rand(min int, max int) int

Purpose: generates integer number in range between min and max (inclusive).

Arguments:

  1. min - the lowest value to be returned.
  2. max - the highest value to be returned.

Returned valuenumber in range between min and max (inclusive).

$r = math.rand(-10, 10)

Functions for working with strings

str.len(str string) int

Purpose: determining the length of the string in characters.

Arguments:

  1. str – string whose length is to be determined.

Returned value: integer is equal to the number of characters in the string.

$str = "Some string"
$len = str.len($str) // $len will contain 15

str.lower(str string) string

Purpose: conversion of string characters to lower case.

Arguments:

  1. str – string to be converted.

Returned value: a string with all characters in lowercase.

$str = "StRiNg"
$lower = str.lower($str) // $lower will contain "string" 

str.upper(str string) string

Purpose: conversion of string characters to uppercase.

Arguments:

  1. str – string to be converted.

Returned value: a string with all characters in uppercase.

$str = "StRiNg"
$upper = str.upper($str) // $lower will contain "STRING" 

str.ucfirst(str string) string

Purpose: conversion of the first character of the string to uppercase.

Arguments:

  1. str – string whose first character is to be converted.

Returned value: string with the first character written in upper case.

$str = str.ucfirst("строка") // $str будет содержать "Строка" 

str.lcfirst(str string) string

Purpose: conversion of the first character of the string to lowercase.

Arguments:

  1. str – string whose first character is to be converted.

Returned value: string with the first character written in lower case.

$str = str.ucfirst("String") // $str will contain "string" 

str.letter(str string, index int) string

Purpose: retrieve the specified character of the string.

Arguments:

  1. str – string whose character is to be retrieved.
  2. index – an integer that defines the character position in the string starting from 0. If this number is negative, then the count starts from the end of the string.

Returned value: the string that corresponds to the specified character or the empty string if there is no character at that position.

$str = "Word"
$firstLetter = str.letter($str, 0)  // First character
$lastLetter = str.letter($str, -1)  // Last character

str.first(str string, index int = 0) string

Purpose: retrieve the specified character of a string starting from the beginning of the string.

Arguments:

  1. str – string whose character is to be retrieved.
  2. index – an integer that defines the position of the character from the beginning of the string starting from 0. In this case, the sign of the number is ignored. The default value is 0 (first character).

Returned value: string that corresponds to the specified character or the empty string if there is no character at that position.

$str = "Word"
$firstLetter = str.first($str)      // First character
 $secondLetter = str.first($str, 1)  // Last character

str.last(str string, index int = 0) string

Purpose: retrieve the specified character of the string starting from the end of the string.

Arguments:

  1. str – string whose character is to be retrieved.
  2. index – an integer that defines the position of the character from the end of the string starting from 0. In this case, the sign of the number is ignored. The default value is 0 (last character).

Returned value: string that corresponds to the specified character or the empty string if there is no character at that position.

$str = "Слово"
$lastLetter = str.last($str)       // Последняя буква
$penultLetter = str.last($str, 1)  // Предпоследняя буква

str.concat(str1 string, str2 string) string

Purpose: concatenates two strings into one.

Arguments:

  1. str1 – string to be concatenated.
  2. str2 – string to be concatenated with.

Returned value: a new line that consists of the first line to the right of which the second line is added.

$str1 = "one"
$str2 = "two"
$str = str.concat($str1, $str2) // $str will contain "onetwo" 

str.sub(str string, offset int, length int = nil) string

Purpose: returns a substring of str starting from the offset character by count and length of character length.

Arguments:

  1. str – original string.
  2. offset – if offset is not negative, the returned substring starts at the offset position from the beginning of the string, starting from zero.
    If offset is negative, the returned substring starts at offset characters from the end of str string.
    If str is less than offset characters, an empty string will be returned.
  3. length – if length is positive, the returned string will be no longer than length characters starting at the offset parameter (depending on the length of string).
    If length is negative, then the number of characters specified by this argument will be discarded from the end of string (after the starting position has been calculated, if offset is negative). If the position of the beginning of the substring specified by the offset argument is in or after the discarded part of the string, then the empty string is returned.
    If the length parameter is defined and equals to 0, an empty string will be returned.
    If the length parameter is omitted or nil, then a substring will be returned starting at the position specified by the offset parameter up to the end of the string.

Returned value: part of str or the empty string.

$sub = str.sub("abcdef", 1)      // $sub is equal to bcdef
$sub = str.sub("abcdef", 1, 3)   // $sub is equal to bcd
$sub = str.sub("abcdef", 0, 4)   // $sub is equal to abcd
$sub = str.sub("abcdef", 0, 8)   // $sub is equal to abcdef
$sub = str.sub("abcdef", -1, 1)  // $sub is equal to f
$sub = str.sub("abcdef", -1)     // $sub is equal to f
$sub = str.sub("abcdef", -2)     // $sub is equal to ef
$sub = str.sub("abcdef", -3, 1)  // $sub is equal to d
$sub = str.sub("abcdef", 0, -1)  // $sub is equal to abcde
$sub = str.sub("abcdef", 2, -1)  // $sub is equal to cde
$sub = str.sub("abcdef", 4, -4)  // $sub is equal to empty string
$sub = str.sub("abcdef", -3, -1) // $sub is equal to de

str.join(arr Collection, separator string = "") string

Purpose: concatenates the elements of a collection (tuple, list, or associative array) into a string.

Arguments:

  1. arr – collection of items to concatenate.
  2. separator – collection separator. The default is an empty string.

Returned value:  a new string that contains all the elements of the collection separated by a delimiter.

$str = str.join([1, 2, 3, 4, 5], "-")             // $str will contain "1-2-3-4-5"
$str = str.join(("a", "b", "c"))                  // $str will contain "abc"
$str = str.join({"a": "один", "b": "два"}, " + ") // $str will contain "one + two"
$str = str.join(["одно"], "/")                    // $str will contain "one"
$str = str.join([], "/")                          // $str will contain ""

str.split(str string, separator string = "", limit int = 0) List

Purpose: splits the string into parts using separator as the delimiter.

Arguments:

  1. str – string to split.
  2. separator – separator. If it is equal to an empty string, then splitting is carried out character by character.
  3. limit – an optional parameter equal to the maximum number of parts the string is splitted to. If limit is 0, then there is no limit. If the limit is positive, then the returned list will contain a maximum of limit elements, with the last element containing the remainder of str. If the limit is negative, then all components will be returned except for the last one – limit.

Returned value:  list of substrings into which the string is split.

$letters = str.split("abcdef")             // returns a list of letters in a word
$words = str.split("one two three", " ")    // returns a list of words
$words = str.split("one two three", " ", 1) // words contains ["one", "two three"]

str.replace(str string, search string, replace string) string

Purpose: searches for all occurrences of a substring in a string and replaces them with the given value.

Arguments:

  1. str – string to be converted.
  2. search – substring that is searched for in the source string. 
  3. replace – replacement string.

Returned value:  a new line where all occurrences of "search" are replaced with "replace".

$str = str.replace("mother washed frame", "frame", "Dasha") // $str contains "mother washed Dasha"

str.match(str string, pattern string) bool

Purpose: performs a regular expression check on the given string.

Arguments:

  1. str – string to match against the regular expression.
  2. pattern – pattern of regular expression.

Returned value: returns true if the string matches the regular expression, otherwise returns false.

<b>Note:</b> <a href="https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions" target="_blank">Perl Compatible Regular Expressions (PCRE)</a> are used as regular expressions. 
<a href="http://www.shtogrin.com/library/web/pcre/" target="_blank">Link to documentation and examples of regular expressions.</a> 
<a href="http://myregexp.com/" target="_blank">Online regular expression editor.</a>
$isIntNumber = str.match("1.234", "/^[0-9]+$/") // $isIntNumber will be equal to false
$isIntNumber = str.match("1234", "/^[0-9]+$/")  // $isIntNumber will be equal to true

str.distance(str1 string, str2 string) number

Purpose: calculates the similarity of two strings.

Arguments:

  1. str1 – first line to compare.
  2. str2 – second line to compare. 

Returned value:  returns a number between 0 and 1 that indicates the similarity of two strings. 1 - strings are equivalent, 0 - strings are completely different.

<b>Note:</b> the function actually calculates
<a href="https://en.wikipedia.org/wiki/Word_error_rate" target="_blank">Word Error Rate.</a>
$d = str.distance("", "abc")              // $d equals 0
$d = str.distance("Да", "да")             // $d equals 1
$d = str.distance("корыто", "открыто")    // $d equals 0.571
$d = str.distance("Да, верно", "таверна") // $d equals 0.625
$d = str.distance("жутко косые бананы", "жуй кокосы, ешь бананы") // $d equals 0.714
$d = str.distance("сошел с ума от раны", "Пошел он в пусурманы")  // $d equals 0.45
$d = str.distance("ёж", "дезоксирибонуклеиновая кислота")         // $d equals 0

Hash functions

hash.of(text string, algo string = "md5", binary bool = false) string

Purpose: calculates the hash of the string according to the specified algorithm.

Arguments:

  1. text – arbitrary string to hash.
  2. algo – the name of the hash algorithm. The default algorithm is md5.
  3. binary – when it is set to true, then it returns output raw binary data. If it is set to false, it outputs the data in lowercase hexadecimal encoding. By default, it is set to false.

Returned value: returns a string that contains the computed hash code in lowercase hexadecimal encoding. If binary is set to true, then the hash code is returned as binary data. It returns an empty string in case of error (for example, if an invalid hash algorithm is specified).

Possible hash algorithms values:

  • md2
  • md4
  • md5
  • sha1
  • sha224
  • sha256
  • sha384
  • sha512/224
  • sha512/256
  • sha512
  • sha3-224
  • sha3-256
  • sha3-384
  • sha3-512
  • ripemd128
  • ripemd160
  • ripemd256
  • ripemd320
  • whirlpool
  • tiger128,3
  • tiger160,3
  • tiger192,3
  • tiger128,4
  • tiger160,4
  • tiger192,4
  • snefru
  • snefru256
  • gost
  • gost-crypto
  • adler32
  • crc32
  • crc32b
  • crc32c
  • fnv132
  • fnv1a32
  • fnv164
  • fnv1a64
  • joaat
  • murmur3a
  • murmur3c
  • murmur3f
  • xxh32
  • xxh64
  • xxh3
  • xxh128
  • haval128,3
  • haval160,3
  • haval192,3
  • haval224,3
  • haval256,3
  • haval128,4
  • haval160,4
  • haval192,4
  • haval224,4
  • haval256,4
  • haval128,5
  • haval160,5
  • haval192,5
  • haval224,5
  • haval256,5

Note: if the third parameter is true, then you cannot pass the value returned by the function as a bot message or part of it. This will crash the bot.

$hash = hash.of("Impudent brown fox cub jumps around a lazy dog.")                 // $hash will contain bff8b4bc8b5c1c1d5b3211dfb21d1e76
$hash = hash.of("Impudent brown fox cub jumps around a lazy dog.", "ripemd160")    // $hash will contain 8817ca339f7f902ad3fb456150a1bb9b4cb5dde9
$hash = hash.of("Impudent brown fox cub jumps around a lazy dog.", "sha256", true) // $hash will contain a binary string (with displayable characters)

Encoding/decoding functions

codec.base64Encode(str string) string

<b>Purpose:</b> encodes the given string into <a href="https://en.wikipedia.org/wiki/Base64" target="_blank">Base64</a>.

Arguments:

  1. str – arbitrary string to encode.

Returned value: returns a string encoded in Base64.

$encoded = codec.base64Encode("Hello!") // $encoded will contain string "0J/RgNC40LLQtdGCIQ=="

codec.base64Decode(str string) ?string

<b>Purpose:</b> decodes the provided <a href="https://en.wikipedia.org/wiki/Base64" target="_blank">Base64</a> string.

Arguments:

  1. str – Base64 encoded string.

Returned value: returns the decoded string or nil if the encoded string contains characters that are not in the base64 character alphabet of the encoding.

$decoded = codec.base64Decode("0J/RgNC40LLQtdGCIQ==") // $decoded will contain string "Hello!"
$failed = codec.base64Decode("Hello!")               // $failed will be equal to nil

Date and Time Functions

dt.add(d1 int|string, d2 int|string) string

Purpose: adds two dates, provided as a string or as a number of seconds.

  • If at least one of the function arguments is the number of seconds, then this number will be added to the number of seconds of another date.
  • If both dates are strings, then the result is d1 + abs(secondsOf(d1) - secondsOf(d2)), where abs is the absolute value of the number (a positive value), secondsOf is the date represented as the number of seconds since the beginning of 1970 (dates prior to that time are represented by a negative value).

Arguments:

  1. d1 – a string that represents a date in one of the allowed formats or an integer that corresponds to the number of seconds.
  2. d2 – similar to the first argument.

Returned value: returns the new date and time as a string.

$d = dt.add("2022-01-01 12:30:00", 59)                    // $d contains string "2022-01-01 12:30:59" 
$d = dt.add(3600, "2022-01-01 12:30:00")                  // $d contains string "2022-01-01 13:30:00"
$d = dt.add("2022-01-02 02:00:00", "2022-01-01 01:00:00") // $d contains string "2022-01-03 03:00:00"

dt.sub(d1 int|string, d2 int|string) int|string

Purpose: calculates the difference between two dates provided as strings or seconds.

  • If both dates are provided in number of seconds, then the function will return their difference as a number of seconds.
  • If both dates are provided as a string, then an integer equal to the difference between the dates in seconds will be returned.
  • If the first argument is a date string and the second argument is a number of seconds, then the result is a new date equal to the difference between the date and the number of seconds.
  • If the second argument is a date string and the first argument is a number of seconds, then the result is an error.

Arguments:

  1. d1 – a string that represents a date in one of the allowed formats or an integer that corresponds to the number of seconds.
  2. d2 – similar to the first argument.

Returned value: returns a new date and time as a string, or the number of seconds – the difference between the dates.

$d = dt.sub(100, 50)                                      // $d contains 50
$d = dt.sub("2022-01-01 12:30:00", 3600)                  // $d  contains string "2022-01-01 11:30:00"
$d = dt.sub(3600, "2022-01-01 12:30:00")                  // This a call is invalid and will cause the program to terminate.
$d = dt.sub("2022-01-01 01:00:00", "2022-01-01 00:00:00") // $d contains 3600

dt.format(dt int|string, format string) string

Purpose: brings the date to the specified format.

Arguments:

  • dt – date provided as a string or number of seconds.
  • format – string that specifies the date and time format.

Returned value: date string in the provided format.

Possible formatting parameters:

Character in the format stringDescriptionExample of returned value
Year
yFull numeric representation of the year (at least 4 digits)1999, 2012, 10208
yyThe last two digits of the year (with zeros if necessary)99, 05
Month
M

Number of the month without leading zero

from 1 to 12
MMNumber of the month with leading zerofrom 01 to 12
Day
dDay of the month without leading zerofrom 1 to 31
ddDay of the month, 2 digits with a leading zerofrom 01 to 31
Hour
hHours in 12-hour format without leading zerofrom 01 to 12
hhHours in 12-hour format with leading zerofrom 01 to 12
HHours in 24-hour format without leading zerofrom 0 to 23
HHHours in 24-hour format with leading zerofrom 0 to 23
Minutes
mMinutes without leading zerofrom 0 to 59
mmMinutes with leading zerofrom 0 to 59
Seconds
sSeconds without a leading zerofrom 0 to 59
ssSeconds with a leading zerofrom 0 to 59

Note: if the format string contains characters that match the above, but are not formatting options, then they should be escaped with the backslash character "\".

$dt = dt.format('2022-12-20 08:34:05', 'y.MM.dd h-mm-ss')    // $dt will contain string "22.12.20 8-34-05"
$dt = dt.format('16:30:47', '\Hour\s an\d \minute\s: HH/mm') // $dt will contain string "Hours and minutes: 16/30"

date.nearFuture(day int) string

Purpose: returns the nearest future date to the current date for the specified day.

Arguments:

  1. day – number of days to determine the next date in the future.

Returned value: returns the closest date to day.

// let's say that today is 2022-12-20
$d = date.nearFuture(25) // $d contains 2022-12-25
$d = date.nearFuture(10) // $d contains 2023-01-10

date.nearPast(day int) string

Purpose: returns the nearest past date to the current date for the given day.

Аргументы:

  1. day – number of days to determine the closest date in the past.

Returned value: returns the closest date to day.

// let's say that today is 2022-12-20
$d = date.nearPast(25) // $d contains 2022-11-25
$d = date.nearPast(10) // $d contains 2023-12-10

date.future(day int) string

Purpose: returns the date that corresponds to the specified day in the next month.


Arguments:

  1. day – number of days to determine a date in the future.

Returned value: date in the future.

// let's say that today is 2022-12-20
$d = date.future(25) // $d contains 2023-01-25
$d = date.future(10) // $d contains 2023-01-10

date.past(day int) string

Purpose: returns the date that corresponds to the specified day in the previous month.

Arguments:

  1. day – number of days to determine a date in the past.

Returned value: date in the past.

// let's say that today is 2022-12-20
$d = date.past(25) // $d contains 2022-11-25
$d = date.past(10) // $d contains 2022-11-10

time.nearFuture(minute int) string

Purpose: returns the nearest future to the current time by the provided number of minutes.

Arguments:

  1. minute – number of minutes to determine the nearest future time.

Returned value: returns the time closest to minute.

// let's say that now is 23:30:00
$t = time.nearFuture(45) // $t contains 23:45:00
$t = time.nearFuture(15) // $t contains 00:15:00

time.nearPast(minute int) string

Purpose: returns the nearest past to the current time for the specified number of minutes.

Arguments:

  1. minute – number of minutes to determine the nearest past time.

Returned value: returns the time closest to minute.

// Let's say now it is 23:30:00
$t = time.nearPast(45) // $t contains 22:45:00
$t = time.nearPast(15) // $t contains 23:15:00

time.future(minute int) string

Purpose: returns time that corresponds to the specified number of minutes in the next hour.

Arguments:

  1. minute – number of minutes to determine the time in the future.

Returned value: time in the future.

// Let's say now it is 23:30:00
$t = time.future(45) // $t contains 00:45:00
$t = time.future(15) // $t contains 00:15:00

time.past(minute int) string

Purpose: returns the time that corresponds to the specified number of minutes in the past hour.

Arguments:

  1. minute – number of minutes to determine the time in the past.

Returned value: time in the past.

// Let's say now it is 23:30:00
$t = time.past(45) // $t contains 22:45:00
$t = time.past(15) // $t contains 22:15:00

Functions for user message queue

queue.size() int

Purpose: determines the size of the user message queue.

Arguments: not present.

Returned value: number of user messages.

$messageCount = queue.size() // $messageCount contains the number of user messages for the entire dialog

queue.last() ?UserMessage

Purpose: returns the last user message or nil if the message queue is empty.

Arguments: not present.

Returned value: UserMessage object or nil.

$lastMessage = queue.last() // $lastMessage contains the last user message in a dialog

queue.first() ?UserMessage

Purpose: returns the first user message or nil if the message queue is empty.

Arguments: not present.

Returned value: UserMessage object or nil.

$firstMessage = queue.first() // $firstMessage contains the first user message in a dialog

queue.nth(index int) ?UserMessage

Purpose: returns the user message by its sequence number starting from 1.

Arguments:

  1. index – sequence number of the user message.

Returned value: UserMessage object or nil.

$message = queue.nth(1) // $message contains the first user message 
$message = queue.nth(5) // $message  contains the fifth user message  

queue.lastNth(index int) ?UserMessage

Purpose: returns the user message by its sequence number starting from the end of the queue. The last message corresponds to sequence number 1.

Arguments:

  1. index – sequence number of the user message starting from the end of the queue.

Returned value: UserMessage object or nil.

$message = queue.lastNth(1) // $message contains the last user message
$message = queue.lastNth(5) // $message contains the fifth user message

Functions for working with facts

fact.save(context string, factName string, factValue mixed, botId string = nil, clientId string = nil)

Purpose: saves the fact to the fact base.

Arguments:

  1. context – string that specifies the context where the fact exists.
  2. factName – string that specifies the name of the fact.
  3. factValue – any value that defines the contents of a fact.
  4. botId – bot ID. Not specified by default.
  5. clientId – Client ID. Not specified by default.

Returned value: not present.

fact.save("place", "city", "Moscow")                    // Fact that is available to all company bots
fact.save("place", "city", "Moscow", nil, @clientId)    // Fact with reference to the client
fact.save("place", "city", "Moscow", @botId)            // Fact with reference to the bot
fact.save("place", "city", "Moscow", @botId, @clientId) // Fact with reference to the bot and client

fact.load(context string, factName string, botId string = nil, clientId string = nil) mixed

Purpose:  retrieves a fact from the fact base.

Arguments:

  1. context – a string that specifies the context where the fact exists.
  2. factName – a string that specifies the name of the fact.
  3. botId – bot ID. Not specified by default.
  4. clientId – client ID. Not specified by default.

Returned value: contents of the fact.

fact.save("place", "city", "Moscow", @botId, @clientId) // Saves the fact with reference to the bot and the client
 $city = fact.load("place", "city", @botId, @clientId) // We load the fact into a variable. $city contains "Moscow"

fact.delete(context string, factName string, botId string = nil, clientId string = nil)

Purpose:  deletes a fact from the fact base.

Arguments:

  1. context – a string that specifies the context where the fact exists.
  2. factName – a string that specifies the name of the fact.
  3. botId – bot ID. Not specified by default.
  4. clientId – client ID. Not specified by default.

Returned value: not present.

fact.save("place", "city", "Moscow", @botId, @clientId) // Saves the fact with reference to the bot and the client
$city = fact.load("place", "city", @botId, @clientId)         // We load the fact into a variable. $city contains "Moscow"
fact.delete("place", "city", @botId, @clientId)               // Deletes fact.
$city = fact.load("place", "city", @botId, @clientId)         // Trying to load a remote fact. Now $city contains nil.

fact.query() FactQuery

Purpose: returns a FactQuery instance for working with the fact database.

Arguments: not present.

Returned value: FactQuery object.

// Added a couple of facts to the database
fact.save("place", "country", "Russia")
fact.save("place", "city", "Moscow")

// We loaded into $places a list of places sorted by fact name in descending order:
// [{"name": "city", "value": "Russia"}, {"name": "country", "value": "Moscow"}]
$places = fact.query().
    select("name,value").
    where("context", "=", "place").
    sortBy("-name").
    rows()

fact.cond() FactQueryCondition

Purpose: returns an instance of FactQueryCondition for creating complex conditions when working with the fact database.

Arguments: not present.

Returned value: FactQueryCondition object.

// Added facts to the database
fact.save("cities", "ekaterinburg", "Ekaterinburg")
fact.save("cities", "moscow", "Moscow")
fact.save("cities", "saint-petersburg", "Saint-Petersburg")
fact.save("cities", "novosibirsk", "Novosibirsk")

// Let's find one city whose name starts with letter "m" or with letter "t" and is not equal to the cities "Ekaterinburg" and "Novosibirsk"
$city = fact.query().
    select("value").
    where("context", "=", "cities").
    where(fact.cond().
        where("name", "^@", "м").
        orWhere("name", "^@", "т")).
    where("name", "not in", ("ekaterinburg", "novosibirsk")).
    one()

Timer Functions

timer.start(time int, nodeId string) string

Purpose: starts the timer. After the specified time is over, the bot will go to the specified block.

Arguments:

  1. time – time in seconds.
  2. nodeId – block ID.

Returned value: timer ID.

$timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2") // $timerId contains a unique timer ID for 60 seconds

timer.stop(timerId string)

Purpose: stops (deletes) the timer.

Arguments:

  1. timerId – timer ID

Returned value: not present.

$timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2")
timer.stop($timerId) // stops (deletes) the timer.

timer.stopAll()

Назначение: stops all timers.

Аргументы: not present.

Возвращаемое значение: not present.

// starts two timers
timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2")
timer.start(120, "760b9732-4bfb-4846-a348-faae5138fcb2")
// stop all timers
timer.stopAll($timerId) 

Functions for working with text in natural language (NLP)

nlp.parse(message string|UserMessage) Sentence

Purpose: parses natural language text. 

Arguments:

  1. message – natural language text or a UserMessage object.

Returned value: a Sentence object containing information about all the intents and entities of the original message.

Note: this function extracts only entities from the text. To work with intents, use the nlu.parse function

$sentence = nlp.parse(queue.first()) // parses the first user message

nlp.join(message1 string|UserMessage, message2 string|UserMessage) Sentence

Purpose: merges two natural language texts into one and then parses it.

Arguments:

  1. message1 – text in natural language or a UserMessage object.
  2. message2 – text in natural language or a UserMessage object.

Returned value: a Sentence object that contains information about all the intents and entities of the combined message.

$sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) //  combine the last but one and the last user messages and then parse them

nlp.setPerception($sentence Sentence)

Purpose: allows you to set a user message for processing in other blocks of the script.

Arguments:

  1. sentence – a Sentence object that contains information about the intents and entities of some message.

Returned value: not present.

$sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) // combines the last but one and last messages of the user and then parse them nlp.setPerception($sentence)                             
// Now the rest of the schema nodes will work with the message $sentence

Functions for "understanding" natural language

nlu.parse(text string, agentId string, timezoneOffset int = 0, version int = 1) Sentence

Purpose: parses text in natural language. Reveals intentions and entities.

Arguments:

  1. text text for parsing.
  2. agentId – ID (uuid) of the agent (neural network) that parses the text.
  3. timezoneOffset – the time zone offset that is necessary to correctly detect temporary entities. The default offset is UTC.
  4. version – NLU version. Can be number 1 (for bots from old version of the website) or 11 (for bots created on the new website).

Returned value: Sentence object.

$sentence = nlu.parse("Good morning John!", "d926726a-5acb-4233-8c1e-ce4300921de0")

Functions for working with HTTP

http.sendRequest(url string, method string, body any = nil, headers Map = nil) Response

Purpose: sends an HTTP request to the specified URL.

Arguments:

  1. url – the URL that the request will be sent to.
  2. method – HTTP method. Possible variants: GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS.
  3. body – request body. Can be represented as a scalar value, a list, or an associative array.
  4. headers – HTTP request headers. The default header is Content-Type: application/json.

Returned value: HTTP response object.

// Executing a request to get a list of users 
$response = http.sendRequest("https://iam.twin24.ai/api/v1/users", "GET", {"limit": 15, "offset": 5}, {"Authorization": "Bearer authToken"})

// Retrieving information about the request
 $statusCode = $response.statusCode
$body = $response.body
$headers = $response.headers
$error = $response.error

http.request(url string = "", method string = "POST", body any = nil) Request

Purpose: generates a new HTTP request object.

Arguments:

  1. url – URL string.
  2. method – name of HTTP method.
  3. body – contents of the request body.

Returned value: an object that contains information about the HTTP request.

$response = http.request("https://some.url", "POST", {"param1": 123, "param2": true}).
                 headers({"Content-Type": "application/json"}).
                 timeout(300).
                 send()

Объект Request

timeout(timeout int) Request

Purpose: specifies the maximum request time in seconds. If the request is executed longer than the specified time, then its execution is interrupted.

Arguments:

  1. timeout – possible request time in seconds.

Returned value: an object that contains information about the HTTP request.

$response = http.request("https://some.url", "GET").
                 timeout(300).
                 send()

url(url string) Request

Purpose: sets the URL of the request.

Arguments:

  1. url – URL string.

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("GET").
                 send()

method(method string) Request

Purpose: specifies the HTTP request method.

Arguments:

  1. method – name of HTTP method.

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("GET").
                 send()

body(body any) Request

Purpose: sets the body of the request.

Arguments:

  1. body – request body.

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2")
                 method("PUT").
                 body("some body").
                 send()

header(header string, value string) Request

Purpose: adds an HTTP header.

Arguments:

  1. header – name of HTTP header.
  2. value – value of HTTP header

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("POST").
                 header("Content-Type", "application/json").
                 header("Accept-Language", "en-US,en;q=0.5").
                 send()

headers(headers Map) Request

Purpose: sets HTTP headers.

Arguments:

  1. headers – HTTP headers.

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url?p1=v1&p2=v2").
                 method("PUT").
                 body("some body").
                 headers({"Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.5"}).
                 send()

file(fileId string, name string = "") Request

Purpose: adds a file to send over HTTP.

Arguments:

  1. fileId – ID of the previously uploaded file.
  2. name – name of the request parameter. If the parameter is not set, then its name will match the file identifier.

Returned value: object that contains information about the HTTP request.

$response = http.request().
                 url("http://some.url").
                 method("POST").
                 header("Content-Type", "multipart/form-data").
                 file($fileId, "file").
                 send()

send() Response

Purpose: sends the generated request.

Returned value: server response object.

$response = http.request("http://some.url?p1=v1&p2=v2", "PUT", "some body").
                 headers({"header1": "...", "header2": "...").
                 send()

Объект Response

statusCode int

Purpose: response status code.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$code = $response.statusCode

body any

Purpose: response body.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$body = $response.body

headers Map

Purpose: response headers

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$headers = $response.headers

error string

Purpose: value of the error element of the response body or the empty string if there is no such element.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$error = $response.error

isError() bool

Purpose: determines the success of the response.

Returned value: returns true if the error property is specified or the status code is greater than or equal to 400, otherwise returns false.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isError = $response.isError()

isSuccessful() bool

Purpose: determines the success of the response.

Returned value: returns true if the error property is empty and the status code is less than 400, otherwise returns false.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isSuccessful = $response.isSuccessful()

hasHeader(header string) bool

Purpose: detects the presence of a header.

Arguments:

  1. header – header name

Returned value: true, if a header with the specified name exists and false otherwise.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$hasContentType = $response.hasHeader("Content-Type")

header(header string) string

Purpose: retrieves the header value

Arguments:

  1. header – header name.

Returned value: the value of the header with the specified name or an empty string if there is no such header.

$response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$contentType = $response.header("Content-Type")

toFile() string

Purpose: retrieves a file from HTTP response.

Returned value: uploaded file ID.

$response = http.sendRequest("http://some.url", "GET")
$fileId = $response.toFile()

System functions

sys.sleep(microseconds int)

Purpose: stops the bot for the specified number of microseconds. If the number of microseconds exceeds 1 minute, then the pause is set to 1 minute.

Arguments:

  1. microseconds – number of microseconds.

Returned value: not present.

sys.sleep(3_000_000) // Pause that lasts 3 seconds

Functions for working with GPT-3

gpt3.ask(text string) string

<b>Purpose:</b> sends a message to the <a href="https://openai.com/blog/chatgpt" target="_blank">ChatGPT3</a> neural network and returns the response.

Arguments:

  1. text – request to the neural network in Russian.

Returned value: the response of the neural network as a string.

$answer = gpt3.ask("Is there life on Mars?") // $answer will contain the answer of the neural network to the question

Client attributes functions

clients.setAttributes (clientId string, attributes array)

Purpose: to set value(s) of client attributes

Agruments:

  1. clientId – Client ID (uuid)
  2. attributes  – object with attributes in format {"attribute_uuid": "attribute_value", ...}
    IDs of available attributes can be found by using  GET /clients/attributes in the chat service API

Returned value: void

clients.setAttributes(@clientId, {"74eb7a40-36d5-4db9-b4a1-abe435fd5f0d": "Firstame", "b87e9a3e-21ad-4b42-aab1-fdc52a13c769": "Lastname", "d5443075-e79d-4d1c-bdca-1c0a1965a078": "example@email.com"});

FactQuery object

Using the methods of this object, you can work with the fact base. The fact base is a list of records. Each record is a single fact that consists of the following parts (fields):

  • Context (context). An arbitrary string whose length does not exceed 255 characters. Denotes some subject area where a fact relates to. Can be used in the search.
  • Fact name (name). An arbitrary string whose length does not exceed 255 characters. Identifies a fact in a provided context. Can be used in the search.
  • Fact value (value). Any value. This is the actual information that we interpret as a fact. Cannot be used in the search (technically it can, but the result is not defined).
  • Bot ID (botId). Can be specified when you save a fact in order to link the fact to the bot. Can be used in the search.
  • Client ID (clientId). Can be specified when you save a fact in order to link the fact to the client. Can be used in the search.

select(fields string|Collection) FactQuery

Purpose: specifies a list of fields from the fact base whose values ​​should be returned as a result of the query. If the select method is not called, then the context, name and value fields are returned.

Arguments:

  1. fields – a string that contains a comma-separated list of required fields or a collection of these fields.

Returned value: the same FactQuery object.

$facts = fact.query().rows()                               // select is not called, return all fields 
$facts = fact.query().select(["value", "context"]).rows()  // Returns a list of facts that require value and context. 
$facts = fact.query().select("botId").rows()               // Returns only the botId field where the facts are attached.

where(field string, operator string, value mixed) FactQuery

Purpose: sets the condition for finding facts. Several where methods are combined on a logical "AND" basis, i.e. all conditions must be met. The where method is equivalent to the andWhere(field, operator, value) method.

Arguments:

  1. field – the name of the field where the condition is specified, i.e. the first argument of the operator.
  2. operator – operator that denotes the operation to be performed on the field. See the list of available operations below.
  3. value – second argument of the operation.

Returned value: the same FactQuery object.

List of possible operations:

  1. "=" checks that field is equal to value.
  2. "!=" or "<>" checks for inequality that field is not equal to value.
  3. ">" checks if field is greater than value.
  4. "<" checks if field is less than value.
  5. ">=" checks if field is greater than or equal to value.
  6. "<=" checks if field is less than or equal to value.
  7. "^@" or "startsWith" matches the string value with the beginning of field. The search is case sensitive..
  8. "~" checks if field matches the regular expression value. The search is case sensitive.
  9. "!~" checks if field does not match the regular expression value. The search is case sensitive.
  10. "~*" checks if field matches the regular expression value. The search is case insensitive.
  11. "!~*" checks if field does not match the regular expression value. The search is case insensitive.
  12. "in" checks if field matches at least one value in the value collection.
  13. "not in" checks if field does not match all values ​​in the value collection.
// looking for facts whose context contains the substring test
 $facts = fact.query().
    select("name,value").
    where("context", "~", "^.*test.*$").
    rows()

andWhere(field string, operator string, value mixed) FactQuery

This function is equivalent to where(field, operator, value).

orWhere(field string, operator string, value mixed) FactQuery

This function is equivalent to where with the only difference that several calls to this method are combined according to the logical "OR" principle, i.e. at least one condition must be met.

where(cond FactQueryCondition) FactQuery

Purpose: specifies a complex (nested) condition. Multiple method calls are combined in a logical AND fashion. Equivalent to the andWhere(cond) method.

Arguments:

  1. cond – a FactQueryCondition object that defines a complex condition.

Returned value: the same FactQuery object.

// Searching for facts where context contains the substring test and at the same time name is equal to "word" or name begins with "on".
$facts = fact.query().
    select("name,value").
    where("context", "~", "^.*test.*$").
    andWhere(fact.cond().
        where("name", "=", "word").
        orWhere("name", "^@", "оn")).
    rows()

andWhere(cond FactQueryCondition) FactQuery

This function is equivalent to where(cond).

orWhere(cond FactQueryCondition) FactQuery

This function is equivalent to where(cond) with the only difference that several calls to this method are combined according to the logical "OR" principle, i.e. at least one condition must be met.

sortBy(fields string|Collection) FactQuery

Purpose: sets the sorting of facts by the specified fields.

Arguments:

  1. fields – a string containing a list of fields (separated by commas) that are used to sort facts or a collection that contains field names. Each field can be prefixed with "+" for ascending sorting or "-" for descending sorting. If no prefix is ​​specified, ascending sorting is used.

Returned value: the same FactQuery object. 

// Receves all the facts for the bot with double sorting:
// first in ascending order (i.e. alphabetically)
// and then by the name of the fact in descending order.
$facts = fact.query().
    select("name,value").
    where("botId", "=", @botId)
    sortBy("+context,-name"). // you can also use collections. For example, sortBy(["+context", "-name"])
    rows()

limit(limit int) FactQuery

Purpose: sets a limit on the maximum number of extracted facts.

Arguments:

  1. limit – an integer that defines the limit on the number of extracted facts.

Returned value: the same FactQuery object. 

// Retrieves first 10 facts
$facts = fact.query().
    select("name,value").
    sortBy("name").
    limit(10).
    rows()

skip(count int) FactQuery

Purpose: sets the number of facts to skip when searching.

Arguments:

  1. count – an integer that specifies the number of facts to skip.

Returned value: the same FactQuery object. 

// Skips the first 5 facts and extracts the next 10
$facts = fact.query().
    select("name,value").
    sortBy("name").
    skip(5).
    limit(10).
    rows()

one() mixed

Purpose: returns the first field of the first found fact specified by select.

Arguments: not present.

Returned value: field value.

// Retrieves the name of the first found fact
$firstFactName = fact.query().
    select("name,value").        // value is specified, but will be ignored 
    one()

column() List

Purpose: returns a list that consists of all values ​​of the first selected field of found facts.

Arguments: not present.

Returned value: list of field values.

// Retrieves a list of names of all found facts
$names = fact.query().
    select("name,value").        // value is specified, but will be ignored  
    column()

row() Map

Purpose: returns all selected fields as an associative array for the first found fact.

Arguments: not present.

Returned value: values ​​of all fields of the first fact.

// Retrieves the name and value of the first found fact
$names = fact.query().
    select("name,value").
    row()

rows() List<Map>

Purpose: returns a list of all found facts. Each fact is returned as an associative array whose keys are the fact fields and whose values ​​are the field values.

Arguments: not present.

Returned value: field values of all facts.

// Retrieves the name and value of all facts
$names = fact.query().
    select("name,value").
    rows()

Объект FactQueryCondition

Methods of this object are used to create complex nested conditions for the base facts.

where(field string, operator string, value mixed) FactQueryCondition

Similar to the where(field string, operator string, value mixed) method of the FactQuery object.

andWhere(field string, operator string, value mixed) FactQueryCondition

Similar to the andWhere(field string, operator string, value mixed) method of the FactQuery object.

orWhere(field string, operator string, value mixed) FactQueryCondition

Similar to the orWhere(field string, operator string, value mixed) method of the FactQuery object.

and(field string, operator string, value mixed) FactQueryCondition

Similar to the andWhere(field string, operator string, value mixed) method of the FactQuery object.

or(field string, operator string, value mixed) FactQueryCondition

Similar to the orWhere(field string, operator string, value mixed) method of the FactQuery object.

where(cond FactQueryCondition) FactQueryCondition

Similar to the where(cond FactQueryCondition) method of the FactQuery object.

andWhere(cond FactQueryCondition) FactQueryCondition

Similar to the andWhere(cond FactQueryCondition) method of the FactQuery object.

orWhere(cond FactQueryCondition) FactQueryCondition

Similar to the orWhere(cond FactQueryCondition) method of the FactQuery object.

and(cond FactQueryCondition) FactQueryCondition

Similar to the andWhere(cond FactQueryCondition) method of the FactQuery object.

or(cond FactQueryCondition) FactQueryCondition

Similar to the orWhere(cond FactQueryCondition) method of the FactQuery object.

Объект UserMessage

message string

Purpose: the original text of the message.

$msg = queue.last().message // $msg contains the text of the last user message

attachments List<string>

Purpose: a list of file IDs attached to the message.

$attachments = queue.first().attachments // $attachments contains a list of attachments of the first user message.

isEmpty() bool

Purpose: defines whether the message is empty.

Arguments: not present.

Returned value: true if the message is empty and false otherwise.

$isEmpty = queue.last().isEmpty() // $isEmpty contains true if the last user message is empty and false otherwise

hasAttachments() bool

Purpose: determines whether there are attachments in the message.

Arguments: not present.

Returned value: true, if the message has attachments and false otherwise.

$hasAttachments = queue.first().hasAttachments() // $hasAttachments contains true if the first user message has attachments and false otherwise

Объект Sentence

intent string

Purpose: recognized intent.

$sentence = nlu.parse("Hello John", "d926726a-5acb-4233-8c1e-ce4300921de0")
$intent = $sentence.intent   // $intent contains "greeting"

intentConfidence number

Purpose: the degree of reliability of the recognized intention (1 - unambiguous recognition, 0 - the intention is actually unrecognized).

$sentence = nlu.parse("Hello John", "d926726a-5acb-4233-8c1e-ce4300921de0")
$confidence = $sentence.intentConfidence   // $confidence contains 0.98

entities List<Tuple>

Purpose: list of recognized entities. Each element of the list contains a tuple of three elements: entity type (string), entity value (string), entity recognition confidence (number).

$sentence = nlu.parse("Hello John", "d926726a-5acb-4233-8c1e-ce4300921de0")
$entities = $sentence.entities // $entities contains [("human-name", "John", 0.96), ("time", "2023-01-09 23:30:00", 0.87)]
$first = $entities.get(0)      // $first contains ("human-name", "John", 0.96)
$type = $first.get(0)          // $type contains "human-name"