Free Trial
Sign In : Sign Up : Blog : Search: Language : Help :
Docs : User Manual : Self

Self

Overview

Self is Bot Libre's JavaScript dialect that has been extend to support natural language processing. You can program your bot using the Self scripting language from your bot's Script page.

The Self scripting language is a state machine based language for scripting chat bots, it also enables bots to alter and program their own scripts.

Classes

Class Description
Object Self defines several object method available to all objects.
String String processing methods.
Language Natural language processing methods.
Date Date and time processing methods.
Utils Common utility methods.
Math Math operations.td>
Http HTTP, HTML, XML, JSON and web service processing methods.
JSON JSON processing methods.
Facebook Facebook messaging methods.
Twitter Twitter messaging methods.
Telegram Telegram messaging methods.
Vision Image and vision messaging methods.
Context Context access methods.
Avatar Avatar, emotion, poses, action, and command accessing methods.


Operators

Operators Description Example
if If statement. if (value == null) { ... } else { ... }
for For statement. for (word in sentence.word) { ... }
while While statement. while (count < 10) { ... }
do Do statement. do { ... }
think The same as do but can be used inside a Template to perform some code but not print a value into the response. think { ... }
return Return the value. if (word == "hello") { return "hello there"; }
== Compare if two values match. apple == apple
!= Compare if two values don't match. apple != orange
< Compare if a value is less than another. if (time < 10) { greeting = "Good Morning!"; }
<= Compare if a value is less or equal than another. if (time <= 12) { greeting = "Have a Nice Day!"; }
> Compare if a value is greater than another. if (time > 12) { greeting = "Good Afternoon!"; }
>= Compare if a value is greater or equal than another. if (time >= 5) { greeting = "Nice Day!"; }
! negates a logical value negative = !negative;
&& Logical AND. if (x < 5 && y > 2) { ... }
|| Logical OR. if (x < 5 || y > 1) { ... }
= Variable assignment. name = "Alice";
++ Increment a variable. var step; for (step = 0; step < 5; step++) { ... }
-- Decrement a variable. var step; for (step = 10; step < 5; step--) { ... }
+ Add two numbers or concatenate two strings. txt1 = "John"; txt2 = "Smith"; txt3 = txt1 + " " + txt2;
- Subtract two numbers. var x = 5; var y = 2; var z = x - y;
* Multiply two numbers. var x = 5; var y = 2; var z = x * y;
/ Divide two numbers. var x = 10; var y = 2; var z = x / y;
new Construct a new object. response = new Sentence();
Symbol Create a new global symbol. Language.define(word, Symbol(word));
. Get a relationship from an object. age = speaker.age;
= Set a relationship on an object. response.word[0] = "Hello";
=+ Add a relationship on an object. sentence.response =+ response;
=- Remove a relationship on from object. sentence.response =- response;
random Select and execute random value. random ("Hello", "Hi", "Hey", "G'day mate");
redirect Evaluate the response to the phrase. redirect ("what is " + star);
srai Synonym for redirect (AIML syntax). srai ("hello");
request Evaluate the response to the phrase using a remote service. request (song, { service : #wikidata, hint : "performer"));
sraix Synonym for request (AIML syntax). sraix (song, { service : #wikidata, hint : "performer"));
learn Learn a new response. learn ( {pattern:"hello", template:"how are you" } );
eval Evaluate code within a learned pattern or template. learn ( {pattern:Pattern("what is {eval (star[0])}"), template:Template("{eval (star[1])}") } );
debug Print the arguments to the log. debug (star);

Object

Object Methods Description Example
get Get a relationship value from an object, optional index. speaker.get(#name), sentence.get(#word, 3)
getLast Get a relationship value from the end of an ordered relationship. conversation.getLast(#input, 1)
getWithAssociate Get a relationship value from an object most associate to the other value.
all Returns an array of all of the object's relationship values for the type. speaker.all(#name)
set Sets a relationship value on an object. speaker.set(#age, 44)
append Append the value to the end of the object's relationship. response.append(#word, ".")
appendWithMeta add a relationship value to the object with the relationship meta data
add Add a relationship value to the object. speaker.add(#name, "Bob")
addWithMeta Add a relationship value to the object with the relationship meta data.
weakAdd Add a relationship value to the object with a low correctness.
weakAddWithMeta Add a relationship value to the object with a low correctness with the relationship meta data.
delete Delete the relationship value. speaker.delete(#name, "Bob")
remove Remove the relationship value. speaker.remove(#name, "Bob")
removeWithMeta Remove the relationship value with the relationship meta data.
deleteAll Delete all the relationship values. speaker.deleteAll(#name),
delete Delete the object, (use this with caution). speaker.delete()
has Return if the relationship exists. speaker.has(#name, "Bob"), speaker.has(#name)
findReference Inverse references lookup.
findReferenceBy Inverse relationship lookup.

String

String Methods Description Example
charAt(index) Return the string's character at the index. "hello"charAt(0) == "h"
concat(text) Concatenate the two strings. "hello".concat(" world!") == "hello world!"
length() Return the string's length. "hello"length() == 5
substring(start, end) Return the string substring. "hello world".substring(0, 4) == "hell"
toLowerCase() Return the string as lower case. "HELLO".toLowerCase() == "hello"
toUpperCase() Return the string as upper case. "hello".toUpperCase() == "HELLO"
trim() Trim leading and trailing whitespace. "     Hello World!     ".trim() == "Hello World!"

Language

Language Methods Description Example
word Creates a compound word. Language.word("ball", "hockey")
sentence Creates a sentence. Language.sentence("How", "are", "you")
define Defines the word as meaning the value. Language.define("foobar", #foobar)

Date

Date Methods Description Example
date() Current Date object. var today = Date.date();
date(text) Convert the text or Timestamp to a Date. var xmas = Date.date("2017-12-25");
time() Current Time object. var time = Date.time();
time(text) Convert the text or Timestamp to a Time. var noon = Date.time("12:00:00");
timestamp() Current Timestamp object. var now = Date.timestamp();
timestamp(text) Convert the text or Date to a Timestamp. var yday = Date.timestamp("2017-10-02 16:52:30");
any(text) Parse any date/time format. var name = Date.parse("Sept 3, 2014")
add(date, part, time) Add the date value. var tomorrow = Date.add(Date.date(), #day, 1);
get(date, part) Return the date part. var day = Date.get(Date.date(), #day);
set(date, part, value) Set the date part. var day = Date.set(Date.date(), #day, 11);
interval(style, from, to) Computer the date/time interval.
interval(style, from, to, format) Computer the date/time interval.
getTimeZone() Return the default time zone. var gmt = Date.getTimeZone();
getTimeZone(zone) Return the dates time zone. var gmt = Date.getTimeZone("gmt");
setTimeZone(date, timezone) Set the dates time zone. var z = Date.setTimeZone(Date.date(), EST);
printAIMLDate(date, format) Print the date using the AIML format.
printDate(date, format) Print the date using Java SimpleDateFormat format. var d = Date.printDate(Date.date(), )

Utils

Util Methods Description Example
encode(text) Converts to URL encoded character. Http.requestXML("http://api.com/fetch?name=" + Utils.encode(name))
denormalize(text) Converts punctuation words back to characters. Utils.normalize("That is cool colon ) at dash at") == "That is cool :) @-@"
normalize(text) Converts punctuation characters to the word values. Utils.normalize("That is cool :) @-@") == "That is cool colon ) at dash at"
explode(text) Expands a string to its character values. Utils.explode("hello") == "h e l l o"
gender(text) Converts between 'he' and 'she'. Utils.gender("he likes her") == "she likes him"
person(text) Converts between 1st and 2nd person. Utils.person("I love myself") == "you love yourself"
person2(text) Converts between 1st and 3rd person. Utils.person("I love myself") == "he love himself"
capitalize(text) Converts the first character to upper case. Utils.person("hello there") == "Hello there"
sentence(text) Converts the first character to upper case. Utils.person("hello there") == "Hello there"
formal(text) Converts the first character to upper case for each word. Utils.person("hello there") == "Hello There"
lowercase(text) Converts to lower case. Utils.person("HELLO There") == "hello there"
uppercase(text) Converts to upper case. Utils.person("hello there") == "HELLO THERE"
program() Returns the current software name and version.
size() Returns to total knowledge base size (total objects).
version() Returns the current software version.
id() Returns the bot's internal id.

Math

Math Methods Description Example
add(x, y) Sum of x and y values. Math.add(2, 3); 5
subtract(x, y) Subtract y from x value. Math.subtract(8, 5); 3
multiply(x, y) Multiply x and y values. Math.multiply(2, 4); 8
divide(x, y) Divide x and y values. Math.divide(18, 9); 2
abs(x) Returns the absolute value of x. Math.abs(-7.7); 7.7
floor(x) Returns the value of x rounded down to its nearest integer. Math.floor(3.8); 3
ceil(x) Returns the value of x rounded up to its nearest integer. Math.ceil(2.2); 3
power(x, y) Returns the value of x to the power of y. Math.power(7, 2); 49
round(x) Returns the value of x rounded to its nearest integer. Math.round(4.3); 4
log(x) Math.log(8); 3
ln(x)
sin(x) Returns the sine of x (x is in radians). Math.cos(0); 1
asin(x)
cos(x) Returns the cosine of x (x is in radians).
acos(x)
tan(x) Returns the tangent of an angle.
tanh(x)


Http

Http Description Example
toJSON(object) Convert an object to JSON text.
toXML(object) Convert an object to XML text.
encode(text) URL encode the text.
requestJSON(url) Fetch the JSON response.
requestJSON(attribute, url) Fetch the JSON response.
requestJSON(attribute, url, headers) Fetch the JSON response. Pass custom headers as JSON object.
requestJSONAuth(attribute, url, user, password) Call authenticated API and fetch the JSON response.
requestXML(url) Fetch the XML response.
requestXML(url, xpath) Fetch the XML response.
requestXML(url, xpath, headers) Fetch the XML response. Pass custom headers as JSON object.
requestXMLAuth(url, user, password, xpath) Call authenticated API and fetch the XML response.
requestHTML(url, xpath) Scrape the HTML page.
requestHTML(url, xpath, format) Scrape the HTML page, return #text, #array, #html, or #object.
requestHTML(url, xpath, format, subformat) Scrape the HTML page, return #array of #text, #html, or #object.
requestCSV(url) Parse the CSV file.
requestText(url) Return the raw text data.
requestText(url, headers) Return the raw text data. Pass custom headers as JSON object.
rss(url) Fetch the last RSS feed.
rssFeed(url) Fetch the entire RSS feed.
postJSON(url, object) Post the JSON object to the URL.
postJSONAuth(url, user, password, object) Post the JSON object to the URL.
postXML(url, object) POST the XML object to the URL.
postXML(url, object, xpath) POST the XML object to the URL. Extract the XPath data.
postXMLAuth(url, user, password, object, xpath) Post the XML object to the URL. Extract the XPath data.
postHTML(url, params, xpath) Post the HTML form parameters to the URL. Extract the XPath data.
putJSON(object) PUT the JSON object to the URL.
delete(url) Send an HTTP DELETE to the URL.

JSON

JSON Description Example
parse(text) Parse an object from JSON text.
stringify(object) Convert an object to JSON text.

Facebook

Facebook Description Example
post(message) Post to the bot's Facebook page.
postComment(comment, postid) Post to the bot's Facebook page.
sendMessage(message, userid) Send a message to a user.

Twitter

Twitter Description Example
tweet(message) Tweet to the bot's Twitter account.
sendMessage(message, userid) Send a direct message to a user.

Telegram

Telegram Description Example
post(message) Post to the bot's Telegram channel.
sendMessage(message, userid) Send a message to a user.

Vision

Vision Description Example
loadImage(url) Load the image into the bot's memory.
matchImage(url, tag, error) Search for the closest matching image for the tag.

Context

Context Description Example
push(object) Push the object to the current context stack.
top() Return the top of the context stack.
top(index) Return the nth top of the context stack.
search(match) Search the context stack for a matching object.

Avatar

Avatar Description Example
setAction(action) Set the avatar's action.
setPose(pose) Set the avatar's pose.
setCommand(command) Set a JSON command object.

State Operations

State Operation Description Example
state A state defines the current input processing. pattern "my name is *" template Template("Pleased to meet you {star}");
case A case can transition to another state if the case variable matches the current input. case "lol" template "Very funny."
pattern A pattern can match an input and evaluate a template response. pattern "hello" template "Hi there";
answer An answer of a state is evaluated if the input processing is complete. answer Template("Pleased to meet you {star}");
function An function can be called from an answer or another function. function todayResponse() { var response = new (#sentence); response.append(#word, "Hello World!"); return response; }
var A variable can be matched with the current input, or store context. var name { instantiation : #name; }

Examples

Here example of self script that counts words:

// Example script that counts words. state CountWords { pattern "count words in *" answer countWords(); function countWords() { var words = Language.sentence(star); var count = 0; for (word in words.word) { count = count + 1; } return Template("There are {count} words."); } }


Here example of self script that repeat words:

// Example script that repeat words. state Repeat { pattern "repeat * by * times" answer repeat(); function repeat() { var response = ""; var repeat = star[1].toNumber(); var count = 0; while (count < repeat) { response = response + " " + star[0]; count = count + 1; } return response; } }


See Also