Botsquad documentation logo

Expressions are used in places where you want to create dynamic content or perform calculations. They can occur as part of any Bubblescript statement. For instance, the argument to the say statement can contain an expression, to make it dynamic.

Consider this example:

name = "Pete"
say "Hello " + name + ", " + random(["how are you?", "what's up?", "how you doing?"])

This uses a variable (name), the string concatenation operator (+), and the random() function to generate a dynamic answer.

The following builtin functions are available to use in expressions:

List (array) functions

filter(list, query)

Filter list of maps according to a MatchEngine query.

first(list)

Return the first item in a list

item(ets, index)

Return tne n-th item from the given list (the first element is at index 0)

join(list, joiner)

Join the given list using a string.

keys(map)

Return the keys of a map or keyword list.

When a plain list is given, returns a list with the list indexes ([0, 1, 2, …]).

Raises an error on non list/map values.

last(list)

Return the last item from a list

pluck(list, key)

Given a list of maps, return for each map the item with the given key.

score(list, query)

Score a list of maps according to a MatchEngine query.

shuffle(list)

Shuffle the given list

sort(enum, opts \\ [])

Sort a list.

Options:

Example:

map = [[num: 1], [num: 2], [num: 3], [num: 4], [num: 5]]
map = sort(map, field: "num", direction: :desc)

split(string, pattern, opts \\ [])

Split the given string on the pattern, returning a list.

Options (doc):

uniq(list)

Return a list with unique elements (no duplicates)

values(map)

Return the values of a map or a keyword list.

When a plain list is given, returns the list itself.

Raises an error on non list/map values.

Date functions

As there is no native datetime datatype in the DSL, all date functions expect a valid ISO date string as input, and also return an ISO date string. Internally, the Timex library is used for all date operations.

date_diff(a, b, granularity)

Get the difference between two dates.

You need to specify a diff granularity, any of the following:

and the result will be an integer value of those units or a Duration struct. The diff value will be negative if a comes before b, and positive if a comes after b. This behaviour mirrors compare/3.

See the Timex manual.

date_format(date, format_string, formatter \\ nil)

Formats an UTC ISO8601 time string.

Expects an ISO date string, a format string and optionally a formatter module.

For the format of the date format string, see the documentation of the Timex date formatter.

The formatter argument can be set to :strftime to

date_now(timezone \\ nil)

Returns the current time as extended ISO8601 string.

When a timezone is passed in, the current date is returned in that timezone.

date_parse(string, opts \\ [])

Parse a given date into a UTC ISO8601 time string.

The input date needs to be a string. The Duckling date parser is used (unless the format option is specified), so a “human input” string (“tomorrow”, “in 2 hours”) can be used as input.

Options can contain the following:

When using format:, date_parse fails with a runtime error when failing to parse the date. When using the duckling option, it returns nil when the parsing fails.

date_part(date, part)

Get a component of the given datetime.

The component name is one of the following:

Returns nil when an invalid part was given.

date_set(date, opts)

Return a new date/time value with the specified fields replaced by new values.

Values are automatically validated and clamped to good values by default.

See the Timex manual.

date_shift(date, opts)

Shifts the given datetime by the given duration.

A single function for adjusting the date using various units: duration, microseconds, seconds, minutes, hours, days, weeks, months, years.

The result of applying the shift will be the same type as that of the input, with the exception of shifting DateTimes, which may result in an AmbiguousDateTime if the shift moves to an ambiguous time period for the zone of that DateTime.

Valid units are:

See the Timex manual.

Miscelaneous helper functions

contains(string, substring)

Return whether a given value is part of the given list, or whether a given value is a substring of the given string.

This is a polymorphic function. When one of the arguments is nil, it will return false. In other cases, when invalid values are passed in, it will raise a runtime error.

distance(a, b)

Return the geographical distance (in meters) between two geographical locations.

The parameters need be valid geographical locations, e.g. maps with a lon and lat attribute.

entity(args)

Construct a new entity

event(name)

Construct an event for use in expecting:

extract_entity(input, entity)

Given an input sentence and an entity, extract the entity, returning its value.

When there is no entity found, it returns nil.

intent(args)

Construct a new intent

length(string)

Return the length of a string or the length of a list.

This is a polymorphic function: When passed in a string, it returns the number of characters in the string. When passed a list or a map, it returns the number of elements. For all other values, it returns 0.

random(number)

Return a random item.

This is a polymorphic function: When a number is given, returns a random number between 0 and that number. When a list is given, returns a random element from the list.

reverse(string)

Reverse the given list or string.

When a different value is passed in, it will raise a runtime error.

slice(string, startpos, endpos \\ nil)

Slice a substring out of the given string, or a sublist out of the given list.

When a different value is passed in, it will raise a runtime error.

Numeric functions

abs(value)

Return the abs of the given number.

ceil(value)

Return the ceil of the given number.

floor(value)

Return the floor of the given number.

max(a, b)

Return the max of the given numbers.

min(a, b)

Return the min of the given numbers.

modulo(a, b)

Return the modulo of the given numbers.

number(value)

Converts most values to their numeric counterpart. Returns nil when conversion fails.

round(value)

Return the round of the given number.

Show functions

audio(url)

Creates and validates a data structure for presenting an audio fragment.

The result is meant to be passed in to the show statement, e.g: show audio "http://example.com/…"

buttons(text, buttons)

Creates and validates a data structure for showing a buttons template

For more info on the exact data format see https://developers.facebook.com/docs/messenger-platform/reference/template/button

file(url)

Creates and validates a data structure for offering a file for download.

The result is meant to be passed in to the show statement, e.g: show file "http://example.com/…"

Creates and validates a data structure for showing a horizontal gallery template.

Options: pass in modal: false to prevent the elements showing in a modal gallery popup, but as large elements in the chat stream instead.

For more info on the exact data format see https://developers.facebook.com/docs/messenger-platform/reference/template/generic

image(url)

Creates and validates a data structure for showing an image.

The result is meant to be passed in to the show statement, e.g: show image "http://example.com/…"

input_method(type, config \\ nil)

Creates and validates a data structure for the given input method, to be used in an expecting: clause.

See http://doc.botsquad.com/dsl/ui/input for more details on different input methods.

list_template(elements, button \\ nil, top_element_style \\ "compact")

Creates and validates a data structure for showing a list template.

For more info on the exact data format see https://developers.facebook.com/docs/messenger-platform/reference/template/list

location(value, opts \\ [])

Convert the given value to a valid location structure

video(url)

Creates and validates a data structure for showing a video clip.

The result is meant to be passed in to the show statement, e.g: show video "http://example.com/…"

web(url)

Creates and validates a data structure for showing a website in an iframe.

The result is meant to be passed in to the show statement, e.g: show web "http://example.com/…"

String functions

capitalize(string)

Capitalizes each word in the string

downcase(string)

Converts a string to lowercase

html_entity_decode(string)

Decode HTML entities in a string.

html_entity_encode(string)

Encode HTML entities in a string.

pluralize(string)

Given a singular word, returns the plural version of it (according to English grammar)

regex_replace(string, regex, replacement, options \\ [])

Replace string in the given string with a replacement.

replace(string, pattern, replacement, options \\ [])

Replace string in the given string with a replacement.

singularize(string)

Given a plural word, returns the singular version of it (according to English grammar)

trim(string)

Trim whitespace characters from both ends of a string.

trim(string, what)

Trim given characters from both ends of a string.

trim_leading(string)

Trim leading whitespace characters from a string.

trim_leading(string, what)

Trim given leading characters from a string

trim_trailing(string)

Trim trailing whitespace characters from a string

trim_trailing(string, what)

Trim given trailing characters from a string

truncate(value, length, append \\ "…")

Truncates a string down to the number of characters passed as the first parameter.

An appendinx, defailting to the ellipsis character(…), is appended to the truncated string. The final string length is at max length characters, including the appendix.

truncate_words(value, numwords, append \\ "…")

Truncates a string down to the number of words passed as the first parameter. An ellipsis (…) is appended to the truncated string.

upcase(string)

Converts a string to uppercase

url_decode(string)

Decode escaped URL characters

url_encode(var)

Converts any URL-unsafe characters in a string into percent-encoded characters. Note that url_encode will turn a space into a + sign instead of a percent-encoded character.

url_escape(var)

Escapes any URL-unsafe characters in a string into percent-encoded characters, but leaves reserved characters alone (/, &, :, ?)

url_params(var)

Convert the given list of key/value pairs into a string which can be used in a URL query string.

Additional builtin functions

These are additional functions which can be used inside the bot processes. They cover more specific tasks that are related to the Botsquad platform, like token management, process management and communication.

cancel_emit(schedule_id)

Will cancel the given scheduled emit. The identifier can be obtained from the emit statement; a scheduled emit (with in: or at: option) sets the variable with the name schedule_id in the bot script. You can use this variable to cancel it:

emit "status_update", [], in: 10, name: "update"
cancel_emit schedule_id

chat_link(frontend, params \\ nil)

Generates a link to this bot for sharing purposes.

say "Reach me on the web on this link:"
say chat_link("web")

If you want a link to the same channel that the current user is chatting through, you can pass in the user.frontend variable:

say chat_link(user.frontend)

The second argument, params is used to add extra parameters to the chat link, for instance the g parameter to join a group.

say chat_link("web", g: group)

To create a link which leads into a users’s session, use the user_id parameter:

say chat_link("web", user_id: some_user_id)

delete_token(token_id)

Delete a given token ID

See API integrations

end_session()

Directly stops the interaction with the bot, ending the chat session. The next time the user talks, a new chat session is started.

dialog bue do
  say "Thank you for your time."
  end_session()
end

get_access_token(token_id)

Return the plain access token for the given token identifer. This access token is used in HTTP calls to perform requests to the integrated service.

See API integrations

get_full_token(token_id)

Retrieves the full token information structure, mainly for inspection purposes.

See API integrations

get_token_info(token_id)

Return some basic information about the user that is connected to the specific token:

log get_token_info(user.tokens.google)

See API integrations

group_name(parts)

Generates a deterministic group name for a list of identifiers based on a hash.

The identifiers can appear in any order, they are sorted before they are hashed. No ~ is prepended to the group name - you need to do this yourself.

json_build(data)

Convert a given value to a string encoded as JSON.

json_parse(data)

Convert the given JSON-encoded string to a data structure. Returns nil when decoding fails.

mail(to, subject, message, opts \\ [])

Sends a notification e-mail to the given user.

mail("[email protected]", "Subject", "Hi there! This is your bot talking to you.")

This will send a pre-formatted HTML email, with the bot’s name, profile picture and the message details.

HTML can not be used inside e-mail. The mail function is meant for basic notification and reminder messages.

The fourth argument can be given as options:

mail("[email protected]", "Subject", "Body", link_url: "http://example.com", image_url: "http://example.com/test.jpg")

oauth_link(alias)

This function generates a link for the requested integration which starts the OAuth authorization flow.

The one required argument is the name of the provider or alias of which integration to start:

say oauth_link("google")

See API integrations

query(recipient, name, payload \\ [])

Sends an event to the given user, and waits for the reply.

reply = query :master, "ping"
say reply

In the other script, define a task or dialog that catches the ping event, and use the reply construct to send a payload back:

task event: "ping" do
  reply "pong"
end

Make sure that the handling task / dialog in the other process finishes quickly. If there is no reply received within 1 second, the value :timeout is returned in the calling process.

See Communication and coordination

spawn_group(group \\ nil, context \\ %{})

Spawn a group process.

uniq_group()

Generate a unique identifier for a group process.

yaml_build(data)

Convert a given value to a string encoded as YAML.

yaml_parse(string)

Convert the given JSON-encoded string to a data structure. Returns nil when decoding fails.