...
| Russian | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
На этой странице:
Функции общего назначенияdel(varName string)Назначение: удаление локальной или модульной переменной. Аргументы:
Возвращаемое значение: отсутствует.
Математические функцииmath.pos(num mixed) numberНазначение: фактически преобразует аргумент к числу. Эквивалент унарной операции "+". Аргументы:
Возвращаемое значение: число.
math.neg(num number) numberНазначение: меняет знак числа. Эквивалент унарной операции "-". Аргументы:
Возвращаемое значение: число со знаком обратному исходному.
math.inv(num number) numberНазначение: инверсия бит числа. Эквивалент унарной операции "~". Аргументы:
Возвращаемое значение: инвертированное число.
math.not(num number) boolНазначение: логическое отрицание числа. Эквивалент унарной операции "!". Аргументы:
Возвращаемое значение: true, если num не равно 0 и false в противном случае.
math.add(num1 number, num2 number, precision int = 12) numberНазначение: сложение чисел. Эквивалент бинарной операции "+". Аргументы:
Возвращаемое значение: сумма чисел.
math.sub(num1 number, num2 number, precision int = 12) numberНазначение: разность чисел. Эквивалент бинарной операции "-". Аргументы:
Возвращаемое значение: разность чисел.
math.mul(num1 number, num2 number, precision int = 12) numberНазначение: произведение чисел. Эквивалент бинарной операции "*". Аргументы:
Возвращаемое значение: произведение чисел.
math.div(num1 number, num2 number, precision int = 12) numberНазначение: частное чисел. Эквивалент бинарной операции "/". Аргументы:
Возвращаемое значение: частное чисел.
math.idiv(num1 number, num2 number) intНазначение: целочисленное деление чисел. Эквивалент бинарной операции "\". Аргументы:
Возвращаемое значение: целая часть частного чисел.
math.mod(num1 number, num2 number, precision int = 12) numberНазначение: остаток от деления двух чисел. Эквивалент бинарной операции "%". Аргументы:
Возвращаемое значение: остаток от деления.
math.pow(base number, power number, precision int = 12) numberНазначение: возведение числа base в степень power. Эквивалент бинарной операции "**". Аргументы:
Возвращаемое значение: результат возведения в степень.
math.sqrt(num number, precision int = 12) numberНазначение: извлечение квадратного корня. Аргументы:
Возвращаемое значение: квадратный корень либо ошибка, если число отрицательное.
math.round(num number, precision int) numberНазначение: округление числа до требуемого знака после запятой. Аргументы:
Возвращаемое значение: округлённое с заданной точностью число.
Функции для работы со строкамиstr.len(str string) intНазначение: определение длины строки в символах. Аргументы:
Возвращаемое значение: целое число, равное количеству символов в строке.
str.lower(str string) stringНазначение: преобразование символов строки в нижний регистр. Аргументы:
Возвращаемое значение: строка, все символы которой находятся в нижнем регистре.
str.upper(str string) stringНазначение: преобразование символов строки в верхний регистр. Аргументы:
Возвращаемое значение: строка, все символы которой находятся в верхнем регистре.
str.ucfirst(str string) stringНазначение: преобразование первого символа строки в верхний регистр. Аргументы:
Возвращаемое значение: строка, в которой первый символ записан в верхнем регистре.
str.lcfirst(str string) stringНазначение: преобразование первого символа строки в нижний регистр. Аргументы:
Возвращаемое значение: строка, в которой первый символ записан в нижнем регистре.
str.letter(str string, index int) stringНазначение: получение указанного символа строки. Аргументы:
Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.
str.first(str string, index int = 0) stringНазначение: получение указанного символа строки, начиная с начала строки. Аргументы:
Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.
str.last(str string, index int = 0) stringНазначение: получение указанного символа строки, начиная с конца строки. Аргументы:
Возвращаемое значение: строка, соответствующая указанному символу, либо пустая строка, если символа с такой позицией не существует.
str.concat(str1 string, str2 string) stringНазначение: объединяет две строки в одну. Аргументы:
Возвращаемое значение: новая строка, состоящая из первой строки, справа от которой добавлена вторая строка.
str.sub(str string, offset int, length int = nil) stringНазначение: возвращает подстроку строки str, начинающейся с offset символа по счету и длиной length символов. Аргументы:
Возвращаемое значение: часть str или пустая строка.
str.join(arr Collection, separator string = "") stringНазначение: объединяет элементы коллекции (кортежа, списка или ассоциативного массива) в строку. Аргументы:
Возвращаемое значение: новая строка, составленная из всех элементов коллекции отделённых между собой разделителем.
str.split(str string, separator string = "", limit int = 0) ListНазначение: разбивает строку на части, используя separator в качестве разделителя. Аргументы:
Возвращаемое значение: список подстрок, на которые была разбита строка.
str.replace(str string, search string, replace string) stringНазначение: ищет все вхождения подстроки в строке и заменяет их на заданное значение. Аргументы:
Возвращаемое значение: новая строка, в которой все search заменены на replace.
str.match(str string, pattern string) boolНазначение: выполняет проверку данной строки регулярному выражению. Аргументы:
Возвращаемое значение: возвращает true, если строка соответствует регулярному выражению и false –в противном случае.
str.distance(str1 string, str2 string) numberНазначение: вычисляет степень сходства двух строк. Аргументы:
Возвращаемое значение: возвращает число от 0 до 1 включительно, определяющее степень сходства двух строк: 1 – строки эквивалентны, 0 – строки абсолютно разные.
Функции хэшированияhash.of(text string, algo string = "md5", binary bool = false) stringНазначение: вычисляет хэш строки согласно указанному алгоритму. Аргументы:
Возвращаемое значение:возвращает строку, содержащую вычисленный хеш-код в шестнадцатеричной кодировке в нижнем регистре. Если binary задан как true, то возвращается хеш-код в виде бинарных данных. В случае ошибки (например, если указан недопустимый алгоритм хэширования) возвращает пустую строку. Допустимые значения алгоритмов хэширования:
Примечание: если третий параметр true, то передавать возвращаемое функцией значение в качестве сообщения бота или его части нельзя. Это приведёт к падению бота.
Функции кодирования/декодированияcodec.base64Encode(str string) string
Аргументы:
Возвращаемое значение: возвращает строку, закодированную в Base64.
codec.base64Decode(str string) ?string
Аргументы:
Возвращаемое значение: возвращает раскодированную строку либо nil, если закодированная строка содержит символы, не входящие в алфавит символов Base64 кодировки.
Функции для работы с датой и временемdt.add(d1 int|string, d2 int|string) stringНазначение: складывает две даты, заданные в виде строки либо как число секунд.
Аргументы:
Возвращаемое значение: возвращает новую дату и время в виде строки.
dt.sub(d1 int|string, d2 int|string) int|stringНазначение: вычисляет разность двух дат, заданных в виде строк либо количеством секунд.
Аргументы:
Возвращаемое значение: возвращает новую дату и время в виде строки либо число секунд – разность дат.
dt.format(dt int|string, format string) stringНазначение: форматирует дату согласно заданному формату. Аргументы:
Возвращаемое значение: строка даты в заданном формате. Допустимые параметры форматирования:
Примечание: если строка формата содержит символы, совпадающие с вышеперечисленными, но не являющиеся параметрами форматирования, то их следует экранировать с помощью символа обратного слэша "\".
date.nearFuture(day int) stringНазначение: возвращает ближайшую будущую к текущей дату по заданному дню. Аргументы:
Возвращаемое значение: возвращает ближайшую к day дату.
date.nearPast(day int) stringНазначение: возвращает ближайшую прошлую к текущей дату по заданному дню. Аргументы:
Возвращаемое значение: возвращает ближайшую к day дату.
date.future(day int) stringНазначение: возвращает дату, соответствующую указанному дню в следующем месяце. Аргументы:
Возвращаемое значение: дата в будущем.
date.past(day int) stringНазначение: возвращает дату, соответствующую указанному дню в прошлом месяце. Аргументы:
Возвращаемое значение: дата в прошлом.
time.nearFuture(minute int) stringНазначение: возвращает ближайшее будущее к текущему время по заданному количеству минут. Аргументы:
Возвращаемое значение: возвращает ближайшее к minute время.
time.nearPast(minute int) stringНазначение: возвращает ближайшее прошлое к текущему время по заданному количеству минут. Аргументы:
Возвращаемое значение: возвращает ближайшее к minute время.
time.future(minute int) stringНазначение: возвращает время, соответствующее указанному числу минут в следующем часе. Аргументы:
Возвращаемое значение: время в будущем.
time.past(minute int) stringНазначение: возвращает время, соответствующее указанному числу минут в прошедшем часе. Аргументы:
Возвращаемое значение: время в прошлом.
Функции по работе с очередью сообщений пользователяqueue.size() intНазначение: определение размера очереди сообщений пользователя. Аргументы: отсутствуют. Возвращаемое значение: число сообщений пользователя.
queue.last() ?UserMessageНазначение: возвращает последнее сообщение пользователя либо nil, если очередь сообщений пуста. Аргументы: отсутствуют. Возвращаемое значение: объект UserMessage или nil.
queue.first() ?UserMessageНазначение: возвращает первое сообщение пользователя либо nil, если очередь сообщений пуста. Аргументы: отсутствуют. Возвращаемое значение: объект UserMessage или nil.
queue.nth(index int) ?UserMessageНазначение: возвращает сообщение пользователя по его порядковому номеру, начиная с 1. Аргументы:
Возвращаемое значение: объект UserMessage или nil.
queue.lastNth(index int) ?UserMessageНазначение: возвращает сообщение пользователя по его порядковому номеру, считая с конца очереди. Последнее сообщение соответствует порядковому номеру 1. Аргументы:
Возвращаемое значение: объект UserMessage или nil.
Функции для работы с фактамиfact.save(context string, factName string, factValue mixed, botId string = nil, clientId string = nil)Назначение: сохраняет факт в базе фактов. Аргументы:
Возвращаемое значение: отсутствует.
fact.load(context string, factName string, botId string = nil, clientId string = nil) mixedНазначение: извлекает факт из базы фактов. Аргументы:
Возвращаемое значение: содержимое факта.
fact.delete(context string, factName string, botId string = nil, clientId string = nil)Назначение: удаляет факт из базы фактов. Аргументы:
Возвращаемое значение: отсутствует.
fact.query() FactQueryНазначение: возвращает экземпляр FactQuery для построения и выполнения запросов к базе фактов. Аргументы: отсутствуют. Возвращаемое значение: объект FactQuery.
fact.cond() FactQueryConditionНазначение: возвращает экземпляр FactQueryCondition для построения составных условий в запросах к базе фактов. Аргументы: отсутствуют. Возвращаемое значение: объект FactQueryCondition.
Функции для работы с таймеромtimer.start(time int, nodeId string) stringНазначение: запускает таймер обратного отсчёта. По истечении указанного времени бот осуществит переход на указанный узел (блок). Аргументы:
Возвращаемое значение: идентификатор таймера.
timer.stop(timerId string)Назначение: останавливает (удаляет) таймер обратного отсчёта. Аргументы:
Возвращаемое значение: отсутствует.
Функции для работы с текстом на естественном языке (NLP)nlp.parse(message string|UserMessage) SentenceНазначение: парсит текст на естественном языке. Аргументы:
Возвращаемое значение: объект Sentence,содержащий информацию о всех намерениях и сущностях исходного сообщения. Примечание: данная функция извлекает из текста только сущности. Для работы с намерениями используйте функцию nlu.parse.
nlp.join(message1 string|UserMessage, message2 string|UserMessage) SentenceНазначение: объединяет два текста на естественном языке в одно и затем парсит его. Аргументы:
Возвращаемое значение: объект Sentence,содержащий информацию о всех намерениях и сущностях объединённого сообщения.
nlp.setPerception($sentence Sentence)Назначение: позволяет установить сообщение пользователя для обработки в других узлах (блоках) схемы бота. Аргументы:
Возвращаемое значение: отсутствует.
Функции для "понимания" естественного языка.nlu.parse(text string, agentId string, timezoneOffset int = 0, version int = 1) SentencePurpose: разбор текста на естественном языке. Выявление намерений и сущностей. Arguments:
Возвращаемое значение: объект Sentence.
Функции для работы с HTTPhttp.sendRequest(url string, method string, body any = nil, headers Map = nil) ResponseНазначение: отправляет HTTP запрос на указанный URL. Аргументы:
Возвращаемое значение: объект HTTP-ответа.
http.request(url string = "", method string = "POST", body any = nil) RequestНазначение: формирует новый объект HTTP-запроса. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
Объект Requesttimeout(timeout int) RequestНазначение: задаёт максимально допустимое время запроса в секундах. Если запрос отрабатывается дольше указанного времени, то его выполнение прерывается. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
url(url string) RequestНазначение: задаёт URL запроса. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
method(method string) RequestНазначение: задаёт HTTP-метод запроса. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
body(body any) RequestНазначение: задаёт тело запроса. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP запросе.
header(header string, value string) RequestНазначение: добавляет HTTP заголовок. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP запросе.
headers(headers Map) RequestНазначение: задаёт HTTP-заголовки. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
file(fileId string, name string = "") RequestНазначение: добавляет файл для отправки по HTTP. Аргументы:
Возвращаемое значение: объект, содержащий информацию о HTTP-запросе.
send() ResponseНазначение: отправляет сформированный запрос. Возвращаемое значение: объект ответа сервера.
Объект ResponsestatusCode intНазначение: код статуса ответа.
body anyНазначение: тело ответа.
headers MapНазначение: заголовки ответа.
error stringНазначение: значение элемента error тела ответа или пустая строка, если такого элемента нет.
isError() boolНазначение: определение успешности ответа. Возвращаемое значение: возвращает true, если свойство error не пустое или код статуса больше или равен 400, иначе возвращает false.
isSuccessful() boolНазначение: определение успешности ответа. Возвращаемое значение: возвращает true, если свойство error пустое и код статуса меньше 400, иначе возвращает false.
hasHeader(header string) boolНазначение: определение наличия заголовка. Аргументы:
Возвращаемое значение: true, если заголовок с указанным именем существует, и false в противном случае.
header(header string) stringНазначение: получение значения заголовка. Аргументы:
Возвращаемое значение: значение заголовка с указанным именем или пустую строку, если такого заголовка нет.
toFile() stringНазначение: получение файла из HTTP-ответа. Возвращаемое значение: идентификатор загруженного файла.
Системные функцииsys.sleep(microseconds int)Назначение: останавливает работу бота на указанное количество микросекунд. Если количество микросекунд превышает 1 минуту, то пауза будет уменьшена до 1 минуты. Аргументы:
Возвращаемое значение: отсутствует.
Функции для работы с GPT-3gpt3.ask(text string, temperature float = 0.7) string
Аргументы:
Возвращаемое значение: ответ нейросети в виде строки.
Объект FactQueryИспользуя методы этого объекты, вы можете выполнять и строить разнообразные запросы к базе фактов. База фактов представляет собой список записей. Каждая запись представляет собой единичный факт, состоящий из следующих частей (полей):
select(fields string|Collection) FactQueryНазначение: задаёт список полей из базы фактов, значения которых следует вернуть в результате запроса. Если метод select не вызывался, то будут возвращены поля context, name и value. Аргументы:
Возвращаемое значение: тот же объект FactQuery.
where(field string, operator string, value mixed) FactQueryНазначение: задаёт условие поиска фактов. Несколько методов where объединяются по принципу логического "И". Т.е. все условия должны быть выполнены. Метод where равносилен методу andWhere(field, operator, value). Аргументы:
Возвращаемое значение: тот же объект FactQuery. Список доступных операций:
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). Аргументы:
Возвращаемое значение: тот же объект FactQuery.
andWhere(cond FactQueryCondition) FactQueryЭквивалентен where(cond). orWhere(cond FactQueryCondition) FactQueryАналогичен where(cond), с той лишь разницей, что несколько вызовов этого метода объединяются по принципу логического "ИЛИ", т.е. должно выполняться хотя бы одно условие. sortBy(fields string|Collection) FactQueryНазначение: задаёт сортирову фактов по указанным полям. Аргументы:
Возвращаемое значение: тот же объект FactQuery.
limit(limit int) FactQueryНазначение: ставит ограничение на максимальное количество извлекаемых фактов. Аргументы:
Возвращаемое значение: тот же объект FactQuery.
skip(count int) FactQueryНазначение: задаёт количество фактов, которые следует пропустить при поиске. Аргументы:
Возвращаемое значение: тот же объект FactQuery.
one() mixedНазначение: возвращает первое указанное через select поле первого найденного факта. Аргументы: отсутствуют. Возвращаемое значение: значение поля.
column() ListНазначение: возвращает список, состоящий из всех значений первого выбранного поля найденных фактов. Аргументы: отсутствуют. Возвращаемое значение: списокзначений поля.
row() MapНазначение: возвращает все выбранные поля в виде ассоциативного массива для первого найденного факта. Аргументы: отсутствуют. Возвращаемое значение: значения всех полей первого факта.
rows() List<Map>Назначение: возвращает список всех найденных фактов. Каждый факт возвращается как ассоциативный массив, ключами которого являются поля факта, а значениями – значения полей. Аргументы: отсутствуют. Возвращаемое значение: значения всех полей всех фактов.
Объект 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. Объект UserMessagemessage stringНазначение: оригинальный текст сообщения.
attachments List<string>Назначение: список идентификаторов файлов, приложенных к сообщению.
isEmpty() boolНазначение: определяет пустое ли сообщение. Аргументы: отсутствуют. Возвращаемое значение: true, если сообщение пустое, и false в противном случае.
hasAttachments() boolНазначение: определяет, есть ли вложения в данном сообщении. Аргументы: отсутствуют. Возвращаемое значение: true, если сообщение имеет вложения, и false в противном случае.
Объект Sentenceintent stringНазначение: распознанное намерение.
intentConfidence numberНазначение: степень достоверности распознанного намерения (1 – однозначное распознавание, 0 – намерение фактически нераспознанно).
entities List<Tuple>Назначение: список распознанных сущностей. Каждый элемент списка содержит кортеж из трёх элементов: тип сущности (string), значение сущности (строка), достоверность распознавания сущности (number).
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| English (US) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Якорь | | Topp | Topp | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| CSS Stylesheet |
|---|
.topptop-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; } .topptop-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:
Оглавление class bpl
| Предупреждение | ||
|---|---|---|
| ||
BPL operations work only in chats and incoming calls. To test scenarios with BPL operations, use chats in the widget.
|
General functions
del(varName string)
Purpose: deletion of a local or module variable.
Arguments:
- 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 |
Math functions
math.pos(num mixed) number
Purpose: converts the argument to a number. The function acts as equivalent to the unary "+" operator.
Arguments:
- 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:
- num – an arbitrary number whose sign changes to the opposite.
Returned value: the samenumber 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:
- num – an arbitrary number with invertible bits.
Returned value: inverted number.
| Блок кода | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||
$a = math.inv(5) // $a is equal to 3 $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:
- 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:
- num1 – the first part
- num2 – the second part.
- precision – the accuracy of calculation, the number of digits after the decimal point. The default value is 12. The maximum value is 100.
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:
- num1 – minuend.
- num2 – subtrahend.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- num1 – first multiplier.
- num2 – second multiplier.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- num1 – dividend.
- num2 – divider.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- num1 – dividend.
- 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:
- num1 – dividend.
- num2 – divider.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- base – base.
- power – degree.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- num – the number from which the root is taken.
- precision – calculation accuracy, the number of digits after the decimal point. The default value is 12, the maximum is 100.
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:
- num – number to round.
- precision – calculation accuracy, the number of digits after the decimal point. The maximum is 100.
Returned value: number rounded with a given precision.
| Блок кода | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||
$a = math.round(3.14159265358979323846264338327950288419716, 17) // $a is equal to 3.14159265358979324 $a = math.round(3.14159265358979323846264338327950288419716, 2) // $a is equal to 3.14 $a = math.round(3.14159265358979323846264338327950288419716, 0) // $a is equal to 3 |
Functions for working with strings
str.len(str string) int
Purpose: determining the length of the string in characters.
Arguments:
- 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:
- 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:
- 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:
- 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:
- 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:
- str – string whose character is to be retrieved.
- 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:
- str – string whose character is to be retrieved.
- 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:
- str – string whose character is to be retrieved.
- 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:
- str1 – string to be concatenated.
- 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:
- str – original string.
- 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. - 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:
- arr – collection of items to concatenate.
- 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:
- str – string to split.
- separator – separator. If it is equal to an empty string, then splitting is carried out character by character.
- 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:
- str – string to be converted.
- search – substring that is searched for in the source string.
- 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:
- str – string to match against the regular expression.
- pattern – pattern of regular expression.
Returned value: returns true if the string matches the regular expression, otherwise returns false.
| HTML |
|---|
<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. |
| HTML |
|---|
<a href="http://www.shtogrin.com/library/web/pcre/" target="_blank">Link to documentation and examples of regular expressions.</a> |
| HTML |
|---|
<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:
- str1 – first line to compare.
- 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.
| HTML |
|---|
<b>Note:</b> This function actually calculates the <a href="https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance" target="_blank">Damerau-Levenshtein distance.</a> |
| Блок кода | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||
$d = str.distance("", "abc") // $d is equal to 0
$d = str.distance("Yes", "yes") // $d is equal to 1
$d = str.distance("close", "open") // $d is equal to 0.714
$d = str.distance("Yes, correct", "close") // $d is equal to 0.625
$d = str.distance("terribly oblique bananas", "chew coconuts, eat bananas") // $d is equal to 0.714
$d = str.distance("went crazy from the wound, "He became a pusurmany") // $d is equal to 0.45
$d = str.distance("hedgehog", "deoxyribonucleic acid") // $d is equal to 0.033 |
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:
- text – arbitrary string to hash.
- algo – the name of the hash algorithm. The default algorithm is md5.
- 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
| HTML |
|---|
<b>Purpose:</b> encodes the given string into <a href="https://en.wikipedia.org/wiki/Base64" target="_blank">Base64</a>. |
Arguments:
- 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
| HTML |
|---|
<b>Purpose:</b> decodes the provided <a href="https://en.wikipedia.org/wiki/Base64" target="_blank">Base64</a> string. |
Arguments:
- 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:
- d1 – a string that represents a date in one of the allowed formats or an integer that corresponds to the number of seconds.
- 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-01 00:00:00", "2022-01-02 00:00:00") // $d contains string "2022-01-03 00: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:
- d1 – a string that represents a date in one of the allowed formats or an integer that corresponds to the number of seconds.
- 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 string | Description | Example of returned value |
|---|---|---|
| Year | ||
| y | Full numeric representation of the year (at least 4 digits) | 1999, 2012, 10208 |
| yy | The 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 |
| MM | Number of the month with leading zero | from 01 to 12 |
| Day | ||
| d | Day of the month without leading zero | from 1 to 31 |
| dd | Day of the month, 2 digits with a leading zero | from 01 to 31 |
| Hour | ||
| h | Hours in 12-hour format without leading zero | from 01 to 12 |
| hh | Hours in 12-hour format with leading zero | from 01 to 12 |
| H | Hours in 24-hour format without leading zero | from 0 to 23 |
| HH | Hours in 24-hour format with leading zero | from 0 to 23 |
| Minutes | ||
| m | Minutes without leading zero | from 0 to 59 |
| mm | Minutes with leading zero | from 0 to 59 |
| Seconds | ||
| s | Seconds without a leading zero | from 0 to 59 |
| ss | Seconds with a leading zero | from 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:
- 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.
Аргументы:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- context – string that specifies the context where the fact exists.
- factName – string that specifies the name of the fact.
- factValue – any value that defines the contents of a fact.
- botId – bot ID. Not specified by default.
- 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:
- context – a string that specifies the context where the fact exists.
- factName – a string that specifies the name of the fact.
- botId – bot ID. Not specified by default.
- 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:
- context – a string that specifies the context where the fact exists.
- factName – a string that specifies the name of the fact.
- botId – bot ID. Not specified by default.
- 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:
- time – time in seconds.
- 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:
- timerId – timer ID
Returned value: not present.
| Блок кода | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||
$timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2") timer.stop($timerId) // stops (deletes) the timer. |
Functions for working with text in natural language (NLP)
nlp.parse(message string|UserMessage) Sentence
Purpose: parses natural language text.
Arguments:
- 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:
- message1 – text in natural language or a UserMessage object.
- 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:
- 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:
- text –text for parsing.
- agentId – ID (uuid) of the agent (neural network) that parses the text.
- timezoneOffset – the time zone offset that is necessary to correctly detect temporary entities. The default offset is UTC.
- version – NLU version. Can be number 1 or 2.
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:
- url – the URL that the request will be sent to.
- method – HTTP method. Possible variants: GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS.
- body – request body. Can be represented as a scalar value, a list, or an associative array.
- 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:
- url – URL string.
- method – name of HTTP method.
- 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:
- 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:
- 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:
- 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:
- 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:
- header – name of HTTP header.
- 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:
- 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:
- fileId – ID of the previously uploaded file.
- 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:
- 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:
- 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:
- 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
| HTML |
|---|
<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:
- 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 |
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:
- 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:
- field – the name of the field where the condition is specified, i.e. the first argument of the operator.
- operator – operator that denotes the operation to be performed on the field. See the list of available operations below.
- value – second argument of the operation.
Returned value: the same FactQuery object.
List of possible operations:
- "=" checks that field is equal to value.
- "!=" or "<>" checks for inequality that field is not equal to value.
- ">" checks if field is greater than value.
- "<" checks if field is less than value.
- ">=" checks if field is greater than or equal to value.
- "<=" checks if field is less than or equal to value.
- "^@" or "startsWith" matches the string value with the beginning of field. The search is case sensitive..
- "~" checks if field matches the regular expression value. The search is case sensitive.
- "!~" checks if field does not match the regular expression value. The search is case sensitive.
- "~*" checks if field matches the regular expression value. The search is case insensitive.
- "!~*" checks if field does not match the regular expression value. The search is case insensitive.
- "in" checks if field matches at least one value in the value collection.
- "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:
- 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:
- 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:
- 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:
- 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" |