Skip to content

Builtin functions

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:

String functions

capitalize(string)

Capitalizes the first word in the string

Examples:

capitalize("this is a string")
"This is a string"

downcase(string)

Converts a string to lowercase Examples:

downcase("HOW ARE YOU?")
"how are you?"

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)

Examples:

pluralize("Dog")
"Dogs"

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

Replace matches of a regular expression in the given string with a replacement

Options:

  • flags: String with regex flags, defaults to "u" (unicode support). For case insensitive regexes, use "iu"

  • global: Boolean to check if regex needs to replace all occurrences or only the first one. Defaults to true.

Examples:

regex_replace("hello to all the cats", "cat", "dog")
"hello to all the dogs"
regex_replace("The cheese is 5 euros, eggs are 1 euro", "euros?", "pound")
"The cheese is 5 pound, eggs are 1 pound"

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

Replace string in the given string with a replacement. The pattern can be a string or a list of strings.

Examples:

replace("abc", "a", "b")
"bbc"
replace("abc", ["a", "b"], "")
"c"

singularize(string)

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

Examples:

singularize("dogs")
"dog"

string(value)

Coerce the given value into a string value

trim(string)

Trim whitespace characters from both ends of a string.

Examples:

trim("         slim me down        ")
  "slim me down"

trim(string, what)

Trim given characters from both ends of a string.

Examples:

trim("^^^Remove^^^", "^")
  "Remove"

trim_leading(string)

Trim leading whitespace characters from a string.

Examples:

trim_leading("      Leading")
  "Leading"

trim_leading(string, what)

Trim given leading characters from a string

Examples:

trim_leading("***Stars", "*")
  "Stars"

trim_trailing(string)

Trim trailing whitespace characters from a string

Examples:

trim_trailing("trailing   ")
  "trailing"

trim_trailing(string, what)

Trim given trailing characters from a string

Examples:

trim_trailing("trailing))))", ")")
  "trailing"

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.

Examples:

truncate("a very long string", 2)
"a…"

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.

Examples:

truncate_words("Truncates a string down to the number of words passed", 3)
"Truncates a string…"
truncate_words("Truncates a string down to the number of words passed", 3, ", read more")
"Truncates a string, read more"

upcase(string)

Converts a string to uppercase Examples:

upcase("am I shouting?")
"AM I SHOUTING?"

url_decode(string)

Decode escaped URL characters

Examples:

url_decode("a%3Dvalue")
"a=value"

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.

Examples:

url_encode("var=this is a value")
  "var%3Dthis+is+a+value"

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.

Examples:

url_params([page: 1, id: 2])
  "page=1&id=2"

List (array) functions

difference(list1, list2)

Returns a list where the items in list2 are removed from list1.

Note that the resulting list will not be sorted.

Examples:

difference([1, 2, 3], [2, 3])
[1]

filter(list, query)

Filter list of maps according to a MatchEngine query.

first(list)

Return the first item in a list

Examples:

first([1, 2, 3])
1

flatten(list)

Flatten a list using Elixir's List.flatten/1.

Examples:

flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
flatten([[1, 2], []])
[1, 2]

intersection(list1, list2)

Returns the set-intersection of two lists.

Note that the resulting list will not be sorted.

Examples:

intersection([1, 2, 3], [2, 3]) 
[2, 3]

item(ets, index)

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

Examples:

item([1, 2, 3, 4], 1)
2
item([[1, 2], [3, 4]], 1)
[3, 4]

join(list, joiner)

Join the given list using a string.

Examples:

join(["06", "121", "448", "66"], "-")
  "06-121-448-66"

join(list, joiner, last_joiner)

Join the given list using a string.

The last_joiner string will be used to join the last two items in the list. This helps with joining strings in a "human readable" way:

Examples:

"The candidates are: " + join(["John", "Mary", "Elsa"], ", ", " and ")
"The candidates are: John, Mary and Elsa"

join_and(input, opts \\ [])

Joins a list of items in the current users locale, or in the specified locale.

Given options are passed to join_localized.

Examples:

join_and(["1", "2", "3"])
"1, 2, and 3"

join_localized(list, opts \\ [])

Presents the list in a human localized to the language set by the locale option.

Available options: - locale: A locale string, default is "en". - style: The style to join the list in, default :standard, available: [:or, :or_narrow, :or_short, :standard, :standard_narrow, :standard_short, :unit, :unit_narrow, :unit_short]

Examples:

join_localized([1, 2, 3, 4], locale: "en")
"1, 2, 3, and 4"
join_localized(["John", "Mary", "Elsa"], locale: "fr")
"John, Mary et Elsa"
join_localized(["John", "Mary", "Elsa"], locale: "fr", style: :or)
"John, Mary ou Elsa"
join_localized(["John", "Mary", "Elsa"], locale: "en", style: :or)
"John, Mary, or Elsa"
join_localized(["John", "Mary", "Elsa"], locale: "en", style: :unit)
"John, Mary, Elsa"
join_localized(["John", "Mary", "Elsa"], locale: "en_GB.FORMAL", style: :unit)
"John, Mary, Elsa"

join_or(input, opts \\ [])

Joins a list of items in the current users locale, or in the specified locale.

Examples:

join_or(["1", "2", "3"])
"1, 2, or 3"

keys(ets)

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.

Examples:

keys(%{a: :b, b: :c})
[:a, :b]

last(list)

Return the last item from a list

Examples:

last([1, 2, 3])
3

pluck(list, keys)

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

Examples:

pluck([%{name: "John", age: 42, job: "Designer"}, %{name: "Mary", age: 36, job: "Programmer"}], [:name, :job])
[%{name: "John", job: "Designer"}, %{name: "Mary", job: "Programmer"}]

score(list, query)

Score a list of maps according to a MatchEngine query.

shuffle(list)

Shuffle the given list, putting its contents in random order.

sort(enum, opts \\ [])

Sort a list.

Options: - direction: either :asc or :desc - field: when sorting a list of maps, specify which field in the maps to sort on.

Examples:

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

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

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

Options (doc):

  • :parts (positive integer or :infinity) - the string is split into at most as many parts as this options specifies. If :infinity, the string will be split into all possible parts. Defaults to :infinity.

  • :trim (boolean) - if true, empty strings are removed from the resulting list.

Examples:

split("this will be a list", " ")
  ["this", "will", "be", "a", "list"]
split("one, two, three", ",", parts: 2)
  ["one", " two, three"]
split("one, two, three,", ",", trim: true)
  ["one", " two", " three"]

subset?(list1, list2)

Determine whether all items in list1 are also in list2. Returns true or false.

Examples:

subset?([2, 3], [1, 2, 3])
true
subset?([1, 2, 3], [1, 2, 3])
true
subset?([], [1, 2, 3])
true
subset?([4, 5], [1, 2, 3])
false

union(list1, list2)

Returns the set-union of two lists.

Note that the resulting list will not be sorted.

Examples:

union([1, 2, 3], [2, 3])
[1, 2, 3]
union([4, 5], [2, 3])
[2, 3, 4, 5]

uniq(list)

Return a list with unique elements (no duplicates)

Examples:

uniq([1, 2, 2, 3, 3, 3])
[1, 2, 3]

values(ets)

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.

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.

Date functions

date_diff(a, b, granularity)

Get the difference between two dates.

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

  • :years
  • :months
  • :calendar_weeks (weeks of the calendar as opposed to actual weeks in terms of days)
  • :weeks
  • :days
  • :hours
  • :minutes
  • :seconds
  • :milliseconds
  • :microseconds
  • :duration

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.

Examples:

date_diff("2020-06-10T00:00:00+00:00", "2021-06-10T00:00:00+00:00", :years)
-1
date_diff("2020-06-10T00:00:00+00:00", "2020-08-10T00:00:00+00:00", :months)
-2
date_diff("2020-06-10T00:00:00+00:00", "2020-06-13T00:00:00+00:00", :days)
-3
date_diff("2020-06-10T12:50:00+00:00", "2020-06-10T09:50:00+00:00", :hours)
3
date_diff("2020-06-10T12:50:00+00:00", "2020-06-10T12:00:00+00:00", :minutes)
50
date_diff("2020-06-10T12:50:00+00:00", "2020-06-10T12:50:10+00:00", :seconds)
-10

date_format(date, format_string, opts \\ [])

Formats an UTC ISO8601 time string.

Expects an ISO date string, and a format string. For the syntax of the date format string, see the documentation of the Timex date formatter.

The third argument can be the following options:

  • locale -- Select the locale to use while formatting, for formatting month names, day names et cetera.

  • formatter -- Specify the the formatter module to use. Set to :strftime to select the alternative strftime formatter.

Examples:

date_format("1990-10-10T00", "{YYYY}/{M}/{D}")
"1990/10/10"
date_format("2012-12-12T00", "{WDfull} {D} {Mfull} {YYYY}")
"Wednesday 12 December 2012"

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(value, 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: - format - when format is given, parsing is done using Timex.parse, otherwise, parsing is done using Duckling. - locale - the locale used for parsing (in case of Ducking parser), defaults to en_US - timezone - the timezone used for parsing (in case of Ducking parser), defaults to Europe/Amsterdam

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.

Examples:

date_parse("1990-01-01")
  "1990-01-01T00:00:00.000+01:00"

date_part(date, part)

Get a component of the given datetime.

The component name is one of the following:

  • :year
  • :month
  • :day
  • :hour
  • :minute
  • :second

Returns nil when an invalid part was given.

Examples:

date_part("2020-06-10T00", :year)
2020
date_part("2020-06-10T00", :month)
06
date_part("2020-06-10T00", :day)
10
date_part("2020-06-10T12:50:00+00:00", :hour)
12
date_part("2020-06-10T12:50:00+00:00", :minute)
50
date_part("2020-06-10T12:50:00+00:00", :second)
0

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:

  • years
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds
  • milliseconds
  • microseconds

See the Timex manual.

Examples:

date_shift("2020-06-10T00:00:00+00:00", years: 1)
"2021-06-10T00:00:00+00:00"
date_shift("2020-06-10T00:00:00+00:00", months: 2)
"2020-08-10T00:00:00+00:00"
date_shift("2020-06-10T00:00:00+00:00", days: 03)
"2020-06-13T00:00:00+00:00"
date_shift("2020-06-10T12:50:00+00:00", hours: -3)
"2020-06-10T09:50:00+00:00"
date_shift("2020-06-10T12:50:00+00:00", minutes: -50)
"2020-06-10T12:00:00+00:00"
date_shift("2020-06-10T12:50:00+00:00", seconds: 10)
"2020-06-10T12:50:10+00:00"

date_truncate(date, precision)

Returns the given datetime with the microsecond field truncated to the given precision.

The precision is one of the following:

  • :year
  • :month
  • :day
  • :hour
  • :minute
  • :second
  • :millisecond

Returns nil when an invalid date or invalid precision was given.

relative_date(amount, unit, locale \\ "en", style \\ :default)

Formats a date to a string relative to the current moment.

Arguments: - unit is the time unit for the formatting. Units are: - :second, - :minute, - :hour, - :day, - :week, - :month, - :year.

Days of the week are also units: :mon, :tue, :wed, :thu, :fri, :sat, :sun, :quarter
  • locale, the locale code for the language to format the date in, e.g. "en", "fr", "de"
  • style, the style that is used to format the date, can be :default, :narrow, or :short

Examples:

relative_date(1, :day, "en")
"tomorrow"
relative_date(1, :hour, "fr")
"dans 1 heure" 

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

card_template(opts)

Creates a card template. A card template is a gallery template with only one item. This is not supported on Facebook Messenger, only on web and google assistant.

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/…"

Locale functions

describe_locales(locales \\ [], opts \\ [])

Returns all the available languages from the list of locales of the current bot, if no list of locales is provided. The result is a list in which each item is a map containing a language and a label key.

Options:

  • locale: The output locale; defaults to the user's current locale. Available locales are: nl, en, es, it, pt, de, fr.

Examples:

describe_locales(["en_US"])
[%{"language" => "en", "label" => "English"}]

extract_language(message)

Will extract the language from a given string and return the locale code."

Examples:

extract_language("I want to speak French")
"fr"
extract_language("Sprichst du Deutsch?")
"de"
extract_language("Do you speak Italian?")
"it"

humanize_duration(value, opts)

Will format a time duration in a human form, spelling out the quarters and halves of hours.

The following opts are available:

  • locale: supported locales are: "en", "fr", "de", "it", "es", "pt", "nl".
  • format: describes the way numbers should be formatted. Available formats:
    • :standard, default, will represent the numbers as numbers: 1 will be formatted as "1".
    • :spellout, will spell the numbers in words: 1 will be formatted as "one".

Examples:

humanize_duration(36, "hour", locale: "en")
"a day and a half"
humanize_duration(1.5, "hour", locale: "en")
"an hour and a half"
humanize_duration(150, "minute", locale: "en")
"2 and a half hours"
humanize_duration(150, "minute", format: :spellout)
"two and a half hours"
humanize_duration(1.5, "month", format: :spellout)
"a month and a half"
humanize_duration(42, "month", format: :spellout)
"three and a half years"
humanize_duration(0.5, "hour", locale: "nl")
"een half uur"
humanize_duration(1.5, "hour", locale: "nl")
"anderhalf uur"
humanize_duration(1.5, "minute", locale: "nl")
"anderhalve minuut"
humanize_duration(1.575, "hour", locale: "nl", format: :spellout)
"een uur, vier­en­dertig minuten en dertig seconden"
humanize_duration(0.5, "minute", locale: "nl")
"een halve minuut"
humanize_duration(30, "minute", locale: "fr")
"une demi-heure"
humanize_duration(18, "month", locale: "fr")
"un an et demi"
humanize_duration(90, "minute", locale: "de")
"anderthalb Stunden"
humanize_duration(150, "minute", locale: "de", format: :spellout)
"zweieinhalb Stunden"

humanize_locale(locale_to_humanize, opts \\ [])

Returns the name of a language in a specified language.

Options:

  • locale: The output locale; defaults to the user's current locale. Available locales are: nl, en, es, it, pt, de, fr.

Examples:

humanize_locale("nl", locale: "nl")
"Nederlands"
humanize_locale("en", locale: "fr")
"anglais"

locale_supported?(locale, available_locales \\ nil)

Returns true if the given locale is supported by the current bot.

When available_locales is left nil, it will default to the locales of the current bot. Otherwise, when it's a list, the function will check whether the language of the given locale matches one of the languages of the given locales.

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.

Examples:

contains("my name is", "name")
  true
contains([1, 2, 3], 3)
  true
contains("", "a")
  false
contains([], [])
  false

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.

Examples:

distance([4.893414, 52.364909], [4.8952, 52.3702])
  600.6996152390233

entity(args)

Construct a new entity

event(name)

Construct an event for use in expecting:

extract(sentence, entity, world_module, world_state)

Given an input sentence and a match specification, extracts the information from the sentence.

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.

Examples:

length("hello")
  5
length([1, 2, 3])
  3

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.

Examples:

  random(10)
  2

reverse(string)

Reverse the given list or string.

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

Examples:

reverse("abcd")
  "dcba"
reverse([1, 2, 3])
  [3, 2, 1]

slice(string, startpos, endpos \\ nil)

Slice a substring out of the given string, or a sublist out of the given list. Arrays and strings are 0-indexed, meaning that the first element has the position of 0.

If no endpos is given, the array or list will be sliced until the end.

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

Examples:

slice("a slice of bread", 11)
  "bread"
slice("a slice of bread", 2, 5)
  "slice"
slice([1, 2, 3], 0, 1)
  [1]

take_random(enumerable, count)

Take a number of items from a list, map or string at random.

take_random("hello", 2) # "ol"
take_random([1, 2, 3], 2) # [3, 2]
take_random(%{1 => "a", 2 => "b", 3 => "c"}, 2) # %{1 => "a", 3 => "c"}

XML functions

xml_build(data)

Build an XML string out of a data structure.

Examples:

xml_build(["element", %{"attr" => "val"}, "content"])
"<element attr="val">content</element>"

xml_parse(data)

Parse an XML string into a data structure.

Examples:

xml_parse("<element attr="val">content</element>")
["element", %{"attr" => "val"}, "content"]

xml_xpath_all(data, query)

Select a list of values or XML elements

Selects a list of values or XML elements from the given XML using an XPath expression. Always returns a list. In the case that no elements were selected, an empty list is returned.

xml_xpath_one(data, query)

Select a single value or XML element

Selects a single value or XML from the given XML data structure using an XPath expression. If the result of the expression is not exactly one single element, nil will be returned.

Additional builtin functions

_(msgid)

Mark a given string as translatable.

For example:

say _("Hello world")

For more information, see the translation guide.

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
cancel_emit schedule_id

When you give the scheduled event a name, it can also be cancelled using that name:

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

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_pwa")

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_pwa", g: group)

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

say chat_link("web_pwa", user_id: some_user_id)

Account linking

To create a link which leads into a user's session and then aliases your current user ID to the new user ID, use user_id combined with alias_user_id (which is the "old" user id):

say chat_link("web_pwa", user_id: some_user_id, alias_user_id: user.user_id)

delete_token(token_id)

Delete a given token ID

See API integrations

detect_language(text)

Detect the language of the given text, using the Google Natural Language processing API.

Only works when your account has Dialogflow support enabled.

end_session()

Stop the interaction.

Note: deprecated: use stop instead

escalate(reason \\ "Assistance required", opts \\ [])

Send an escalation message to the operators of this bot.

The operators which are on call are notified, either in the studio, by web push notification, or with email. The return value is true when an operator could be reached, or false if there were no operators on call.

The reason that can be passed in is supposed to be a human-readable message, describing why the bot needed to hand over the conversation. It is sent as the subject of the email and push notification.

Options can include:

  • to: - the audience of the escalation. This is either a role tag (to: "tag:finance"), which will send the escalation to all roles with the finance tag; an array of tags: to: ["tag:finance", "tag:frontdesk"]; or a user id of a user in the studio: to: "studio:68eafe876f8a6e87a6e"

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_available_operators()

Get all operators which are on call. Returns a list of user id, name and profile picture.

get_dialog_locale()

Return the locale in which the bot is currently talking to the user.

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

get_users_by_email(email)

Retrieve user details for all users that are registered with the given email address. Used for account linking.

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.

Returns a link to this conversation in the inbox of the Botsquad Studio.

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.

log(value)

Logs a debugging statement in the chat session's stream.

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

Sends a notification e-mail to the given user.

mail("user@example.com", "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:

  • cc: a list of email addresses to put in the CC field
  • bcc: a list of email addresses to put in the BCC field
  • link_url: can be used to render a button below the text, which will link to the given URL.
  • link_caption: The optional caption of the button, defaults to "Open link"
  • image_url: The URL of an image to show below the text (and below the button). When link_url is also set, the image links to the link URL as well.
  • unsubscribe_url: The URL where the recipient can go to unsubscribe theirselves from messages like this. When set, an 'unsubscribe' option will be added to the mail message's footer.
  • locale: The locale to localize the unsubscribe link in. Defaults to en.
mail("user@example.com", "Subject", "Body", link_url: "http://example.com", image_url: "http://example.com/test.jpg")

See e-mail handling for more information on the mail capabilities of the platform.

mustache(template, context)

Render a mustache template with the given variables.

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

phone_parse(phone, default_country \\ "NL")

Parse a phone number and return it in normalized, international format.

phone_parse("0612345678")"+31612345678"

When no country code is given in the input, the number is assumed to be local to the default country.

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

read_script(title)

Read a script file by name, returning its text.

resolve_dialogflow_intent(text, lang \\ nil)

Check if the given text resolves to a dialogflow intent

If an intent matches it returns the intent structure, otherwise nil.

Like the global intent matcher, this function looks first in a locally defined Dialogflow agent (if the dialogflow Google Service account JSON file was found); otherwise it uses the globally-available Botsquad-Defaults Dialogflow agent.

shorten_url(url)

Create a shortened URL, for use in SMS messages and such.

The shortened URLs are scoped to the current bot and, as such, are removed when the bot is removed. Shortening the same URL again returns the same short URL.

Only HTTP and HTTPS URLs can be shortened. Giving invalid input to the function returns nil instead of a short URL.

sms_notify(phone, message)

Send a notification SMS message to the given phone number.

The phone number must be specified in full international format, e.g. +31641345678. The sender of the SMS is the fixed Botsquad notification number.

In order for this function to work, you need to have setup a Twilio connection to your existing SMS service. Read more about SMS handling

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

Spawn a group process.

strip_emoji(string)

Remove any emoji from a given string.

strip_markdown(string)

Remove Markdown formatting from a given string.

tag?(tag)

Retrieve the value of a prefixed tag, or true / false for a normal tag, for the tags that are set on the current conversation.

tag "workflow::assigned"
say tag?("workflow")

Will say assigned.

tag "hello"
if tag?("hello"), do: say "Hello is set"

testing?()

Helper function for checking whether the bot is running as part of a test case

Returns true if that is the case, or false otherwise.

Using this function can help you switching parts of your bot (mocking data, HTTP calls etc.) when the bot tests are being run.

unidecode(text)

Transliterate a string with accented characters to a plain ASCII version without any accents or special symbols.

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.