| CSS Stylesheet |
|---|
.top-button {
background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/baseline_keyboard_arrow_up_white_18dp.png) !important;
background-position: center;
background-color: #47a7f5 !important;
background-repeat: no-repeat;
box-shadow: -1px 1.5px 3px #999;
color: #47a7f5 !important;
border-radius:50px !important;
position: fixed;
bottom: 45px;
left: 93.5%;
width: 50px;
height: 50px !important;
font-size: 12px !important;
padding: 14.5px !important;
z-index: 2;
}
.top-button:hover{
background-color: #65b9ff !important;
color: #65b9ff !important;
}
.page-header{
background-color: #232838;
background-repeat: no-repeat;
background-position: center;
width: auto;
height: 100px;
background-image: url(https://confluence.twin24.ai/download/attachments/23986188/logo_twin-02.png);
background-size: 10em;
color: #fff;
font-size: 20px;
padding: 20px;
}
.page-footer{
background-color: #232838;
background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/decorated-pattern-dark.png);
width: auto;
height: 10px;
color: #fff;
text-align: end;
font: small-caption;
padding-inline-end: 30px;
padding-top: 200px;
padding-bottom: 30px;
}
.page-headline{
background-image: url(https://confluence.twin24.ai/download/thumbnails/23986188/Solid256dot8_2changed.png);
background-repeat: no-repeat;
background-position-x: -227px;
background-position-y: center;
padding: 20px;
background-color: #007bff;
width: auto;
height: 10px;
color: #fff;
text-align: center;
font: caption;
font-weight: 600;
}
.tabs-menu{
padding-left: 85% !important;
} |
On this page: | Предупреждение |
|---|
| BPL operations work only in chats and incoming calls. To test scenarios with BPL operations, use chats in the widget. Also see Creating a test widget. |
General functionsdel(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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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 functionsmath.pos(num mixed) numberPurpose: converts the argument to a number. The function acts as quivalent to the unary "+" operator. Arguments: - num – arbitrary value that will be converted to a number.
Returned value: number. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $a = math.pos(true) // $a will be equal toо 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) numberPurpose: changes the sign of a number. The function acts as quivalent to the unary operation "-". Arguments: - num – an arbitrary number whose sign changes to the opposite.
Returned value: the samenumber with the opposite sign. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: bit number inversion. This function is equivalent to the unary operator "~". Arguments: - num – an arbitrary number with invertable bits.
Returned value: inverted number. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $a = math.inv(5) // $a is equal to 3
$a = ~5 // same as previous line |
math.not(num number) boolPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) intPurpose: integer division of numbers. This function is equivalent to the binary operation "\". Arguments: - num1 – dividend.
- num2 – divider.
Returned value: integer part of private numbers. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: raising the number base to the power 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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 stringsstr.len(str string) intPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "Some string"
$len = str.len($str) // $len will contain 15 |
str.lower(str string) stringPurpose: convertion of string characters to lower case. Arguments: - str – string to be converted.
Returned value: a string with all characters in lowercase. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "StRiNg"
$lower = str.lower($str) // $lower will contain "string" |
str.upper(str string) stringPurpose: convertion of string characters to uppercase. Arguments: - str – string to be converted.
Returned value: a string with all characters in uppercase. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "StRiNg"
$upper = str.upper($str) // $lower will contain "STRING" |
str.ucfirst(str string) stringPurpose: convertion 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. | Блок кода |
|---|
| language | py |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = str.ucfirst("строка") // $str будет содержать "Строка" |
str.lcfirst(str string) stringPurpose: convertion 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = str.ucfirst("String") // $str will contain "string" |
str.letter(str string, index int) stringPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "Word"
$firstLetter = str.letter($str, 0) // First character
$lastLetter = str.letter($str, -1) // Last character |
str.first(str string, index int = 0) stringPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "Word"
$firstLetter = str.first($str) // First character
$secondLetter = str.first($str, 1) // Last character |
str.last(str string, index int = 0) stringPurpose: 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: строка соответствующая указанному символу, либо пустая строка если символа с такой позицией не существует. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str = "Слово"
$lastLetter = str.last($str) // Последняя буква
$penultLetter = str.last($str, 1) // Предпоследняя буква |
str.concat(str1 string, str2 string) stringPurpose: concatenates two strings into one. Arguments: - str1 – string to be concatenated.
- str2 – string to be concatenated with.
Returned value: a new line that cosists of the first line to the right of which the second line is added. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $str1 = "one"
$str2 = "two"
$str = str.concat($str1, $str2) // $str will contain "onetwo" |
str.sub(str string, offset int, length int = nil) stringPurpose: 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sub = str.sub("abcdef", 1) // $sub равен bcdef
$sub = str.sub("abcdef", 1, 3) // $sub равен bcd
$sub = str.sub("abcdef", 0, 4) // $sub равен abcd
$sub = str.sub("abcdef", 0, 8) // $sub равен abcdef
$sub = str.sub("abcdef", -1, 1) // $sub равен f
$sub = str.sub("abcdef", -1) // $sub равен f
$sub = str.sub("abcdef", -2) // $sub равен ef
$sub = str.sub("abcdef", -3, 1) // $sub равен d
$sub = str.sub("abcdef", 0, -1) // $sub равен abcde
$sub = str.sub("abcdef", 2, -1) // $sub равен cde
$sub = str.sub("abcdef", 4, -4) // $sub равен пустой строке
$sub = str.sub("abcdef", -3, -1) // $sub равен de |
str.join(arr Collection, separator string = "") stringPurpose: 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline |
|---|
| linenumbers | true |
|---|
| 1 | | title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $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) ListPurpose: 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $letters = str.split("abcdef") // returnes a list of letters in a word
$words = str.split("one two three", " ") // returnes a list of words
$words = str.split("one two three", " ", 1) // words contains ["one", "two three"] |
str.replace(str string, search string, replace string) stringPurpose: 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 all cccurences of "search" are replaced with "replace". | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $str = str.replace("mother washed frame", "frame", "Dasha") // $str содержит "mother washed Dasha" |
str.match(str string, pattern string) boolPurpose: 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. Note: Perl Compatible Regular Expressions (PCRE) are used as regular expressions. Link to documentation and examples of regular expressions. Online regular expression editor. | Блок кода |
|---|
| language | php |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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) numberPurpose: 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. Note: This function actually calculates the Damerau-Levenshtein distance. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $d = str.distance("", "abc") // $d is equal to 0
$d = str.distance("Да", "да") // $d is equal to 1
$d = str.distance("корыто", "открыто") // $d is equal to 0.714
$d = str.distance("Да, верно", "таверна") // $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 functionshash.of(text string, algo string = "md5", binary bool = false) stringPurpose: 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $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 functionscodec.base64Encode(str string) stringPurpose: encodes the given string into Base64. Arguments: - str – arbitrary string to encode.
Returned value: returns a string encoded in Base64. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $encoded = codec.base64Encode("Привет!") // $encoded will contain string "0J/RgNC40LLQtdGCIQ==" |
codec.base64Decode(str string) ?stringPurpose: decodes the provided Base64 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $decoded = codec.base64Decode("0J/RgNC40LLQtdGCIQ==") // $decoded will contain string "Hello!"
$failed = codec.base64Decode("Привет!") // $failed will be equal to nil |
Date and Time Functionsdt.add(d1 int|string, d2 int|string) stringPurpose: 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline |
|---|
| linenumbers | true |
|---|
| 1 | | title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $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|stringPurpose: 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline |
|---|
| linenumbers | true |
|---|
| 1 | | title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $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") // Thisa 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 |
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 "\". | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $dt = dt.format('2022-12-20 08:34:05', 'y.MM.dd h-mm-ss') // $dt будет содержать строку "22.12.20 8-34-05"
$dt = dt.format('16:30:47', '\Hour\s an\d \minute\s: HH/mm') // $dt будет содержать строку "Hours and minutes: 16/30" |
date.nearFuture(day int) stringPurpose: 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: возвращает ближайшую к day датуreturns the closest date to day. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| // Допустим сейчас 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) stringPurpose:возвращает ближайшую прошлую к текущей дату по заданному дню 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: возвращает ближайшую к day датуreturns the closest date to day. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| linenumbers | true |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| // Допустим сейчас 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) stringPurpose:возвращает дату соответствующую указанному дню в следующем месяце 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | Usage example |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| // Допустим сейчас 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) stringPurpose:возвращает дату соответствующую указанному дню в прошлом месяце returns the date that corresponds to the specified day in the previous month. Аргументы: - day – число дней для определения даты в прошломnumber of days to determine a date in the past.
Returned value: дата в прошломdate in the past. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| // Допустим сейчас 2022-12-20
$d = date.past(25) // $d содержит 2022-11-25
$d = date.past(10) // $d содержит 2022-11-10 |
time.nearFuture(minute int) stringPurpose:возвращает ближайшее будущее к текущему время по заданному количеству минут 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: возвращает ближайшее к minute времяreturns the time closest to minute. | Блок кода |
|---|
| language | powershellphp |
|---|
| theme | DJango |
|---|
| linenumbers | true |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| // Допустим сейчас 23:30:00
$t = time.nearFuture(45) // $t содержит 23:45:00
$t = time.nearFuture(15) // $t содержит 00:15:00 |
time.nearPast(minute int) stringPurpose:возвращает ближайшее прошлое к текущему время по заданному количеству минут returns the nearest past to the current time for the specofoed number of minutes. Arguments: - minute – число минут для определения ближайшего в прошлом времениnumber of minutes to determine the nearest past time.
Returned value: возвращает ближайшее к minute времяreturns the time closest to minute. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| // Допустим сейчас 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) stringPurpose:возвращает время соответствующее указанному числу минут в следующем часе 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| linenumbers | true |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| // Допустим сейчас 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) stringPurpose:возвращает время соответствующее указанному числу минут в прошедшем часе 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| // Допустим сейчас 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() intPurpose: определение размера очереди сообщений пользователя determines the size of the user message queue. Arguments: отсутствуют not present. Returned value: число сообщений пользователяnumber of user messages. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $messageCount = queue.size() // $messageCount содержитcontains число сообщений пользователя за всё время диалогаthe number of user messages for the entire dialog |
queue.last() ?UserMessagePurpose: возвращает последнее сообщение пользователя либо nil, если очередь сообщений пустаreturns the last user message or nil if the message queue is empty. Arguments: отсутствуют not present. Returned value: объект UserMessage или object or nil. | Блок кода |
|---|
| language | py |
|---|
| theme | DJango |
|---|
| firstline |
|---|
| linenumbers | true |
|---|
| 1 | | title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $lastMessage = queue.last() // $lastMessage contains содержитthe последнееlast наuser данныйmessage моментin сообщениеa пользователяdialog |
queue.first() ?UserMessagePurpose:возвращает первое сообщение пользователя либо nil, если очередь сообщений пуста returns the first user message or nil if the message queue is empty. Arguments: отсутствуют not present. Returned value: объект UserMessage или object or nil. | Блок кода |
|---|
| language | py |
|---|
| theme | DJango |
|---|
| linenumbers | true |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $firstMessage = queue.first() // $firstMessage содержитcontains первоеthe сообщениеfirst пользователяuser заmessage всёin времяa диалогаdialog |
queue.nth(index int) ?UserMessagePurpose:возвращает сообщение пользователя по его порядковому номеру, начиная с 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| linenumberstitle | trueUsage example |
|---|
| collapselinenumbers | true |
|---|
| $message = queue.nth(1) // $message contains the содержитfirst первоеuser сообщениеmessage пользователя
$message = queue.nth(5) // $message содержит пятое сообщение пользователяcontains the fifth user message |
queue.lastNth(index int) ?UserMessagePurpose: возвращает сообщение пользователя по его порядковому номеру считая с конца очереди. Последнее сообщение соответствует порядковому номеру 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. | Блок кода |
|---|
| language | pyphp |
|---|
| theme | DJango |
|---|
| firstline |
|---|
| linenumbers | true |
|---|
| 1 | | title | Usage example |
|---|
| linenumberscollapse | true |
|---|
| $message = queue.lastNth(1) // $message содержитcontains the последнееlast сообщениеuser пользователяmessage
$message = queue.lastNth(5) // $message содержитcontains пятоеthe сfifth конца очереди сообщение пользователя | Функции для работы с фактамиFunctions for working with factsfact.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 specidies 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| 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) mixedPurpose: извлекает факт из базы фактов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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| 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 existscontext – строка определяющая контекс в рамках которого существует факт.
- 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. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| 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() FactQueryPurpose: возвращает экземпляр FactQuery для построения и выполнения запросов к базе фактовreturns a FactQuery instance for working with the fact database. Arguments: отсутствуютnot present. Returned value: объект FactQuery object. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | truephp |
|---|
| // Добавили пару фактов в базу 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() FactQueryConditionPurpose: возвращает экземпляр FactQueryCondition для построения составных условий в запросах к базе фактовreturns an instance of FactQueryCondition for creating complex conditions when working with the fact database. Arguments: отсутствуютnot present. Returned value: объект FactQueryCondition object. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // 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.start(time int, nodeId string) stringPurpose: запускает таймер обратного отсчёта. По истечении указанного времени бот осуществит переход на указанный узел (блок). Arguments: - time – время в секундах.
- nodeId – идентификатор блока для перехода после завершения отсчёта.
Returned value: идентификатор таймера. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2") // $timerId содержит уникальный идентификатор таймера на 60 секунд |
timer.stop(timerId string)Purpose: останавливает (удаляет) таймер обратного отсчёта. Arguments: - timerId – идентификатор таймера.
Returned value: отсутствует. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $timerId = timer.start(60, "760b9732-4bfb-4846-a348-faae5138fcb2")
timer.stop($timerId) // останавливаем (удаляем) таймер |
Функции для работы с текстом на естественном языке (NLP)nlp.parse(message string|UserMessage) SentencePurpose: парсит текст на естественном языке. Arguments: - message – текст на естественном языке или объект UserMessage.
Returned value: объект Sentence содержащий информацию о всех намерениях и сущностях исходного сообщения. Примечание: данная функция извлекает из текста только сущности. Для работы с намерениями используйте функцию nlu.parse | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlp.parse(queue.first()) // парсим первое сообщение пользователя |
nlp.join(message1 string|UserMessage, message2 string|UserMessage) SentencePurpose: объединяет два текста на естественном языке в одно и затем парсит его. Arguments: - message1 – текст на естественном языке или объект UserMessage.
- message2 – текст на естественном языке или объект UserMessage.
Returned value: объект Sentence содержащий информацию о всех намерениях и сущностях объединённого сообщения. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) // объединяем предпоследнее и последнее сообщения пользователя и затем парсим его |
nlp.setPerception($sentence Sentence)Purpose: позволяет установить сообщение пользователя для обработки в других узлах (блоках) схемы бота. Arguments: - sentence – объект Sentence содержащий информацию о намерениях и сущностях некоторого сообщения.
Returned value: отсутствует. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlp.join(queue.lastNth(2), queue.lastNth(1)) // объединяем предпоследнее и последнее сообщения пользователя и затем парсим его
nlp.setPerception($sentence) // Теперь остальные узлы схемы будут работать с cообщением $sentence |
Функции для "понимания" естественного языка.nlu.parse(text string, agentId string, timezoneOffset int = 0, version int = 1) SentencePurpose: разбор текста на естественном языке. Выявление намерений и сущностей. Arguments: - text –текст для разбора.
- agentId – идентификатор (uuid) агента (нейросети) производящего разбор текста.
- timezoneOffset – смещение временной зоны, необходимое для правильного выявления временных сущностей. По умолчанию используется смещение для UTC.
- version – версия NLU. Может быть числом 1 или 2.
Returned value: объект Sentence. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlu.parse("Доброе утро Вася!", "d926726a-5acb-4233-8c1e-ce4300921de0") |
Функции для работы с HTTPhttp.sendRequest(url string, method string, body any = nil, headers Map = nil) ResponsePurpose: отправляет HTTP запрос на указанный URL. Arguments: - url – URL адрес на который будет оправлен запрос.
- method – HTTP метод. Допустимые значения: GET, POST, PUT, DELETE, PATCH, HEAD и OPTIONS.
- body – тело запроса. Может быть представлено скалярным значением, списком или ассоциативным массивом.
- headers – HTTP заголовки запроса. По умолчанию устанавливается заголовок Content-Type: application/json.
Returned value: объект HTTP ответа. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| // Выполняем запрос на получение списка юзеров
$response = http.sendRequest("https://iam.twin24.ai/api/v1/users", "GET", {"limit": 15, "offset": 5}, {"Authorization": "Bearer authToken"})
// Извлекаем информацию о запросе
$statusCode = $response.statusCode
$body = $response.body
$headers = $response.headers
$error = $response.error |
http.request(url string = "", method string = "POST", body any = nil) RequestPurpose: формирует новый объект HTTP запроса. Arguments: - url – строка URL.
- method – название HTTP метода.
- body – содержимое тела запроса.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request("https://some.url", "POST", {"param1": 123, "param2": true}).
headers({"Content-Type": "application/json"}).
timeout(300).
send() |
Объект Requesttimeout(timeout int) RequestPurpose: задаёт максимально допустимое время запроса в секундах. Если запрос отрабатывает дольше указанного времени, то его выполнение прерывается. Arguments: - timeout – допустимое время запроса в секундах.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request("https://some.url", "GET").
timeout(300).
send() |
url(url string) RequestPurpose: задаёт URL запроса. Arguments: - url – строка URL.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request().
url("http://some.url?p1=v1&p2=v2").
method("GET").
send() |
method(method string) RequestPurpose: задаёт HTTP метод запроса. Arguments: - method – название HTTP метода.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| | Блок кода |
|---|
| $response = http.request().
url("http://some.url?p1=v1&p2=v2").
method("GET").
send() |
body(body any) RequestPurpose: задаёт тело запроса. Arguments: - body – тело запроса.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request().
url("http://some.url?p1=v1&p2=v2")
method("PUT").
body("some body").
send() |
Purpose: добавляет HTTP заголовок. Arguments: - header – название HTTP заголовка.
- value – значение HTTP заголовка.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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() |
Purpose: задаёт HTTP заголовки. Arguments: - headers – HTTP заголовки.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $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 = "") RequestPurpose: добавляет файл для отправки по HTTP. Arguments: - fileId – идентификатор ранее загруженного файла.
- name – название параметра запроса. Если параметр не задан, то его имя будет совпадать с идентификатором файла.
Returned value: объект содержащий информацию о HTTP запросе. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request().
url("http://some.url").
method("POST").
header("Content-Type", "multipart/form-data").
file($fileId, "file").
send() |
send() ResponsePurpose: отправляет сформированный запрос. Returned value: объект ответа сервера. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.request("http://some.url?p1=v1&p2=v2", "PUT", "some body").
headers({"header1": "...", "header2": "...").
send() |
Объект ResponsestatusCode intPurpose: код статуса ответа. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$code = $response.statusCode |
body anyPurpose: тело ответа. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$body = $response.body |
Purpose: заголовки ответа. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$headers = $response.headers |
error stringPurpose: значение элемента error тела ответа или пустая строка, если такого элемента нет. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$error = $response.error |
isError() boolPurpose: определение успешности ответа. Returned value: возвращает true, если свойство error не пустое или код статуса больше или равен 400, иначе возвращает false. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isError = $response.isError() |
isSuccessful() boolPurpose: определение успешности ответа. Returned value: возвращает true, если свойство error пустое и код статуса меньше 400, иначе возвращает false.. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| | Блок кода |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$isSuccessful = $response.isSuccessful() |
Purpose: определение наличия заголовка. Arguments: - header – название заголовка.
Returned value: true, если заголовок с указанным именем существует и false в противном случае. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$hasContentType = $response.hasHeader("Content-Type") |
Purpose: получение значения заголовка. Arguments: - header – название заголовка.
Returned value: значение заголовка с указанным именем или пустую строку, если такого заголовка нет. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url?p1=v1&p2=v2", "PUT", "some body")
$contentType = $response.header("Content-Type") |
toFile() stringPurpose: получение файла из HTTP ответа. Returned value: идентификатор загруженного файла. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $response = http.sendRequest("http://some.url", "GET")
$fileId = $response.toFile() |
Системные функцииsys.sleep(microseconds int)Purpose: останавливает работу бота на указанное количество микросекунд. Если количество микросекунд превышает 1 минуту, то пауза будет уменьшена до 1 минуты. Arguments: - microseconds – число микросекунд паузы.
Returned value: отсутствует. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| sys.sleep(3_000_000) // Пауза в 3 секунды |
Функции для работы с GPT-3gpt3.ask(text string) stringPurpose: отправляет сообщение в нейросеть ChatGPT3 и возвращает её ответ. Arguments: - text – запрос к нейросети на русском языке.
Returned value: ответ нейросети в виде строки. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $answer = gpt3.ask("Есть ли жизнь на Марсе?") // В $answer будет ответ нейросети на заданный вопрос |
Объект FactQueryИспользуя методы этого объекты вы можете выполнять и строить разнообразные запросы к базе фактов. База фактов представляет собой список записей. Каждая запись представляет собой единичный факт состоящий из следующих частей (полей): - Контекст (context). Произвольная строка длина которой не превышает 255 символов. Обозначает некоторую предметную область в рамках которой существует факт. Может участвовать в поиске.
- Имя факта (name). Произвольная строка длина которой не превышает 255 символов. Служит для идентификации факта в заданном контексте. Может участвовать в поиске.
- Значение факта (value). Любое значение. Это собственно и есть та информация которую мы трактуем как факт. Не может участвовать в поиске (технически может, но результат недетерминирован).
- Идентификатор бота (botId). Может быть задан при сохранении факта с целью привязки факта к боту. Может участвовать в поиске.
- Идентификатор клиента (clientId). Может быть задан при сохранении факта с целью привязки факта к клиенту. Может участвовать в поиске.
select(fields string|Collection) FactQueryPurpose: задаёт список полей из базы фактов значения которых следует вернуть в результате запроса. Если метод select не вызыался, то будут возвращены поля context,name и value. Arguments: - fields – строка содержащая список неободимых полей разделённых запятой либо коллекция этих полей.
Returned value: тот же объект FactQuery. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $facts = fact.query().rows() // select не вызван возвращаем все поля.
$facts = fact.query().select(["value", "context"]).rows() // Возвращаем список фактов для которых нам нужны только value и context.
$facts = fact.query().select("botId").rows() // Возвращаем только поле botId к которым привязаны факты. |
where(field string, operator string, value mixed) FactQueryPurpose: задаёт условие поиска фактов. Несколько методов where объединяются по принципу логического "И", т.е. все условия должны быть выполнены. Метод where равносилен методу andWhere(field, operator, value). Arguments: - field – название поля для которого задаётся условие, т.е. первый аргумент операции operator.
- operator – оператор обозначающий операцию выполняющуюся над field. Список доступных операций смотри ниже.
- value – второй аргумент операции.
Returned value: тот же объект FactQuery. Список доступных операций: - "=" проверка, что field равно value.
- "!=" или "<>" проверка на неравенство, что field не равно value.
- ">" проверяет, что field больше value.
- "<" проверяет, что field меньше value.
- ">=" проверяет, что field больше или равно value.
- "<=" проверяет, что field меньше или равно value.
- "^@" или "startsWith" ищет совпадение строки value с началом field. Поиск регистрозависимый.
- "~" проверяет соответствие field регулярному выражению value. Поиск регистрозависимый.
- "!~" проверяет несоотвествие field регулярному выражению value. Поиск регистрозависимый.
- "~*" проверяет соответствие field регулярному выражению value. Поиск регистронезависимый.
- "!~*" проверяет несоотвествие field регулярному выражению value. Поиск регистронезависимый.
- "in" проверяет совпадение field хотя бы с одним значением в коллекции value.
- "not in" проверяет несовпадение field со всеми значениями из коллекции value.
| Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Ищем факты у которых context содержит подстроку test
$facts = fact.query().
select("name,value").
where("context", "~", "^.*test.*$").
rows() |
andWhere(field string, operator string, value mixed) FactQueryЭквивалентен where(field, operator, value). orWhere(field string, operator string, value mixed) FactQueryАналогичен where, с той лишь разницей, что несколько вызовов этого метода объединяются по принципу логического "ИЛИ", т.е. должно выполняться хотя бы одно условие. where(cond FactQueryCondition) FactQueryPurpose: задаёт сложное (вложенное) условие. Несколько вызвов метода объединяются по принципу логического "И". Эквивалентен методу andWhere(cond). Arguments: - cond – объект FactQueryCondition определяющий сложносоставное условие.
Returned value: тот же объект FactQuery. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Ищем факты у которых context содержит подстроку test и при этом name равен "слово" или name начинается на "оп".
$facts = fact.query().
select("name,value").
where("context", "~", "^.*test.*$").
andWhere(fact.cond().
where("name", "=", "слово").
orWhere("name", "^@", "оп")).
rows() |
andWhere(cond FactQueryCondition) FactQueryЭквивалентен where(cond) orWhere(cond FactQueryCondition) FactQueryАналогичен where(cond), с той лишь разницей, что несколько вызовов этого метода объединяются по принципу логического "ИЛИ", т.е. должно выполняться хотя бы одно условие. sortBy(fields string|Collection) FactQueryPurpose: задаёт сортирову фактов по указанным полям. Arguments: - fields – строка содержащая список полей (через запятую) по которым следует отсортировать факты либо коллекция содержащая названия полей. Каждое поле может содержать префикс "+" для сортировки по возрастанию или "-" для сортировки по убыванию. Если префикс не указан, то используется сортировка по возрастанию.
Returned value: тот же объект FactQuery. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Получаем все факты для бота с двойной сортировкой:
// сначала по контексту по возрастанию (т.е. в алфавитном порядке)
// и далее по имени факта по убыванию.
$facts = fact.query().
select("name,value").
where("botId", "=", @botId)
sortBy("+context,-name"). // можно также использовать коллеции. Например, sortBy(["+context", "-name"])
rows() |
limit(limit int) FactQueryPurpose: ставит ограничение на максимальное количество извлекаемых фактов. Arguments: - limit – целое число определяющее лимит на количество извлекаемых фактов.
Returned value: тот же объект FactQuery. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Получаем первые 10 фактов
$facts = fact.query().
select("name,value").
sortBy("name").
limit(10).
rows() |
skip(count int) FactQueryPurpose: задаёт количество фактов которые следует пропустить при поиске. Arguments: - count – целое число определяющее количество фактов для пропуска.
Returned value: тот же объект FactQuery. . | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| | Блок кода |
|---|
| // Пропускаем 5 первых фактов и извлекаем следующие 10
$facts = fact.query().
select("name,value").
sortBy("name").
skip(5).
limit(10).
rows() |
one() mixedPurpose: возвращает первое указанное через select поле первого найденного факта. Arguments: отсутствуют. Returned value: значение поля. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Извлекает имя первого найденного факта
$firstFactName = fact.query().
select("name,value"). // value хоть и указано, но будет проигнорировано
one() |
column() ListPurpose: возвращает список состоящий из всех значений первого выбранного поля найденных фактов. Arguments: отсутствуют. Returned value: списокзначений поля. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Извлекает список имён всех найденных фактов
$names = fact.query().
select("name,value"). // value хоть и указано, но будет проигнорировано
column() |
row() MapPurpose: возвращает все выбранные поля в виде ассоциативного массива для первого найденного факта. Arguments: отсутствуют. Returned value: значения всех полей первого факта. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Извлекает имя и значение первого найденного факта
$names = fact.query().
select("name,value").
row() |
rows() List<Map>Purpose: возвращает список всех найденных фактов. Каждый факт возвращается как ассоциативный массив ключами которого являются поля факта, а значениями - значения полей. Arguments: отсутствуют. Returned value: значения всех полей всех фактов. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| // Извлекает имя и значение всех фактов
$names = fact.query().
select("name,value").
rows() |
Объект FactQueryConditionИспользуйте методы этого объекта чтобы строить сложные вложенные условия к базе фактам. where(field string, operator string, value mixed) FactQueryConditionАналогичен методу where(field string, operator string, value mixed) объекта FactQuery. andWhere(field string, operator string, value mixed) FactQueryConditionАналогичен методу andWhere(field string, operator string, value mixed) объекта FactQuery. orWhere(field string, operator string, value mixed) FactQueryConditionАналогичен методу orWhere(field string, operator string, value mixed) объекта FactQuery. and(field string, operator string, value mixed) FactQueryConditionАналогичен методу andWhere(field string, operator string, value mixed) объекта FactQuery. or(field string, operator string, value mixed) FactQueryConditionАналогичен методу orWhere(field string, operator string, value mixed) объекта FactQuery. where(cond FactQueryCondition) FactQueryConditionАналогичен методу where(cond FactQueryCondition) объекта FactQuery. andWhere(cond FactQueryCondition) FactQueryConditionАналогичен методу andWhere(cond FactQueryCondition) объекта FactQuery. orWhere(cond FactQueryCondition) FactQueryConditionАналогичен методу orWhere(cond FactQueryCondition) объекта FactQuery. and(cond FactQueryCondition) FactQueryConditionАналогичен методу andWhere(cond FactQueryCondition) объекта FactQuery. or(cond FactQueryCondition) FactQueryConditionАналогичен методу orWhere(cond FactQueryCondition) объекта FactQuery. Объект UserMessagemessage stringPurpose: оригинальный текст сообщения. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $msg = queue.last().message // $msg содержит текст последнего сообщения пользователя |
attachments List<string>Purpose: список идентификаторов файлов приложенных к сообщению. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $attachments = queue.first().attachments // $attachments содержит список вложений первого сообщения пользователя. |
isEmpty() boolPurpose: определяет пустое ли сообщение. Arguments: отсутствуют. Returned value: true, если сообщение пустое и false в противном случае. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $isEmpty = queue.last().isEmpty() // $isEmpty содержит true, если последнее сообщение пользователя пустое и false в противном случае |
hasAttachments() boolPurpose: определяет есть ли вложения в данном сообщении. Arguments: отсутствуют. Returned value: true, если сообщение имеет вложения и false в противном случае. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| $hasAttachments = queue.first().hasAttachments() // $hasAttachments содержит true, если первое сообщение пользователя имеет вложения и false в противном случае |
Объект Sentenceintent stringPurpose: распознанное намерение. | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlu.parse("Привет Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$intent = $sentence.intent // $intent содержит "greeting" |
intentConfidence numberPurpose: степень достоверности распознанного намерения (1 – однозначное распознавание, 0 – намерение фактически нераспознанно). | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlu.parse("Привет Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$confidence = $sentence.intentConfidence // $confidence содержит 0.98 |
entities List<Tuple>Purpose: список распознанных сущностей. Каждый элемент списка содержит кортеж из трёх элементов: тип сущности (string), значение сущности (строка), достоверность распознавания сущности (number). | Блок кода |
|---|
| language | php |
|---|
| theme | DJango |
|---|
| firstline | 1 |
|---|
| title | Usage example |
|---|
| linenumbers | true |
|---|
| $sentence = nlu.parse("Доброе утро Вася", "d926726a-5acb-4233-8c1e-ce4300921de0")
$entities = $sentence.entities // $entities содержит [("human-name", "Вася", 0.96), ("time", "2023-01-09 23:30:00", 0.87)]
$first = $entities.get(0) // $first содержит ("human-name", "Вася", 0.96)
$type = $first.get(0) // $type содержит "human-name" |
|