Built-in scripting functions

Review

Functions are used as arguments by script components. They allow you to calculate specific values ​​and even perform operations on the system.

Functions are divided into:

  • pure – the return value depends only on the parameters.

  • with site effects - the return value may vary depending on the state of the system.

  • modifiers – makes changes to the system.

Components constantly use arguments,

arguments can be represented as expressions, expressions can use functions.

Function Categories

Category Description

Mathematical

Pure mathematical functions.

String

Pure functions for working with strings.

Date/time

Pure functions for working with dates and times and side-effect functions for accessing the current time.

Transformations

Pure functions for value conversion, encoding, packaging, presentation.

Hash sums

Pure hash functions.

Files and paths

Pure functions for working with file paths and directory categories.

Service functions

Various functions for bidirectional access to context and state.

Access

Side-effect functions for special access to variables.

Configuration

Side-effect functions for obtaining data from the system configuration.

Constants

Pure constant substitution functions.

Symbols

Pure character substitution functions.

IVR

Side-effect functions for accessing call data and queue state modifiers.

Function directory

Table 1. Mathematical functions
Function Options Description

sin

num

Sine of a number

cos

num

Cosine of a number

tan

num

Tangent of a number

asin

num

Arcsine of numbers

acos

num

Arc cosine of a number

atan

num

Arctangent of a number

atan2

num, num

Arctangent of the quotient of two numbers

sinh

num

Hyperbolic sine of a number

cosh

num

Hyperbolic cosine of a number

tanh

num

Hyperbolic tangent of a number

exp

num

Exponent of a number

log

num

Natural logarithm of a number

log2

num

Binary logarithm of a number

log10

num

Decimal logarithm of a number

pow

num, num

The result of raising one number to the power of another

sqrt

num

Square root of a number

erf

num

Error function:

2/sqrt(pi)*integral from 0 to X of exp(-t*t) dt

Not available on Windows

erfc

num

1.0 - erf(X)

Not available on Windows

max

num, num

The maximum of two numbers

min

num, num

Minimum of two numbers

trunc

num

The result of discarding the fractional part of a number

round

num

The result of rounding a number to an integer

abs

num

Absolute value of a number

floor

num

Closest integer from below

ceil

num

Closest integer from above

lg

num

Decimal logarithm of a number

ln

num

Natural logarithm of a number

log

num, num

Logarithm of one number to the base of another

sqr

num

Number square

random

Random decimal number from 0 to 1

random

int

Random integer from 0 to a specified integer

random

int, int

Random integer in the range between two integers

Table 2. String functions
Function Options Description

newid

Returns the generated UUID.

len

str

Returns the length of a string in characters.

concat

str,str

Returns the result of concatenating two strings.

equal

str,str

Result of comparing two strings: 0 or 1

str

str,str

Returns the index of the position of the first occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

rstr

str,str

Returns the position index of the last occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

substr

str,int

Returns a substring from the specified position (n2) to the end.

substr

str,int,int

Returns a substring from the specified position (n2) of no more than the specified length (n3).

replace

str,str,str

Returns the result of replacing the occurrence of (n2) in the string (n1) with the value (n3).

lower

str

Returns a lowercase string.

upper

str

Returns an uppercase string.

remove

str,int

Returns a string after removing a substring from the specified position (n2) to the end.

remove

str,int,int

Returns a string after removing a substring from the specified position (n2) of the specified length (n3).

indexof

str,str

Returns the index of the position of the first occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

indexof

str,str,int

Returns the index of the position of the first occurrence of the substring (n2) in the string (n1), starting at the specified position (n3). Returns 0 if no occurrences are found.

trim

str

Returns a string stripped of leading and trailing empty characters (space, tab, etc.).

ltrim

str

Returns a string stripped of leading blank characters (space, tab, etc.).

rtrim

str

Returns a string stripped of trailing empty characters (space, tab, etc.).

trimstart

str

Returns a string stripped of leading blank characters (space, tab, etc.).

trimend

str

Returns a string stripped of trailing empty characters (space, tab, etc.).

left

str,int

Returns the left side of a string no greater than the specified length.

right

str,int

Returns the right side of a string no greater than the specified length.

reverse

str

Returns the reversed string.

regexreplace

str,str,str

Returns the result of a replacement using a regular expression. p1 - ​​value, p2 - pattern, p3 - replacement.

regexreplaceg

str,str,str

Returns the result of a replacement using a regular expression with the global option. p1 - ​​value, p2 - pattern, p3 - replacement.

modify_json

str,json,json

Returns the modified json structure. Applies the search query (p1) to the value (p2), modifies the detected element according to the options (p3) and returns the overall result.

Example:
modify_json(
  "chat/0/msgs",
  '{"chat":[{"msgs":[{"txt":"abc"}]}]}',
  '{"action":"append","value":{"txt":"zcv"}}'
)

Options are presented as a json object with a required key action. Possible options:

  • append - for an array. Adds a new element to the end. In the options, the value of the element is based on the key value.

  • prepend - for an array. Adds a new element to the beginning. In options, the element value by key value

  • insert - for an array. Adds a new element at the specified position. In the options, the element value is by key value, position is by key index.

  • replace - for an array. Replaces the element at the specified position with a new one. In the options, the value of the new element is by the key value, the position is by the key index.

  • replace_auto - for an array. Replaces all array elements with the specified value. In the options, the value is by the key value.

  • delete - for an array. Removes an element from the specified position. In the options, the value of the position by the key index.

  • keystore - for an object. Saves an element using the specified key, and depending on the presence of the key, adds or changes the value. In the options, the value of the element is by key value, the value of the key is by key key.

  • keyreplace - for an object. Replaces an element using the specified key, and if the key is missing, it leaves it unchanged. In the options, the value of the element is by key value, the value of the key is by key key.

  • keyinsert - for an object. Saves the element by the specified key if it is missing, otherwise it fails with an error. In the options, the value of the element is by key value, the value of the key is by key key.

  • keydelete - for an object. Removes the element using the specified key. In the options, the key value is by key key.

Table 3. Functions for working with dates/times
Function Options Description

nowtick

Returns a number representing the absolute value in milliseconds since 1970.

now

Returns the current date and time in the server’s local time zone in RFC3339 format. For example, 2019-10-06T16:43:30.46+03:00.

nowutc

Returns the current date and time in UTC in RFC3339 format.

nowgregsecond

Returns the number of seconds according to the Gregorian calendar, since 0 AD.

ticktolocal

int

Returns the date in the server’s local time zone based on the absolute value of tick.

ticktoutc

int

Returns the date in UTC based on the absolute value of tick.

tick

dt

Converts date to unix timestamp

dateformat

str, dt

Returns a string representing the date (n2) in the specified format (n1). For example: yyyy-MM-dd.

Possible format string placeholders: yyyy, yy, MM, d, dd, h, HH, MMM, mm, ss, ffff, fff, ff, f, zzz.

date

Returns the current date in the server’s local time zone, without specifying the time zone. Format YYYY-MM-DD.

date

dt

Returns a date from a specified date/time.

time

Returns the current time in the server’s local time zone, without specifying a time zone. Format YYYY-MM-DD.. Format HH:mm:ss.fff.

time

dt

Returns the time from the specified date/time.

datetime

str

Returns a date/time generated from a string. The string can contain various date/time representations, including RFC3339.

datetime

int,int,int

Returns date/time based on the passed p1 - year, p2 - month, p3 - day.

datetime

int,int,int,int,int

Returns date/time based on the passed p1 - year, p2 - month, p3 - day, p4 - hour, p5 - minute.

datetime

int,int,int,int,int,int

Returns date/time based on the passed n1 - year, n2 - month, n3 - day, n4 - hour, n5 - minutes, n6 - seconds.

datetime

int,int,int,int,int,int,int

Returns date/time based on the passed n1 - year, n2 - month, n3 - day, n4 - hour, n5 - minutes, n6 - seconds, n7 - milliseconds.

datediff

atom,dt,dt

Returns the number of specified time units between two dates.

The parameter is specified as an atom (not a string), for example datediff('dd',"2019-10-06","2019-10-05")

Possible types of units in descending order: yy, yyyy, q, qq, m, mm, ww, wk, d, dd, h, hh, mi, n, s, ss, ms

dateadd

atom,int,dt

Returns the date after adding the specified number (n2) of the specified time units (n1) to the specified date/time (n3).

The parameter is specified as an atom (not a string), for example dateadd('mi',120,"2019-10-06T13:05:28")

Possible types of units in descending order: yy, yyyy, q, qq, m, mm, ww, wk, d, dd, h, hh, mi, n, s, ss, ms

year

dt

Returns the current year of the specified date/time.

month

dt

Returns the current month (1-12) of the specified date/time.

day

dt

Returns the current day (1-31) of the specified date/time.

hour

dt

Returns the current hour (0-23) of the specified date/time.

minute

dt

Returns the current minute (0-59) of the specified date/time.

second

dt

Returns the current second (0-59) of the specified date/time.

millisecond

dt

Returns the current millisecond (0-999) of the specified date/time.

dayofyear

dt

Returns the number of the day in the year for the specified date/time.

dayofweek

dt

Returns the day of the week number (1-7) for the specified date/time.

weekofyear

dt

Returns the week number in the year for the specified date/time.

isleapyear

int

Returns true if the specified date/time represents a leap year.

datetimelocal

dt

Returns the date/time adjusted to the server’s local time zone. Numerical date/time values ​​do not change, but the absolute time point can be shifted after changing the time zone to local.

datetimeutc

dt

Returns the date/time normalized to UTC. Numerical date/time values ​​do not change, but the absolute time point can be shifted after changing the time zone to zero.

localtoutc

dt

Returns the UTC date/time for the specified date/time, considered in the server’s local time zone.

utctolocal

dt

Returns the local date/time for the specified date/time, treated as UTC.

valid_date

dt

Returns true if the specified string contains a valid date/time, otherwise false.

Table 4. Conversion functions
Function Options Description

char

int

Returns a string with a single character based on its Unicode code.

str

int

Converts a numeric value to a string.

num

str

Converts a string to a number. If it fails, it exits with an error.

numval

str

Converts a string to a number, cutting off inappropriate characters from the end. In the limit it returns 0.

dechex

int

Returns a string with the HEX representation of a number.

hexdec

str

Returns a number based on its HEX representation.

base64encode

str

Returns the string resulting from packing into Base64 representation.

base64decode

str

Returns the string resulting from decompression from a Base-64 representation.

urlencode

str

Returns a string encoded with UrlEncode.

urldecode

str

Returns a string encoded using UrlEncode.

htmlencode

str

Returns a string encoded using Unicode Hex Character Code.

htmldecode

str

Returns a string decoded using Unicode Hex Character Code

escape

str

Returns the string resulting from the escape sequence conversion. Used for inserting into JSON.

unescape

str

Returns the string resulting from unpacking from the escape sequence. Used to clean up after JSON.

translit

str

Returns the result of the string transliteration.

ifelse

bool,any,any

If the value of the first parameter is true, then it returns n2, otherwise it returns n3.

Table 5. Hash amounts
Function Options Description

md5

str

Returns a hash of a string encoded in UTF-8 using the MD5 algorithm.

crc32

any

Returns a hash of any value using the CRC32 algorithm (IEEE 802.3).

crc32

num,any

Returns a new hash value from the previous value combined with a new chunk. n1 is the previous hash value, n2 is a new piece of data. According to the CRC32 algorithm (IEEE 802.3).

adler32

any

Returns a hash of any value using the Adler-32 algorithm.

adler32

num,any

Returns a new hash value from the previous value combined with a new chunk. n1 is the previous hash value, n2 is a new piece of data. According to the Adler-32 algorithm.

phash2

any

Returns the hash sum of any value using an internal algorithm.

Table 6. Functions for working with file paths
Function Options Description

pathtype

str

Returns the path type (the category prefix from the specified path).

relpath

str

Returns the relative path (the specified path without the category prefix).

filename

str

Returns the filename extracted from the specified path.

filetext

str

Returns the file extension extracted from the specified path.

filedir

str

Returns the name of the directory. For a file path, this is the name of the directory; for a directory path, this is the name of the parent directory.

makepath

str,str

Returns the path formed by concatenating two parts.

makepath

str,str,str

Returns a path formed by concatenating three parts: path, filename, and file extension.

temp

Returns :TEMP - the prefix of the script’s temporary local directory.

syn_media

Returns :SYNC_COMMON - the category prefix of the general purpose synchronized directory.

syn_dom_media

syn_domain

Returns :SYNC_DOMAIN_DATA the category prefix of the domain data directory being synchronized.

syn_script

Returns :SYNC_SCRIPT_DATA the category prefix of the current script’s synchronizing data directory (by code).

syn_script_media

Returns :SYNC_SCRIPT_STATIC the category prefix of the synchronized directory of static script files (by code).

ss_public

Returns :SITESHARE_PUBLIC - the prefix of the general purpose network intrasite directory category.

ss_domain

Returns :SITESHARE_DOMAIN_DATA - the prefix of the category of the network intrasite directory of the current domain.

ss_script

Returns :SITESHARE_SCRIPT_DATA - the prefix of the category of the network intrasite directory of the current scenario (by code).

gs_public

Returns :GLOBALSHARE_PUBLIC, the general purpose network intersite directory category prefix.

gs_domain

Returns :GLOBALSHARE_DOMAIN_DATA - the prefix of the network cross-site directory category of the current domain.

gs_script

Returns :GLOBALSHARE_SCRIPT_DATA - the prefix of the current script’s network cross-site directory category (by code).

Table 7. Service functions
Function Options Description

startparam

int

Returns the value of the input parameter at the specified index. Scripts can accept up to 20 input parameters.

getscriptref

Returns a string containing the ID of the current scripting engine. Other script handlers can send messages to the handler using this identifier, for example using the Script Interaction component.

get_project_id

Returns a string containing the project ID of the currently running script.

cmd

str,str,str,str

cmd

str,str,str,str,str

component

int(atom,binary),binary(map,proplist)

Executes a component of the specified type from a group of service script components. The first parameter is the component type (numeric number or key from the module name, for example 103 or pause), the second parameter is the component properties from the documentation, with the exception of transition branches and variables for output values ​​(can be erlang:map() or erlang:proplist() or binary() with JSON). Returns an object with the keys of the fields of the output variables and additionally "transferKey", the format of the return value matches the format of the second parameter.

component

int(atom,binary),binary(map,proplist),atom

Executes a component of the specified type from a group of service script components.

The first parameter is the component type (a numeric number or a key from the module name, for example 103 or pause).

The second parameter is the component properties from the documentation, excluding transition branches and variables for output values (can be erlang:map() or erlang:proplist() or binary() with JSON).

The third parameter sets the format of the return value (map, proplist, json). Another third parameter can order a value for a specific key to be returned from the result (for example, to return a value typically stored in a component’s output variable). Also, the third parameter can set the mode of returning a string concatenated from the transferKey and varValue values ​​(format "TransferKeyValue;OtherKeyValue"), for this you need to set the third parameter without quotes: "{transfer,Key}".

Returns an object with the keys of the output variable fields and additionally "transferKey", or the value for a specific key from this object.

Examples:

---- component(notify, #{mode ⇒ 0, text ⇒ [a1], user ⇒ <<"admin">>}, map) component(111, #{<<"mode">> ⇒ 0, <<"text">> ⇒ <<"Something">>, <<"user">> ⇒ <<"admin">>}, json) component(111, <<"\"mode\": 0, \"text\": \"Something\", \"user\": \"admin\"">>, <<"transferKey">>) component(parser, #{algoritm ⇒ 0, functionJSON ⇒ 0, data ⇒ <<"{\\\"a\\\":\\\"value\\\"}">>, query ⇒ <<"a">>}, {transfer,<<"resultVariable">>}) ----

Component codes and fields are available in the documentation on the corresponding component pages.

One possible way is to set up a new script with a component that has the settings of interest, and copy its contents from the JSON script.

lock

any,int

Waits for and blocks the critical section (analogous to the Mutex component). The first parameter is the unique name of the critical section. The second parameter is the waiting time in milliseconds before the timeout. Returns "ok", "timeout", "error".

lock

any,int,any,int

Waits for and blocks the critical section (analogous to the Mutex component). The first parameter is the unique name of the critical section. The second parameter is the waiting time in milliseconds before the timeout. The third parameter is the type of operation under lock (1 or read - reading, 2 or write - writing). The fourth parameter is the time in milliseconds after which the critical section will be automatically released. Returns "ok", "timeout", "error".

unlock

any

Releases the critical section (analogous to the Mutex component). Returns "ok" or "error".

dc_read_types

str

dc_read_fields

str,str

dc_read

str,str

dc_read

str,str,str

dc_find

str,str

dc_find

str,str,str

dc_select

str,str

dc_select

str,str,str

Table 8. Accessibility functions
Function Options Description

check_variable

str

Returns true if a variable with the specified name exists and contains a value.

get_variable_value

str

Returns the value of a variable by its name.

get_variable_value

str, any

Returns the value of a variable by its name, and if the value is not set, then the default value from the second parameter.

get_variable_id

str

Returns a string with a variable identifier by its name.

get_variable_orig

str

Returns the value of a variable by its name, and if the value is a string, then it is returned in the original encoding without conversion.

set_variable_value_if_undefined

str, any

Sets the value of a variable by its name if its value is not specified. Returns the value of a variable as a result of an operation.

var

str

Returns the value of a variable by its name.

storage_put

str, any

Extends or places in the data storage on the site the value (2nd parameter) by key (1st parameter) for 2 days. Returns "ok". If the storage is unavailable, returns "error".

storage_put

str, any, int

Extends or places in the data storage on the site the value (2nd parameter) by key (1st parameter) for the specified number of seconds (3rd parameter). Returns "ok". If the storage is unavailable, returns "error".

storage_get

str, any

Returns the value by key from the data store on the site, or the default value if there is none. If the storage is unavailable, returns "error".

storage_del

str

Removes the value for the specified key from the data store on the site. If the storage is unavailable, returns "error".

Reading and modifying an existing value in the store when working in parallel mode should be done in a critical section, for example, built by the "Mutex" component or the lock/unlock expression functions.
Table 9. Configuration functions
Function Options Description

wsurl

Returns the URL of the closest available server with the logical role ws.

site

Returns the site on which the script is executed.

domain

Returns the domain in which the script is running.

parentdomain

Returns the parent domain of the one in which the script is running.

isworktime

Returns true if the current time is working time, false otherwise. The schedule is taken from domain settings and applied to the local time zone of the site (servers with the mdc/sdc role).

isworktime

int

Returns true if the current time is working time, false otherwise. The schedule is taken from domain settings and applied to the time zone specified in minutes, for example, 0 - UTC, 180 - Moscow.

In proto://ip-address:port format.

Table 10. Constants
Function Options Description

e

Returns the number e (2.718281828459045).

pi

Returns the number pi (3.141592653589793).

phi

Returns the number phi (1.618033988749895).

Table 11. Symbols
Function Options Description

tab

Returns a string with a tab character.

endline

Returns a string with a line terminator.

quot

Returns a string with a quote character.

dblquot

Returns a string with a double quote character.

Table 12. IVR script functions (issue RP-1468)
Function Options Description

ivrparam

str

Returns the value of the specified parameter from the X-Era-Ivr header, which is generated by the b2b role.

For example, from, to, by.

Available only for calls received in IVR.

callednum

Returns a string with the number dialed by the subscriber from the INVITE that is included in the routing.

ATTENTION! For incoming calls from outside (from connections to providers), this number generally does not coincide with the one to which the external call was received. For the latter, use the calledid() function.

Available only for calls received in IVR.

To obtain a subscriber number when making outgoing calls using ivr (component 'Outgoing call', API 'invite_byivr'), you must use the IVR script parameters (startparam(N)) and pass the necessary information through them.

calledext

Returns a string with the extension KAF through which the call was received in the IVR. Contains the entire postfix after removing the feature code number.

Available only for calls received in IVR.

To obtain a subscriber number when making outgoing calls using ivr (component 'Outgoing call', API 'invite_byivr'), you must use the IVR script parameters (startparam(N)) and pass the necessary information through them.

remotenum

Returns a string with the subscriber number generated as a result of applying representation rules, or the internal number of the subscriber of the current domain, or username from the From header of an INVITE request received for routing.

ATTENTION! For incoming calls from outside (from connections to providers), this number generally does not coincide with the one from which the external call came, since it can be converted by normalization rules. For the latter, use the callerid() function.

Available only for calls received in IVR.

To obtain a subscriber number when making outgoing calls using ivr (component 'Outgoing call', API 'invite_byivr'), you must use the IVR script parameters (startparam(N)) and pass the necessary information through them.

calledid

Returns a string with the number dialed by the subscriber.

For calls originating externally from the provider, contains the username of the To header of the original received INVITE request before normalization and routing rules are applied.

Available only for calls received in IVR.

callerid

Returns a string with the number dialed by the subscriber.

For calls originating externally from the provider, contains the username of the From header of the original received INVITE request before normalization, routing, and presentation rules are applied.

Available only for calls received in IVR.

callid

Returns a string with the value of the header CallId of the b2b - ivr arm of the SIP dialogue with the subscriber.

seancenativeid

Returns a string with the native identifier of the current session (SC), extracting it from the labels of the current call. If you execute the function at the very beginning of the first call, it may delay execution by up to 500 ms while waiting for the session to be assigned.

sessionid

Returns a string with the current session identifier (SC), identifying it in the session store by the label’s native session. If you execute the function at the very beginning of the first call, it may delay execution by up to 500 ms while waiting for the session to be assigned.

sipheader

Returns a string with the value of the b2b - ivr arm of the SIP dialogue with the subscriber specified in the header parameter.

In order for an arbitrary header from the initial request from the subscriber to be forwarded to the IVR shoulder, you need to configure the list of headers forwarded through (the 'fwd_headers' parameter) in the configuration parameters of the 'esg' and 'b2b' roles.

If there are several specified headers, their values will be separated by a line break ('\r\n' or 0x0D,0x0A).

Available only for calls received in IVR.

huntid

Returns a string with the entity identifier hunt-group to which the call is directed.

Available only for calls received in IVR via featurecode with type hunt, in scenarios qivrscript and preivrscript. In all other cases it returns invalid_mode.

huntobjid

Returns a string with the identifier of the runtime object of the hunt group queue.

Available only for calls received in IVR via featurecode with type hunt, in scenarios qivrscript and preivrscript. In all other cases it returns invalid_mode.

queuepriority

Returns the current numeric value of the priority in the queue.

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode.

queuepriority

int

Sets a new numeric priority value in the queue, automatically moving.

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

queue position

Returns the current position in the queue.

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

queueestimatedsec

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

queuerescount

Returns the number of operators in the hunt group.

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

queuerescount

str

Returns the number of operators in the hunt group that are in state (online or free, indicated by the parameter).

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

queuestate

Returns a string with the name of the queued state.

Available only for calls received in IVR via featurecode with type hunt, in qivrscript scenarios. In all other cases it returns invalid_mode

q_displayname

Returns the displayname from the From header URI of an INVITE SIP request waiting in a hunt group queue of type sipuser.

Only available for preivrscript scenarios. In all other cases it returns invalid_mode.

q_username

Returns the username from the From header URI of an INVITE SIP request waiting in a hunt group queue with type sipuser.

Only available for preivrscript scenarios. In all other cases it returns invalid_mode.

q_domain

Returns domain from the From header URI of an INVITE SIP request waiting in the hunt group queue with type sipuser.

Only available for preivrscript scenarios. In all other cases it returns invalid_mode.

r_number

Returns a string with the operator call number (username from the URI header To of the INVITE SIP request sent to call the operator).

Only available for preivrscript scenarios. In all other cases it returns invalid_mode.