# Chat Scripts

Chat scripts are simple Python expressions. They're used for data manipulation in certain AI agent [actions](https://documentation.proto.cx/docs/modules/ai-agents/workflows-and-actions) triggered during a chat.

***

## Actions & Delimiters

The following actions support chat scripts. To display a variable's value within an AI agent's action content, enclose the variable name within curly braces `{ }` as a delimiter.

<table><thead><tr><th width="457">Actions that require { ... } delimiter</th><th>Actions that do not require delimiter</th></tr></thead><tbody><tr><td><a href="../modules/ai-agents/workflows-and-actions/send-message">Send Message</a></td><td><a href="../modules/ai-agents/workflows-and-actions/branch">If/Else</a></td></tr><tr><td><a href="../modules/ai-agents/workflows-and-actions/send-file">Send File</a></td><td><a href="../modules/ai-agents/workflows-and-actions/set-variable">Set Chat Variable</a></td></tr><tr><td><a href="../modules/ai-agents/workflows-and-actions/show-carousel">Show Carousel</a></td><td><a href="../modules/ai-agents/workflows-and-actions/send-api-request">Send API Request</a></td></tr><tr><td><a href="../modules/ai-agents/workflows-and-actions/show-survey">Show Survey</a></td><td></td></tr><tr><td><a href="../modules/ai-agents/workflows-and-actions/create-ticket">Create Ticket</a></td><td></td></tr></tbody></table>

`{ … }` is required to print out variable/script values.

<figure><img src="https://documentation.proto.cx/~gitbook/image?url=https%3A%2F%2F2581047078-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Few2P7M4OjewnGSuQi7Ht%252Fuploads%252FiGadwVbxLxK01jKlPdGn%252Fmodvar_script.png%3Falt%3Dmedia%26token%3D839c35bf-835c-4ff1-a6e6-499e40e56300&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=a6e8c993&#x26;sv=2" alt=""><figcaption><p>From Modify Variable to Message</p></figcaption></figure>

<figure><img src="https://documentation.proto.cx/~gitbook/image?url=https%3A%2F%2F2581047078-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Few2P7M4OjewnGSuQi7Ht%252Fuploads%252FvNX6DgkV3u1y1zshFVJo%252Fsurvey_script.png%3Falt%3Dmedia%26token%3Db18b354c-2b32-4a3d-9d54-35898aac3fb0&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=6b6dafce&#x26;sv=2" alt=""><figcaption><p>From Survey to Message</p></figcaption></figure>

***

## Scripts <a href="#proto-script-1" id="proto-script-1"></a>

### `_.dt_diff(datetime1, datetime2, unit)` <a href="#dt_diff-datetime1-datetime2-unit" id="dt_diff-datetime1-datetime2-unit"></a>

Calculates the difference between two datetime objects and returns the result in the specified time unit. Unit - d for day, h for hour, m for minute, s for second, e.g.:

```
dt1 = datetime.datetime(2022, 4, 12, 12, 0, 0)
dt2 = datetime.datetime(2022, 4, 11, 12, 0, 0)

seconds_diff = _.dt_diff(dt1, dt2,'s')
Output: 86400

hours_diff = _.dt_diff(dt1, dt2,'h')
Output: 24
```

***

### `_.fmt(string, value)` <a href="#fmt-string-value" id="fmt-string-value"></a>

Formats the specified value(s) and insert them inside the string's placeholder, e.g.:

```
_.fmt("Hello, %s!", "world")
Output: "Hello, world!"
```

***

### `_.format_time(datetime, format, timezone)` <a href="#format_time-datetime-format-timezone" id="format_time-datetime-format-timezone"></a>

Format datetime, e.g.:

```
_.format_time(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S", "America/New_York"))
Output: Formatted time in New York timezone

 _.formatTime(_.str2datetime(timestamp), '%Y-%m-%d %H:%M:%S', 'America/Toronto')
Output: Formatted time in Toronto timezone
```

***

### `_.join(separator, items)` <a href="#join-separator-items" id="join-separator-items"></a>

Join all items in a tuple into a string, using a character as a separator, e.g.:

```
items = ["apple", "banana"", "cherry"]
_.join("", "", items)
Output: "apple, banana, cherry"
```

***

### `_.json_parse(data)` <a href="#json_parse-data" id="json_parse-data"></a>

Parses a JSON string and returns a Python object, e.g.:

```
json_data = '{"name": "Alice", "age": 25}'
_.json_parse(json_data)
Output: {'name': 'Alice', 'age': 25}
```

***

### `_.json_stringify(data)` <a href="#json_stringify-data" id="json_stringify-data"></a>

Serialises Python objects into JSON format. It returns a JSON string representing the input data, e.g.:

```
data = {"name": "John", "age": 30}
_.json_stringify(data)
Output: '{"name": "John", "age": 30}'
```

***

### `_.len(x)` <a href="#len-x" id="len-x"></a>

The number of characters in a variable, e.g.:

```
_.len("hello")
Output: 5
```

***

### `_.lower(string)` <a href="#lower-string" id="lower-string"></a>

Convert string to lowercase, e.g.:

```
_.lower("WORLD")
Output: "world"
```

***

### `_.now(timezone, format)` <a href="#now-timezone-format" id="now-timezone-format"></a>

Retrieves the current date and time in the Coordinated Universal Time (UTC) timezone. If a timezone is define, it would display the current year and hour based on the timezone, formatted as a string. If a dateime format code is define, it will output based on the format set.

```
_.now()
Output: Current date and time in UTC timezone

example time now at Manila is 2024-04-15 10:30:00
_.now('Asia/Manila', '%Y %H')
Output: 2024 10
```

***

### `_.replace(string, search, replacement)` <a href="#replace-string-search-replacement" id="replace-string-search-replacement"></a>

Replaces a specified phrase with another specified phrase, e.g.:

```
_.replace("hello world", "world", "universe")
Output: "hello universe"
```

***

### `_.split(string, separator)` <a href="#split-string-separator" id="split-string-separator"></a>

Split a string into a list where each word is a list item, e.g.:

```
string = "apple, banana, cherry"
_.split(string, "", "")
Output: ['apple', 'banana', 'cherry']
```

***

### `_.str2datetime(timestring, format)` <a href="#str2datetime-timestring-format" id="str2datetime-timestring-format"></a>

Convert string to datetime, e.g.:

```
_.str2datetime("2023-12-25"))
Output: 2023-12-25 00:00:00
```

***

### `_.upper(string)` <a href="#upper-string" id="upper-string"></a>

Convert string to uppercase, e.g.:

```
_.upper("hello))  
Output: "HELLO"
```

***

### `_.as_int(string)` <a href="#as_int-string" id="as_int-string"></a>

Convert string to integer, e.g.:

```
_.as_int("10") 
Output: 10
```

***

### `_.as_float(string)` <a href="#as_float-string" id="as_float-string"></a>

Convert string to float, e.g.:

```
_.as_float("3.14")
Output: 3.14
```

***

### `_.as_str(string)` <a href="#as_str-string" id="as_str-string"></a>

Convert specified value to string, e.g.:

```
_.as_str(42))
Output: "42"
```

***

### `_.round_num(number,precision)` <a href="#round_num-number-precision" id="round_num-number-precision"></a>

Returns a floating point number that is a rounded version of the specified number, e.g.:

```
_.round_num(3.14159, 2) 
Output: 3.14
```

***

### `_.random_num(min,max)` <a href="#random_num-min-max" id="random_num-min-max"></a>

Returns an integer number selected element from the specified range, e.g.:

```
_.random_num(1, 10)
Output: Random integer between 1 and 10
```

***

### `_.random_choice(list)` <a href="#random_choice-list" id="random_choice-list"></a>

Returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple, or any other kind of sequence, e.g.:

```
_.random_choice(["apple", "banana", "cherry"])
Output: Randomly chosen item from the list
```

***

### `_.match_pattern(string, pattern)` <a href="#match_pattern-string-pattern" id="match_pattern-string-pattern"></a>

Search the regular expression pattern and return the first occurrence, .e.g.:

```
email = "example@email.com"
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
_.match_pattern(email,pattern)
```

***

### `_.obj_keys(dictionary)` <a href="#obj_keys-dictionary" id="obj_keys-dictionary"></a>

Takes a dictionary as input and returns a list containing all the keys from the input dictionary, e.g.:

```
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = _.obj_keys(my_dict)
Output: [a, b, c]
```

***

### `_.obj_values(dictionary)` <a href="#obj_values-dictionary" id="obj_values-dictionary"></a>

Takes a dictionary as input and returns a list containing all the values from the input dictionary, e.g.:

```
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = _.obj_values(my_dict)
Output: [1, 2, 3]
```

***

### `_.get(dictionary, path)` <a href="#get-dictionary-path" id="get-dictionary-path"></a>

Retrieves the value at a specified path within a nested dictionary or list, e.g.:

```
object = {
    'a': [
        {'b': {'c': 3}}
    ]
}

 _.get(object, 'a')
Output: [{'b': {'c': 3}}]

 _.get(object, 'a[0].b.c')
Output: 3

_.get(object, ['a', '0', 'b', 'c'])
Output: 3
```

***

### `_.map_get(list[dict], path)`

Maps the get function over a list of dictionaries. It retrieves the value at a specified path within each dictionary in the list, e.g.:

```
list_d = [
    {'a': {'b': 1}},
    {'a': {'b': 2}},
    {'a': {'b': 3}}
]

_.map_get(list_d, 'a.b')
Output: [1, 2, 3]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://documentation.proto.cx/docs/developer-documentation/chat-scripts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
