Cloud Script API
Telerivet's Cloud Script API lets you easily build powerful mobile messaging services on top of the Telerivet platform in just a few lines of code, without needing to run your own servers,
and without even needing to install developer tools on your computer.
For example, you can use Telerivet's cloud script API to:
- Integrate your SMS service with external APIs, such as weather forecasts, commodity prices, Wikipedia articles, CRM systems like Salesforce, or other web applications
- Parse data from incoming SMS messages, and save it as custom contact information or as rows in a custom data table
- Create custom automated conversation flows
- Call nearly any function from Telerivet's REST API without needing to install any software or run your own servers
Telerivet's script engine is based on JavaScript. Your scripts can use the objects and functions defined in the core JavaScript language, as well as the additional objects and functions defined here.
Telerivet's script engine is designed to be easy to use by even beginner programmers. However, some basic knowledge of JavaScript is necessary to write your own scripts.
For a general introduction to programming in JavaScript, see Codecademy's JavaScript tutorial.
|
Example Script
|
Creating and Running Scripts
To create a script, add a new service in your Telerivet project and click "Cloud Script API", or click the button below:
Create New Script
Then, you can write the JavaScript code for your script directly in your browser. There are no developer tools to install.
When you create a Cloud Script API service, Telerivet will call your main() function when the service is triggered.
After you save the service, your script will run automatically whenever your service is triggered, most commonly when you receive an incoming message.
Note that Telerivet scripts execute in a secure sandbox on Telerivet's cloud servers, not in your web browser.
Telerivet's cloud-based script engine invokes scripts synchronously and waits for them to complete. Each script invocation must complete within 8 seconds or Telerivet will terminate it.
For scripts you write in the browser, the maximum script size is 100 KB, or 20 KB for scripts as part of a "run JavaScript code" rule in a Custom Actions service.
To create longer scripts, you can import code from an external Git repository (see example).
Using an external Git repository also makes it possible to use your preferred code editor, use source control to track version history, and reuse code across multiple projects.
Connect External Git Repo
|
|
Examples
Retrieving data from your Telerivet account
Using the code below, anyone can text the first part of a person's name, and Telerivet will return the full names and phone numbers of up to 5 matching contacts from your Telerivet contact database:
|
Example SMS Conversation
john
John Jackson 5550123
John Jacobson 5550325
John Jenkins 5550818
zardoz
No contacts found starting with 'zardoz'.
|
Collecting and storing data in your Telerivet account
The code below allows election monitors to submit structured reports via SMS in the format precinct_id#num_voters#num_turned_away .
All reports are stored in a data table in your Telerivet account.
|
Example SMS Conversation
5241#123#20
Your election report has been recorded!
Precinct ID: 5241
Num Voters: 123
Num Turned Away: 20
|
Creating custom conversation flows
The code below defines an automated conversation that allows people to register via SMS. The conversation prompts the user first to enter their name, then their email address, and
updates their contact information in your database.
For more about automated conversations, see ContactServiceState.
|
Example SMS Conversation
JOIN
What is your name?
John Smith
Hi, John Smith. What is your email address?
john.smith@example.com
Thanks! You are now registered.
|
Interacting with JSON APIs
The code below uses the CoinDesk API to send an SMS auto-reply with the current exchange rate of Bitcoin to US dollars.
Interacting with JSON APIs is easy using JSON.parse and JSON.stringify .
For more about making requests to external APIs, see httpClient.request.
|
Example SMS Conversation
|
Interacting with XML APIs
The code below lets the user send a text containing a 5-digit US zipcode, and uses the Yahoo Weather's RSS API to send an SMS auto-reply with the current weather conditions.
Interacting with XML APIs is easy using DOMParser and XMLSerializer.
|
Example SMS Conversation
94111
It is currently 62 degrees Fahrenheit and Mostly Cloudy in San Francisco, CA.
|
Creating custom USSD services
If you connect a USSD access code to Telerivet, you can implement services that handle incoming USSD requests using the Cloud Script API
functions sendReply, promptDigits, and addInputHandler. The code below implements a USSD account menu protected by a PIN.
|
Example USSD Session
*123#
Welcome to the example service! Please enter your PIN.
1234
1 - show balance
2 - change PIN
1
Your balance is 25.
|
Creating custom IVR call flows
If you have a route that supports Interactive Voice Response (IVR), you can use the Cloud Script API to define a call flow for incoming and outgoing voice calls.
IVR services can play recorded audio (playAudio) or dynamic text-to-speech messages (sayText and setVoice), prompt users for input via the keypad (promptKey, promptDigits, and addInputHandler), and record audio (recordAudio).
The example code below prompts the contact for their age and gender and adds them to a group, demonstrating voice menus and input validation.
|
Example voice call
If you want to register, press 1. Otherwise, press 2."
1
Please enter your age on the keypad, then press pound.
38
If you are male, press 1. If you are female, press 2. Otherwise, press any key.
2
Thank you for registering! We will be in touch. Goodbye!
|
JavaScript Language Support
Telerivet's script engine implements much of the ECMAScript 2015 (ES6) standard, as well as portions of ES2016/ES7, including:
const / let keywords
- Arrow functions
- Template strings
- Shorthand object properties
- Destructuring assignment
- Generator functions
for ..of loops
- Array.protoype.includes
- Exponentiation operator (
** )
Some ES2015 language features are not currently available in Telerivet's script engine, including:
import , export , and class keywords
- Default parameters (
function foo(arg = 1) )
- spread/rest operator (
... )
- Computed property names (
var foo = 'x'; var obj = {[foo]: 1} )
|
Example Script
|
Global Objects
Telerivet's script engine defines all of the standard built-in functions and objects defined the core JavaScript language,
including Math,
Date,
and RegExp.
Note that JavaScript DOM objects such as window and document , and functions like setTimeout and setInterval don't exist within Telerivet's script engine.
Telerivet's script engine does provide DOMParser and XMLSerializer for interacting with XML APIs and HTML documents.
In addition to the standard JavaScript objects, Telerivet's script engine provides the following additional global variables, functions, and objects that make it easy to build mobile messaging services.
Note that some global objects are only available for scripts in certain "contexts". For example, Telerivet provides the content variable and sendReply function for scripts that handle incoming messages,
but not for scripts that run at scheduled intervals.
contact |
Context: Message or voice call | state |
Context: Message or voice call The current state for the current contact on this service
| phone |
Context: Message or voice call | from_number |
Context: Message string The sender phone number of the current message (same as message.from_number)
| to_number |
Context: Message string The recipient phone number of the current message (same as message.to_number)
| content |
Context: Message string The content of the current message (same as message.content)
| word1, word2, word3 |
Context: Message string The first three words of the message content
| remainder1, remainder2, remainder3 |
Context: Message string The remainder of the message content after the corresponding words
| message_type |
Context: Message string The type of the current message (same as message.message_type)
| message |
Context: Message | call |
Context: Voice call | contact |
Context: Contact | state |
Context: Contact The current state for the current contact on this service
| transaction |
Context: AirtimeTransaction The current airtime transaction
| balance |
Context: AirtimeTransaction The current account balance, after sending the airtime transaction. An object with amount (float) and currency (string, currency code) properties.
| row |
Context: DataRow | table |
Context: DataRow | request |
Context: Webhook request The current webhook request
| service |
The current automated service
| project |
The current Telerivet project
| task |
The task that triggered this service
| $temp (e.g.) |
string, int, or bool Any variable name starting with '$' will be shared between the script engine and the rest of the Rules Engine.
| simulated |
bool True if the service was triggered via the simulator, false otherwise.
| return_value |
string, int, or bool The return value of this service invocation. (Setting this to true will prevent Telerivet from automatically falling-through to the next service)
| call |
Context: USSD session | global |
The JavaScript global object itself
|
| |
Context: Message or voice call sendReply(content, options)
Sends a text reply to the phone number that sent the incoming message.
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the reply message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendReply("Thanks for your message!");
|
Context: Message or voice call starMessage()
Adds a "star" to the current message.
ArgumentsNone Return Typeundefined | ExamplestarMessage();
|
Context: Voice call sayText(text, options)
Says text in the current voice call using a built-in text-to-speech voice.
Argumentstext | string, required | options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the text will be replaced with their current values.
Default: false |
Return Typeundefined | ExamplesayText("Hello there!");
|
Context: Voice call setVoice(lang, voiceId)
Changes the built-in text-to-speech voice used in subsequent calls to sayText.
Typically setVoice would be called once at the top of your script.
Argumentslang | string, required The language/locale to use for the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | voiceId | string, optional The ID of the text-to-speech voice to use. If the voice ID is not available for the given language, Telerivet will use the default voice for that language.
Possible Values: female, male Default: female (when available for given language) |
Return Typeundefined | ExamplesetVoice("en-GB", "male");
|
Context: Voice call playAudio(url)
Plays an audio file in the current voice call.
Argumentsurl | string, required The URL of the audio file (must start with http:// or https:// ). Audio files should be in mp3 format.
|
Return Typeundefined | ExampleplayAudio("https://telerivet.s3.amazonaws.com/example.mp3");
|
Context: Voice call recordAudio(variableName, options)
Records audio from the caller in MP3 format, saving the URL in call.vars[variableName].
If the user presses '#' to end the recording, the IVR flow will continue after the recording with state.id == variableName.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
Optionstimeout | int, optional Maximum number of seconds of silence to wait before ending the recording
Default: 8 | playBeep | bool, optional Whether or not to play a beep to indicate that the recording has started
Default: true | finishOnKey | string, optional A string containing one or more keys that the user can press to end the recording (0-9, *, #).
Default: # |
Return Typeundefined | ExamplerecordAudio("recording", {
timeout: 5,
playBeep: false,
finishOnKey: "*"
});
|
Context: Voice call promptKey(variableName, options)
Prompts the user to press a key on the keypad, saving the key (as a 1-character string) in call.vars[variableName].
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
Optionstimeout | int, optional Number of seconds to wait before continuing
Default: 10 | maxRepeats | int, optional Maximum number of times to repeat the previous playAudio or sayText action if no response is received before the timeout
Default: 1 |
Return Typeundefined | ExamplepromptKey("menu_option", {
timeout: 5,
maxRepeats: 2
});
|
Context: Voice call promptDigits(variableName, options)
Prompts the user to press one or more digits on the keypad, saving the digits (as a string) in call.vars[variableName].
The input may be terminated when either 1) a maximum number of digits is pressed, 2) a termination key is pressed (default: #), or 3) a certain amount of time has passed without additional input (default: 10 seconds).
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
OptionssubmitOnHash | bool, optional True if Telerivet should stop collecting input when the # key is pressed. The # key itself will not be included in the variable value.
Default: true | maxDigits | int, optional Maximum number of digits to collect
Default: 99 | timeout | int, optional Number of seconds to wait after the last key press before continuing (if maxDigits has not been reached and # key is not pressed when submitOnHash is true)
Default: 10 | maxRepeats | int, optional Maximum number of times to repeat the previous playAudio or sayText action if no response is received before the timeout
Default: 1 |
Return Typeundefined | ExamplepromptDigits("age", {
submitOnHash: true,
maxDigits: 3,
timeout: 5,
maxRepeats: 2
});
|
Context: Voice call forwardCall(phoneNumber)
Forwards the call to another phone number.
ArgumentsphoneNumber | string, required The phone number to dial.
|
Return Typeundefined | ExampleforwardCall("+14155550123");
|
Context: Voice call addInputHandler(variableName, callback)
Defines a callback function to handle input for a particular variable during a voice call.
Should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addInputHandler for each variable used in promptKey , promptDigits , or recordAudio .
When the input is received, the callback function will be called with one string argument that is equal to call.vars[variableName].
For promptKey , the argument to the callback function will be the key pressed, as a string.
For promptDigits , the argument to the callback function will be the digits pressed, as a string (not including the final #, if applicable).
For recordAudio , the argument to the callback function will be the URL of the recorded audio file.
If addInputHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsvariableName | string, required Variable name on the call
| callback | function, required Callback function with one string argument that will be called with the input value (same as call.vars[variableName])
|
Return Typeundefined | ExampleaddInputHandler("menu_option", function(input) {
sayText('You pressed ' + input);
});
|
Context: Voice call addEventListener(eventName, callback)
Defines a callback function to handle a named event.
Should be called every time the script runs (i.e., not inside the main() function).
Currently only the call_complete event is defined for voice calls.
Within an event listener callback function, any calls to sayText , playAudio , recordAudio ,
promptKey , promptDigits , forwardCall , or joinConference will be ignored.
ArgumentseventName | string, required Possible Values: call_complete | callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddEventListener("call_complete", function() {
console.log('Duration = ' + call.duration + ' sec');
});
|
Context: Voice call hangUp()
Hangs up the current voice call.
ArgumentsNone Return Typeundefined | ExamplehangUp();
|
Context: Contact sendMessageToContact(content, options)
Sends a text message to the current contact.
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToContact("Thanks for your message!");
|
waitForResponse(stateId, options)
Waits for the user to send a response message which will be handled by a callback function registered via addResponseHandler
(instead of the main function). This makes it easy to create stateful conversation flows.
If the timeoutDays or timeoutMinutes options are specified, the conversation will timeout after the specified
interval. An optional timeout handler function can be registered to run at that time, for example to re-prompt the user and call
waitForResponse again.
ArgumentsstateId | string, required ID of the next state in the messaging flow (same as first argument to addResponseHandler )
| options | object, optional |
OptionstimeoutDays | number, optional Number of days to wait before timeout (decimals allowed)
| timeoutMinutes | number, optional Number of minutes to wait before timeout (decimals allowed, though events are only triggered approximately once every 15 seconds)
| timeoutId | string, optional ID of a function registered via addTimeoutHandler . If timeoutId is not defined, the timeout will still occur after the specified time, but no action will be performed.
|
Return Typeundefined | ExamplewaitForResponse("email", {
timeoutMinutes: 60,
timeoutId: "email_timeout"
});
|
addResponseHandler(stateId, callback)
Defines a callback function to handle a particular response in a messaging flow.
addResponseHandler should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addResponseHandler for each variable used in waitForResponse .
If addResponseHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsstateId | string, required ID of the state in the messaging flow (same as argument to waitForResponse )
| callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddResponseHandler("email", function() {
sendReply('You said ' + content);
});
|
addTimeoutHandler(timeoutId, callback)
Defines a callback function to be called if no response was received within the timeout specified in waitForResponse .
addTimeoutHandler should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addResponseHandler for each timeoutId used in waitForResponse .
If addTimeoutHandler is called multiple times with the same timeout ID, only the last handler function will be called.
ArgumentstimeoutId | string, required ID of the state in the messaging flow (same as timeoutId option in waitForResponse )
| callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddTimeoutHandler("answer_timeout", function() {
sendReply("We didn't receive your answer... please reply.");
waitForResponse('answer');
});
|
sendMessage(toNumber, content, options)
Sends a text message to a phone number (using the default route).
For more advanced options, see project.sendMessage.
ArgumentstoNumber | string, required Phone number to send the message to
| content | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessage("+16505550123", "Hello");
|
sendMessageToGroup(groupName, content, options)
ArgumentsgroupName | string, required Name of group to send the message to
| content | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToGroup("Employees", "Good news, everyone!");
|
sendUSSD(mmiCode)
Sends a USSD request (using the default route).
For more advanced options, see project.sendMessage.
ArgumentsmmiCode | string, required The MMI/USSD code to send, e.g. *102#. Always ends in '#' character.
|
Return Typeundefined | ExamplesendUSSD("*102#");
|
sendEmail(options)
Sends a plain-text email notification from Telerivet's servers. The 'From' address will appear as 'Telerivet User'.
May also be called with three arguments like sendEmail(to, subject, body) .
ArgumentsOptionsto | string, optional Email address to send the email to.
| subject | string, optional | body | string, optional | replyTo | string, optional Reply-To email address (default is the email address of the organization owner)
| attachMedia | bool, optional If true, add any media files attached to this message as email attachments (only when service is triggered in the context of a message)
|
Return Typeundefined | ExamplesendEmail({
to: "nobody@example.com",
subject: "Email Notification",
body: "Your message content here",
replyTo: "me@example.com",
attachMedia: true
});
|
stopRules()
Prevents Telerivet from executing any rules after this script within the same service.
ArgumentsNone Return Typeundefined | ExamplestopRules();
|
replaceVariables(str)
Returns a string where placeholders for Rules Engine variables in double square brackets are replaced with the corresponding values in the current service context.
Argumentsstr | string, required String that may contain variable placeholders
|
Return Typestring | ExamplereplaceVariables("Hello, [[contact.name]]! You said: [[content]]");
|
Context: USSD session sendReply(text)
Displays text in the current USSD session.
ArgumentsReturn Typeundefined | ExamplesendReply("Hello there!");
|
Context: USSD session promptDigits(variableName)
Prompts the user to press one or more digits on the keypad, saving the digits (as a string) in call.vars[variableName].
The input may be terminated when either 1) a maximum number of digits is pressed, 2) a termination key is pressed (default: #), or 3) a certain amount of time has passed without additional input (default: 10 seconds).
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the USSD session
|
Return Typeundefined | ExamplepromptDigits("age");
|
Context: USSD session addInputHandler(variableName, callback)
Defines a callback function to handle input for a particular variable during a USSD session.
Should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addInputHandler for each variable used in promptDigits .
When the input is received, the callback function will be called with one string argument that is equal to call.vars[variableName].
If addInputHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsvariableName | string, required Variable name on the call
| callback | function, required Callback function with one string argument that will be called with the input value (same as call.vars[variableName])
|
Return Typeundefined | ExampleaddInputHandler("menu_option", function(input) {
sayText('You pressed ' + input);
});
|
Context: USSD session addEventListener(eventName, callback)
Defines a callback function to handle a named event.
Should be called every time the script runs (i.e., not inside the main() function).
Currently only the call_complete event is defined for USSD sessions.
Within an event listener callback function, any calls to sayText or promptDigits will be ignored.
ArgumentseventName | string, required Possible Values: call_complete | callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddEventListener("call_complete", function() {
console.log('Duration = ' + call.duration + ' sec');
});
|
Context: USSD session hangUp()
Ends the current USSD session.
ArgumentsNone Return Typeundefined | ExamplehangUp();
|
Context: USSD session sendMessageToContact(content, options)
Sends a text message to the current contact using the project's default route (not a USSD reply).
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToContact("Thanks for your message!");
|
httpClient.request(url, options)
Fetches a external URL over HTTP or HTTPS, such as an API or a web page.
Argumentsurl | string, required The URL to request. Must use http:// or https:// protocol; custom port numbers are not allowed.
| options | object, optional |
Optionsmethod | string, optional Possible Values: GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE Default: GET | params | object, optional An object to convert into query string parameters and append to the end of the URL (e.g. if params is {a:1,b:'hello world'}, Telerivet would append ?a=1&b=hello+world to the end of the URL)
| data | string or object, optional The content of a HTTP POST, PUT, or PATCH request. If this is an object, Telerivet will serialize the key/value pairs as URL-encoded params (e.g. {a:1,b:'hello world'} would be encoded as a=1&b=hello+world). If you want to send data as JSON instead, pass the result of calling JSON.stringify.
| headers | object, optional Key/value pairs for custom HTTP headers to send with the request
| basicAuth | string, optional A string in the format "username:password" to use for HTTP Basic authentication
| timeout | int, optional Timeout for the HTTP request in milliseconds. If the requested timeout is less than 1 ms or longer than the overall timeout for the service, the overall timeout for the service will be used instead.
|
Return Typeobject Return Value Propertiesstatus |
int
The HTTP response status code (e.g. 200, 404, etc.)
| content |
string
The content of the HTTP response
| headers |
object
A key/value map of the HTTP response headers
|
| Examplevar response = httpClient.request("http://api.example.com/rest", {
method: "POST",
params: {'foo': 2, 'bar': "hi"},
data: {'a': 1, 'b': "hello world"},
headers: {'X-Example': "example"},
basicAuth: "my_username:my_password"
});
|
require(path)
Includes and executes an external JavaScript module (see example).
This allows you to define scripts in your own source control system if desired, to reuse code across multiple services, and to build scripts larger than the 100 KB limit of Telerivet's web-based script editor.
External JS files may define JavaScript code that executes directly, or may export behavior via the CommonJS module format, i.e. by setting properties on the 'exports' variable.
Although this behaves similarly to the node.js require() function, Telerivet's script
engine is not node.js, and including node.js modules probably will not work.
Contact us for more information on connecting your source control system with Telerivet.
Argumentspath | string, required The path to the Javascript module. For the "top-level" call to require(), the path must be an path starting with 'ext/'
Modules may include additional modules using paths relative to the intial module URL, e.g. require('./foo')
All module paths must end with the '.js' extension. The path may optionally omit the trailing '.js'.
|
Return Type'exports' object from included script | Examplevar weather = require("ext/example/weather");
sendReply(weather.getWeatherForZIPCode('94111'));
|
console.log(str)
Displays a custom string to the simulator window (and saves it in the logs for your service), in order to help with debugging.
ArgumentsReturn Typeundefined | Exampleconsole.log("Kilroy was here");
|
console.trace()
Displays a stack trace to the simulator window (and saves it in the logs for your service), in order to help with debugging.
ArgumentsNone Return Typeundefined | Exampleconsole.trace();
|
MessageOrIVRCallGlobal
Global Variables:contact |
Context: Message or voice call | state |
Context: Message or voice call The current state for the current contact on this service
| phone |
Context: Message or voice call |
| |
Context: Message or voice call sendReply(content, options)
Sends a text reply to the phone number that sent the incoming message.
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the reply message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendReply("Thanks for your message!");
|
Context: Message or voice call starMessage()
Adds a "star" to the current message.
ArgumentsNone Return Typeundefined | ExamplestarMessage();
|
MessageGlobal
Telerivet's script engine defines all of the standard built-in functions and objects defined the core JavaScript 1.6 language, including Math, Date, JSON, and RegExp.
Note that JavaScript DOM objects such as window and document , and functions like setTimeout and setInterval do not exist within Telerivet's script engine.
Telerivet's script engine does provide DOMParser and XMLSerializer for interacting with XML APIs and HTML documents.
In addition, Telerivet's script engine provides the global variables, functions, and objects defined below.
Global Variables:from_number |
Context: Message string The sender phone number of the current message (same as message.from_number)
| to_number |
Context: Message string The recipient phone number of the current message (same as message.to_number)
| content |
Context: Message string The content of the current message (same as message.content)
| word1, word2, word3 |
Context: Message string The first three words of the message content
| remainder1, remainder2, remainder3 |
Context: Message string The remainder of the message content after the corresponding words
| message_type |
Context: Message string The type of the current message (same as message.message_type)
| message |
Context: Message |
| |
IVRCallGlobal
Global Variables:
| |
Context: Voice call sayText(text, options)
Says text in the current voice call using a built-in text-to-speech voice.
Argumentstext | string, required | options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the text will be replaced with their current values.
Default: false |
Return Typeundefined | ExamplesayText("Hello there!");
|
Context: Voice call setVoice(lang, voiceId)
Changes the built-in text-to-speech voice used in subsequent calls to sayText.
Typically setVoice would be called once at the top of your script.
Argumentslang | string, required The language/locale to use for the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | voiceId | string, optional The ID of the text-to-speech voice to use. If the voice ID is not available for the given language, Telerivet will use the default voice for that language.
Possible Values: female, male Default: female (when available for given language) |
Return Typeundefined | ExamplesetVoice("en-GB", "male");
|
Context: Voice call playAudio(url)
Plays an audio file in the current voice call.
Argumentsurl | string, required The URL of the audio file (must start with http:// or https:// ). Audio files should be in mp3 format.
|
Return Typeundefined | ExampleplayAudio("https://telerivet.s3.amazonaws.com/example.mp3");
|
Context: Voice call recordAudio(variableName, options)
Records audio from the caller in MP3 format, saving the URL in call.vars[variableName].
If the user presses '#' to end the recording, the IVR flow will continue after the recording with state.id == variableName.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
Optionstimeout | int, optional Maximum number of seconds of silence to wait before ending the recording
Default: 8 | playBeep | bool, optional Whether or not to play a beep to indicate that the recording has started
Default: true | finishOnKey | string, optional A string containing one or more keys that the user can press to end the recording (0-9, *, #).
Default: # |
Return Typeundefined | ExamplerecordAudio("recording", {
timeout: 5,
playBeep: false,
finishOnKey: "*"
});
|
Context: Voice call promptKey(variableName, options)
Prompts the user to press a key on the keypad, saving the key (as a 1-character string) in call.vars[variableName].
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
Optionstimeout | int, optional Number of seconds to wait before continuing
Default: 10 | maxRepeats | int, optional Maximum number of times to repeat the previous playAudio or sayText action if no response is received before the timeout
Default: 1 |
Return Typeundefined | ExamplepromptKey("menu_option", {
timeout: 5,
maxRepeats: 2
});
|
Context: Voice call promptDigits(variableName, options)
Prompts the user to press one or more digits on the keypad, saving the digits (as a string) in call.vars[variableName].
The input may be terminated when either 1) a maximum number of digits is pressed, 2) a termination key is pressed (default: #), or 3) a certain amount of time has passed without additional input (default: 10 seconds).
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the call
| options | object, optional |
OptionssubmitOnHash | bool, optional True if Telerivet should stop collecting input when the # key is pressed. The # key itself will not be included in the variable value.
Default: true | maxDigits | int, optional Maximum number of digits to collect
Default: 99 | timeout | int, optional Number of seconds to wait after the last key press before continuing (if maxDigits has not been reached and # key is not pressed when submitOnHash is true)
Default: 10 | maxRepeats | int, optional Maximum number of times to repeat the previous playAudio or sayText action if no response is received before the timeout
Default: 1 |
Return Typeundefined | ExamplepromptDigits("age", {
submitOnHash: true,
maxDigits: 3,
timeout: 5,
maxRepeats: 2
});
|
Context: Voice call forwardCall(phoneNumber)
Forwards the call to another phone number.
ArgumentsphoneNumber | string, required The phone number to dial.
|
Return Typeundefined | ExampleforwardCall("+14155550123");
|
Context: Voice call addInputHandler(variableName, callback)
Defines a callback function to handle input for a particular variable during a voice call.
Should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addInputHandler for each variable used in promptKey , promptDigits , or recordAudio .
When the input is received, the callback function will be called with one string argument that is equal to call.vars[variableName].
For promptKey , the argument to the callback function will be the key pressed, as a string.
For promptDigits , the argument to the callback function will be the digits pressed, as a string (not including the final #, if applicable).
For recordAudio , the argument to the callback function will be the URL of the recorded audio file.
If addInputHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsvariableName | string, required Variable name on the call
| callback | function, required Callback function with one string argument that will be called with the input value (same as call.vars[variableName])
|
Return Typeundefined | ExampleaddInputHandler("menu_option", function(input) {
sayText('You pressed ' + input);
});
|
Context: Voice call addEventListener(eventName, callback)
Defines a callback function to handle a named event.
Should be called every time the script runs (i.e., not inside the main() function).
Currently only the call_complete event is defined for voice calls.
Within an event listener callback function, any calls to sayText , playAudio , recordAudio ,
promptKey , promptDigits , forwardCall , or joinConference will be ignored.
ArgumentseventName | string, required Possible Values: call_complete | callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddEventListener("call_complete", function() {
console.log('Duration = ' + call.duration + ' sec');
});
|
Context: Voice call hangUp()
Hangs up the current voice call.
ArgumentsNone Return Typeundefined | ExamplehangUp();
|
ContactGlobal
Global Variables:contact |
Context: Contact | state |
Context: Contact The current state for the current contact on this service
|
| |
Context: Contact sendMessageToContact(content, options)
Sends a text message to the current contact.
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToContact("Thanks for your message!");
|
ResponseHandlerGlobal
| |
waitForResponse(stateId, options)
Waits for the user to send a response message which will be handled by a callback function registered via addResponseHandler
(instead of the main function). This makes it easy to create stateful conversation flows.
If the timeoutDays or timeoutMinutes options are specified, the conversation will timeout after the specified
interval. An optional timeout handler function can be registered to run at that time, for example to re-prompt the user and call
waitForResponse again.
ArgumentsstateId | string, required ID of the next state in the messaging flow (same as first argument to addResponseHandler )
| options | object, optional |
OptionstimeoutDays | number, optional Number of days to wait before timeout (decimals allowed)
| timeoutMinutes | number, optional Number of minutes to wait before timeout (decimals allowed, though events are only triggered approximately once every 15 seconds)
| timeoutId | string, optional ID of a function registered via addTimeoutHandler . If timeoutId is not defined, the timeout will still occur after the specified time, but no action will be performed.
|
Return Typeundefined | ExamplewaitForResponse("email", {
timeoutMinutes: 60,
timeoutId: "email_timeout"
});
|
addResponseHandler(stateId, callback)
Defines a callback function to handle a particular response in a messaging flow.
addResponseHandler should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addResponseHandler for each variable used in waitForResponse .
If addResponseHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsstateId | string, required ID of the state in the messaging flow (same as argument to waitForResponse )
| callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddResponseHandler("email", function() {
sendReply('You said ' + content);
});
|
addTimeoutHandler(timeoutId, callback)
Defines a callback function to be called if no response was received within the timeout specified in waitForResponse .
addTimeoutHandler should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addResponseHandler for each timeoutId used in waitForResponse .
If addTimeoutHandler is called multiple times with the same timeout ID, only the last handler function will be called.
ArgumentstimeoutId | string, required ID of the state in the messaging flow (same as timeoutId option in waitForResponse )
| callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddTimeoutHandler("answer_timeout", function() {
sendReply("We didn't receive your answer... please reply.");
waitForResponse('answer');
});
|
AirtimeTransactionGlobal
Global Variables:transaction |
Context: AirtimeTransaction The current airtime transaction
| balance |
Context: AirtimeTransaction The current account balance, after sending the airtime transaction. An object with amount (float) and currency (string, currency code) properties.
|
| |
DataRowGlobal
Global Variables:row |
Context: DataRow | table |
Context: DataRow |
| |
WebhookGlobal
Global Variables:request |
Context: Webhook request The current webhook request
|
| |
ServiceGlobal
Telerivet's script engine defines all of the standard built-in functions and objects defined the core JavaScript 1.6 language, including Math, Date, JSON, and RegExp.
Note that JavaScript DOM objects such as window and document , and functions like setTimeout and setInterval do not exist within Telerivet's script engine.
Telerivet's script engine does provide DOMParser and XMLSerializer for interacting with XML APIs and HTML documents.
In addition, Telerivet's script engine provides the global variables, functions, and objects defined below.
Global Variables:service |
The current automated service
| project |
The current Telerivet project
| task |
The task that triggered this service
| $temp (e.g.) |
string, int, or bool Any variable name starting with '$' will be shared between the script engine and the rest of the Rules Engine.
| simulated |
bool True if the service was triggered via the simulator, false otherwise.
| return_value |
string, int, or bool The return value of this service invocation. (Setting this to true will prevent Telerivet from automatically falling-through to the next service)
|
| |
sendMessage(toNumber, content, options)
Sends a text message to a phone number (using the default route).
For more advanced options, see project.sendMessage.
ArgumentstoNumber | string, required Phone number to send the message to
| content | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessage("+16505550123", "Hello");
|
sendMessageToGroup(groupName, content, options)
ArgumentsgroupName | string, required Name of group to send the message to
| content | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToGroup("Employees", "Good news, everyone!");
|
sendUSSD(mmiCode)
Sends a USSD request (using the default route).
For more advanced options, see project.sendMessage.
ArgumentsmmiCode | string, required The MMI/USSD code to send, e.g. *102#. Always ends in '#' character.
|
Return Typeundefined | ExamplesendUSSD("*102#");
|
sendEmail(options)
Sends a plain-text email notification from Telerivet's servers. The 'From' address will appear as 'Telerivet User'.
May also be called with three arguments like sendEmail(to, subject, body) .
ArgumentsOptionsto | string, optional Email address to send the email to.
| subject | string, optional | body | string, optional | replyTo | string, optional Reply-To email address (default is the email address of the organization owner)
| attachMedia | bool, optional If true, add any media files attached to this message as email attachments (only when service is triggered in the context of a message)
|
Return Typeundefined | ExamplesendEmail({
to: "nobody@example.com",
subject: "Email Notification",
body: "Your message content here",
replyTo: "me@example.com",
attachMedia: true
});
|
stopRules()
Prevents Telerivet from executing any rules after this script within the same service.
ArgumentsNone Return Typeundefined | ExamplestopRules();
|
replaceVariables(str)
Returns a string where placeholders for Rules Engine variables in double square brackets are replaced with the corresponding values in the current service context.
Argumentsstr | string, required String that may contain variable placeholders
|
Return Typestring | ExamplereplaceVariables("Hello, [[contact.name]]! You said: [[content]]");
|
USSDSessionGlobal
Global Variables:call |
Context: USSD session |
| |
Context: USSD session sendReply(text)
Displays text in the current USSD session.
ArgumentsReturn Typeundefined | ExamplesendReply("Hello there!");
|
Context: USSD session promptDigits(variableName)
Prompts the user to press one or more digits on the keypad, saving the digits (as a string) in call.vars[variableName].
The input may be terminated when either 1) a maximum number of digits is pressed, 2) a termination key is pressed (default: #), or 3) a certain amount of time has passed without additional input (default: 10 seconds).
The IVR flow will continue after the key press with state.id == variableName.
If promptKey is preceded by a call to playAudio or sayText, the user is allowed to press the key before the audio message is finished.
ArgumentsvariableName | string, required Variable name on the USSD session
|
Return Typeundefined | ExamplepromptDigits("age");
|
Context: USSD session addInputHandler(variableName, callback)
Defines a callback function to handle input for a particular variable during a USSD session.
Should be called every time the script runs (i.e., not inside the main() function).
There should be one call to addInputHandler for each variable used in promptDigits .
When the input is received, the callback function will be called with one string argument that is equal to call.vars[variableName].
If addInputHandler is called multiple times for the same variable name, only the last handler function will be called.
ArgumentsvariableName | string, required Variable name on the call
| callback | function, required Callback function with one string argument that will be called with the input value (same as call.vars[variableName])
|
Return Typeundefined | ExampleaddInputHandler("menu_option", function(input) {
sayText('You pressed ' + input);
});
|
Context: USSD session addEventListener(eventName, callback)
Defines a callback function to handle a named event.
Should be called every time the script runs (i.e., not inside the main() function).
Currently only the call_complete event is defined for USSD sessions.
Within an event listener callback function, any calls to sayText or promptDigits will be ignored.
ArgumentseventName | string, required Possible Values: call_complete | callback | function, required Callback function with no arguments
|
Return Typeundefined | ExampleaddEventListener("call_complete", function() {
console.log('Duration = ' + call.duration + ' sec');
});
|
Context: USSD session hangUp()
Ends the current USSD session.
ArgumentsNone Return Typeundefined | ExamplehangUp();
|
Context: USSD session sendMessageToContact(content, options)
Sends a text message to the current contact using the project's default route (not a USSD reply).
For more advanced options, see project.sendMessage.
Argumentscontent | string, required Content of the text message
| options | object, optional |
OptionsreplaceVariables | bool, optional If true, Rules Engine variables in double square brackets like [[contact.name]] in the message content will be replaced with their current values.
Default: false | trackClicks | string, optional If true, URLs in the message content will be replaced with trackable short links.
Default: false |
Return Typeundefined | ExamplesendMessageToContact("Thanks for your message!");
|
Global
Global Variables:global |
The JavaScript global object itself
|
| |
httpClient.request(url, options)
Fetches a external URL over HTTP or HTTPS, such as an API or a web page.
Argumentsurl | string, required The URL to request. Must use http:// or https:// protocol; custom port numbers are not allowed.
| options | object, optional |
Optionsmethod | string, optional Possible Values: GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE Default: GET | params | object, optional An object to convert into query string parameters and append to the end of the URL (e.g. if params is {a:1,b:'hello world'}, Telerivet would append ?a=1&b=hello+world to the end of the URL)
| data | string or object, optional The content of a HTTP POST, PUT, or PATCH request. If this is an object, Telerivet will serialize the key/value pairs as URL-encoded params (e.g. {a:1,b:'hello world'} would be encoded as a=1&b=hello+world). If you want to send data as JSON instead, pass the result of calling JSON.stringify.
| headers | object, optional Key/value pairs for custom HTTP headers to send with the request
| basicAuth | string, optional A string in the format "username:password" to use for HTTP Basic authentication
| timeout | int, optional Timeout for the HTTP request in milliseconds. If the requested timeout is less than 1 ms or longer than the overall timeout for the service, the overall timeout for the service will be used instead.
|
Return Typeobject Return Value Propertiesstatus |
int
The HTTP response status code (e.g. 200, 404, etc.)
| content |
string
The content of the HTTP response
| headers |
object
A key/value map of the HTTP response headers
|
| Examplevar response = httpClient.request("http://api.example.com/rest", {
method: "POST",
params: {'foo': 2, 'bar': "hi"},
data: {'a': 1, 'b': "hello world"},
headers: {'X-Example': "example"},
basicAuth: "my_username:my_password"
});
|
require(path)
Includes and executes an external JavaScript module (see example).
This allows you to define scripts in your own source control system if desired, to reuse code across multiple services, and to build scripts larger than the 100 KB limit of Telerivet's web-based script editor.
External JS files may define JavaScript code that executes directly, or may export behavior via the CommonJS module format, i.e. by setting properties on the 'exports' variable.
Although this behaves similarly to the node.js require() function, Telerivet's script
engine is not node.js, and including node.js modules probably will not work.
Contact us for more information on connecting your source control system with Telerivet.
Argumentspath | string, required The path to the Javascript module. For the "top-level" call to require(), the path must be an path starting with 'ext/'
Modules may include additional modules using paths relative to the intial module URL, e.g. require('./foo')
All module paths must end with the '.js' extension. The path may optionally omit the trailing '.js'.
|
Return Type'exports' object from included script | Examplevar weather = require("ext/example/weather");
sendReply(weather.getWeatherForZIPCode('94111'));
|
console.log(str)
Displays a custom string to the simulator window (and saves it in the logs for your service), in order to help with debugging.
ArgumentsReturn Typeundefined | Exampleconsole.log("Kilroy was here");
|
console.trace()
Displays a stack trace to the simulator window (and saves it in the logs for your service), in order to help with debugging.
ArgumentsNone Return Typeundefined | Exampleconsole.trace();
|
APICursor
An easy-to-use interface for interacting with API methods that return collections of objects that may be split into multiple pages of results.
Using the APICursor, you can easily iterate over query results without having to manually fetch each page of results.
| |
cursor.count()
Returns the total count of entities matching the current query, without actually fetching the entities themselves.
This is much more efficient than all() if you only need the count, as it only results in one API call, regardless of the number of entities matched by the query.
ArgumentsNone Return Typeint | Examplevar count = cursor.count();
|
cursor.hasNext()
Returns true if there are any more entities in the result set, false otherwise
ArgumentsNone Return Typebool | Examplecursor.hasNext();
|
cursor.next()
Returns the next entity in the result set.
ArgumentsNone Return TypeEntity | Examplevar entity = cursor.next();
|
cursor.limit(limit)
Limits the maximum number of entities fetched by this query.
By default, iterating over the cursor will automatically fetch additional result pages as necessary. To prevent fetching more objects than you need, call this method to set the maximum number of objects retrieved from the API.
Argumentslimit | int, required The maximum number of entities to fetch from the server (may require multiple API calls if greater than 200)
|
Return Typethe current APICursor object | Examplecursor.limit(15);
|
cursor.all()
Get all entities matching the current query in an array.
Warning: This may result in an unbounded number of API calls! If the result set may be large (e.g., contacts or messages), consider using hasNext() / next() instead.
ArgumentsNone Return Typearray | Examplevar entities = cursor.all();
|
DOMParser
| |
var parser = new DOMParser()
ArgumentsNone Return TypeDOMParser | Examplevar parser = new DOMParser();
|
parser.parseFromString(xmlSource, supportedType)
ArgumentsxmlSource | string, required String containing XML source
| supportedType | string, required Possible Values: text/html, text/xml, application/xml |
Return TypeDOMDocument | Examplevar doc = parser.parseFromString("<foo bar='1'>baz</foo>", "text/xml");
|
XMLSerializer
| |
var serializer = new XMLSerializer()
ArgumentsNone Return TypeXMLSerializer | Examplevar serializer = new XMLSerializer();
|
serializer.serializeToString(domDocument)
ArgumentsdomDocument | DOMDocument, required DOM document to serialize
|
Return Typestring | Examplevar str = serializer.serializeToString(doc);
|
HTTPRequest
For scripts that directly handle incoming HTTP requests, the request variable has the properties listed below.
Note: Webhook requests will not be processed if the query string is longer than 4096 bytes, if the request body is more than 100000 bytes,
or if the request body or query string is not a valid UTF-8 string.
Properties:method |
string HTTP method (e.g. GET, POST, PUT, HEAD)
| GET |
object Object containing query string parameters as key/value pairs, after decoding URL-encoded characters. This will be provided even if the request method is not GET.
Any parameter names or values that are not valid UTF-8 strings will not be present in the GET property.
Note: If the query string contains parameter names followed by numbers in square brackets like
arr[0] or arr[1] or if it contains parameter names followed by empty square brackets like arr[] ,
this object will have a single property (e.g. arr ) whose value is an array. If the request contains
parameter names with non-numeric values in square brackets like obj[bar] or obj[baz] , this object
will have a single property (e.g. obj ) whose value is an object containing key/value pairs. This decoding
is performed recursively if the parameter names contain multiple sets of square brackets.
| POST |
object Object containing parameters in the request body as key/value pairs, after decoding URL-encoded characters, if they could be parsed as URL-encoded form parameters. This will be provided even if the request method is not POST.
Parameters with names containing square brackets are decoded in the same way as the GET property.
Any parameter names or values that are not valid UTF-8 strings will not be present in the POST property.
If the POST body does not contain URL-encoded form parameters, use the content property instead and decode the parameters yourself, e.g. using JSON.parse(request.content) .
| content |
string Raw content of the request body
| query |
string Raw query string (after the first ? in the URL)
| headers |
object Object containing HTTP headers as key/value pairs. Keys are normalized into title case, e.g. Content-Type.
Note: If the request contains multiple headers with the same name, only one of the headers will be available.
| remote_addr |
string IP address of client that made the HTTP request
|
| |
JSON
Utility functions for parsing/serializing JSON
| |
JSON.stringify(obj)
Argumentsobj | string, required Object to serialize as JSON
|
Return Typestring | Examplevar str = JSON.stringify({'hello': 42});
|
JSON.parse(str)
Argumentsstr | string, required JSON-encoded string to parse
|
Return Typestring | Examplevar obj = JSON.parse("{\"hello\":42}");
|
PhoneNumber
Utility functions for phone numbers.
| |
PhoneNumber.formatE164(phoneNumber, defaultIsoCountryCode)
Converts a phone number to E.164 format (for example, +14155550123).
On success, returns the converted phone number. If Telerivet does not understand the given phone number, returns null .
ArgumentsphoneNumber | string, required The phone number, in an arbitrary format
| defaultIsoCountryCode | string, required The two-letter country code (ISO 3166-1 alpha-2) to use when interpreting phone numbers without a country code. Note this code is not the international dialing prefix for the country.
|
Return Typestring | ExamplePhoneNumber.formatE164("415-555-0123", "US");
|
PhoneNumber.formatInternational(phoneNumber, defaultIsoCountryCode)
Converts a phone number to international format (for example, +1 415-555-0123).
On success, returns the converted phone number. If Telerivet does not understand the given phone number, returns null .
ArgumentsphoneNumber | string, required The phone number, in an arbitrary format
| defaultIsoCountryCode | string, required The two-letter country code (ISO 3166-1 alpha-2) to use when interpreting phone numbers without a country code. Note this code is not the international dialing prefix for the country.
|
Return Typestring | ExamplePhoneNumber.formatInternational("415-555-0123", "US");
|
PhoneNumber.formatInternationalRaw(phoneNumber, defaultIsoCountryCode)
Converts a phone number to international format without punctuation (for example, 14155550123).
On success, returns the converted phone number. If Telerivet does not understand the given phone number, returns null .
ArgumentsphoneNumber | string, required The phone number, in an arbitrary format
| defaultIsoCountryCode | string, required The two-letter country code (ISO 3166-1 alpha-2) to use when interpreting phone numbers without a country code. Note this code is not the international dialing prefix for the country.
|
Return Typestring | ExamplePhoneNumber.formatInternationalRaw("415-555-0123", "US");
|
PhoneNumber.formatNational(phoneNumber, defaultIsoCountryCode)
Converts a phone number to national format (for example, (415) 555-0123).
On success, returns the converted phone number. If Telerivet does not understand the given phone number, returns null .
ArgumentsphoneNumber | string, required The phone number, in an arbitrary format
| defaultIsoCountryCode | string, required The two-letter country code (ISO 3166-1 alpha-2) to use when interpreting phone numbers without a country code. Note this code is not the international dialing prefix for the country.
|
Return Typestring | ExamplePhoneNumber.formatNational("415-555-0123", "US");
|
PhoneNumber.formatNationalRaw(phoneNumber, defaultIsoCountryCode)
Converts a phone number to national format without punctuation (for example, 4155550123).
On success, returns the converted phone number. If Telerivet does not understand the given phone number, returns null .
ArgumentsphoneNumber | string, required The phone number, in an arbitrary format
| defaultIsoCountryCode | string, required The two-letter country code (ISO 3166-1 alpha-2) to use when interpreting phone numbers without a country code. Note this code is not the international dialing prefix for the country.
|
Return Typestring | ExamplePhoneNumber.formatNationalRaw("415-555-0123", "US");
|
Base64
Utility functions for encoding/decoding from Base64
| |
Base64.encode(str)
Encodes a string in Base64 (using the UTF-8 representation).
Argumentsstr | string, required String to encode in Base64
|
Return Typestring | Examplevar base64str = Base64.encode("hello world");
|
Base64.decode(base64str)
Decodes a Base64-encoded string (using the UTF-8 representation).
Argumentsbase64str | string, required Base64-encoded string to encode
|
Return Typestring | Examplevar str = Base64.decode("aGVsbG8gd29ybGQ=");
|
_ (Underscore)
Telerivet's script engine provides the Underscore library, which provides many JavaScript helper functions. The current version of Telerivet's Underscore library is 1.6.0. For more documentation on Underscore, see http://underscorejs.org/.
| |
moment
Telerivet's script engine provides the Moment.js library to make it easy to manipulate and format dates in your scripts. The current version of Telerivet's Moment.js library is 2.7.0. Moment Timezone version 0.5.5-2016f is also provided. For more documentation on Moment.js, see http://momentjs.com/.
| |
CryptoJS
Telerivet's script engine provides the CryptoJS library to make it easy to use many cryptographic hash functions and ciphers in your scripts. Algorithms provided by CryptoJS include MD5, SHA-1, SHA-256, SHA-512, SHA-3, HMAC, PBKDF2, AES, 3DES, RC4, and more. The current version of Telerivet's CryptoJS library is 3.1.2. For more documentation on CryptoJS, see https://code.google.com/p/crypto-js/.
| |
Storing Custom Data
All Telerivet objects allow you to store and retrieve arbitrary data – also known as custom variables – in the 'vars' property.
For example:
- You can use custom variables for contacts to store custom contact information, such as email addresses, alternate phone numbers, or unique IDs from another CRM system.
- Telerivet uses custom variables for data rows to store responses and compute statistics for each of your poll questions.
- You can use custom variables for contact/service state to track temporary information for each contact in the context of an automated conversation.
You can also store custom variables with messages, phones, projects, and more.
Each object can store up to 100 custom variables.
Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length.
Arrays and objects are not supported. Setting a variable to null will delete the variable.
For certain object types (currently contacts and data rows), Telerivet also supports querying objects by their custom variables.
Other types of objects cannot be queried by custom variables.
If you need to store custom data that isn't directly associated with any built-in object, Telerivet lets you define custom data tables, so you can store your data in data rows.
|
Example
contact.name = "John Smith";
contact.phone_number = "+16505550123";
contact.send_blocked = false;
contact.conversation_status = "active";
contact.vars.email = "jsmith@example.com";
contact.vars.birthdate = "1953-01-05";
contact.save();
|
Filtering Queries
Several API methods allow you to specify filter conditions to retrieve objects matching certain criteria.
For example, the API method to query contacts accepts several parameters, including name , last_message_time , and vars .
By default, each filter parameter will only match objects containing the exact value specified (case-insensitive); e.g.
{name: "John"}
would match contacts whose name is "John", or "john", but not "John Smith".
Many parameters accept "modifiers" to parameter names, which lets you specify more complex filter conditions. For example, the prefix modifier will match objects where the property starts with a particular string. Modifiers are specfied by adding [modifier_name] to the end of the query parameter; e.g.
{'name[prefix]': "John"}
.
You can also express query modifiers by setting the parameter to an object with the modifier name as a property. For example, the filter condition {name: {prefix: "John"}} is exactly the same as {'name[prefix]': "John"} .
When multiple filter parameters are provided, only objects matching all filters will be returned (OR queries are not currently supported).
Note that not all modifiers may be valid for every parameter; the allowed modifiers for each parameter are documented in the reference below.
Available Modifiers
prefix | Filter objects where the field starts with the parameter value (case-insensitive). Only applicable for string fields. |
not_prefix | Filter objects where the field does not start with the parameter value (case-insensitive). Only applicable for string fields. |
exists | If the parameter value is 1 or true, filter objects where the field has any (non-null) value.
If the parameter value is 0 or false, filter objects where the field does not have any value. |
null | If the parameter value is 1 or true, filter objects where the field does not have any value.
If the parameter value is 0 or false, filter objects where the field has any (non-null) value. |
gte | Filter objects where the value is greater than or equal to the parameter value. For string fields and custom variables the comparison is alphabetical; for numeric fields the comparison is numeric. |
gt | Filter objects where the field value is greater than the parameter value. For string fields and custom variables the comparison is alphabetical; for numeric fields the comparison is numeric. |
lt | Filter objects where the value is less than the parameter value. For string fields and custom variables the comparison is alphabetical; for numeric fields the comparison is numeric. |
lte | Filter objects where the value is less than or equal to the parameter value. For string fields and custom variables the comparison is alphabetical; for numeric fields the comparison is numeric. |
min | Filter objects where the value is greater than or equal to the parameter value (inclusive), always performing a numeric comparison. Not applicable for string fields. |
max | Filter objects where the value is less than the parameter value (non-inclusive), always performing a numeric comparison. Not applicable for string fields. |
ne | Filter objects where the field does not match the parameter value exactly (case-insensitive). |
eq | Filter objects where the field matches the parameter value exactly (case-insensitive). This is the same as not using any modifier. |
|
Example
cursor = project.queryContacts({
name: {'prefix': "John"},
last_message_time: {'min': 1734645745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var contact = cursor.next();
// do something with contact
}
|
Messages | |
Object Type: Message
Represents a single message.
Attributesid |
string, max 34 characters | read-only |
direction |
string Direction of the message: incoming messages are sent from one of your contacts to your phone; outgoing messages are sent from your phone to one of your contacts
Possible Values: incoming, outgoing | read-only |
status |
string Current status of the message
Possible Values: ignored, processing, received, sent, queued, failed, failed_queued, cancelled, delivered, not_delivered, read | read-only |
message_type |
string Possible Values: sms, mms, ussd, ussd_session, call, chat, service | read-only |
source |
string How the message originated within Telerivet
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | read-only |
time_created |
UNIX timestamp The time that the message was created on Telerivet's servers
| read-only |
time_sent |
UNIX timestamp The time that the message was reported to have been sent (null for incoming messages and messages that have not yet been sent)
| read-only |
time_updated |
UNIX timestamp The time that the message was last updated in Telerivet.
| read-only |
from_number |
string The phone number that the message originated from (your number for outgoing messages, the contact's number for incoming messages)
| read-only |
to_number |
string The phone number that the message was sent to (your number for incoming messages, the contact's number for outgoing messages)
| read-only |
content |
string The text content of the message (null for USSD messages and calls)
| read-only |
starred |
bool Whether this message is starred in Telerivet
| updatable |
simulated |
bool Whether this message was simulated within Telerivet for testing (and not actually sent to or received by a real phone)
| read-only |
label_ids |
array of string IDs of LabelList of IDs of labels applied to this message
| read-only |
route_params |
object Route-specific parameters for the message. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value is an object with route-specific parameters to use when the message is sent by that type of route.
| read-only |
vars |
object Custom variables stored for this message. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
priority |
int Priority of this message. Telerivet will attempt to send messages with higher priority numbers first. Only defined for outgoing messages.
| read-only |
error_message |
string A description of the error encountered while sending a message. (This field is omitted from the API response if there is no error message.)
| updatable |
error_code |
string A route-specific error code encountered while sending a message. The error code values depend on the provider and may be described in the provider's API documentation. Error codes may be strings or numbers, depending on the provider. (This field is omitted from the API response if there is no error code.)
| read-only |
external_id |
string The ID of this message from an external SMS gateway provider (e.g. Twilio or Vonage), if available.
| read-only |
num_parts |
number The number of SMS parts associated with the message, if applicable and if known.
| read-only |
price |
number The price of this message, if known.
| read-only |
price_currency |
string The currency of the message price, if applicable.
| read-only |
duration |
number The duration of the call in seconds, if known, or -1 if the call was not answered.
| read-only |
ring_time |
number The length of time the call rang in seconds before being answered or hung up, if known.
| read-only |
audio_url |
string For voice calls, the URL of an MP3 file to play when the contact answers the call
| read-only |
tts_lang |
string For voice calls, the language of the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | read-only |
tts_voice |
string For voice calls, the text-to-speech voice
Possible Values: female, male | read-only |
track_clicks |
boolean If true, URLs in the message content are short URLs that redirect to a destination URL.
| read-only |
short_urls |
array For text messages containing short URLs, this is an array of objects with the properties short_url , link_type , time_clicked (the first time that URL was clicked), and expiration_time . If link_type is "redirect", the object also contains a destination_url property. If link_type is "media", the object also contains an media_index property (the index in the media array). If link_type is "service", the object also contains a service_id property. This property is undefined for messages that do not contain short URLs.
| read-only |
network_code |
string A string identifying the network that sent or received the message, if known. For mobile networks, this string contains the 3-digit mobile country code (MCC) followed by the 2- or 3-digit mobile network code (MNC), which results in a 5- or 6-digit number. For lists of mobile network operators and their corresponding MCC/MNC values, see Mobile country code Wikipedia article. The network_code property may be non-numeric for messages not sent via mobile networks.
| read-only |
media |
array For text messages containing media files, this is an array of objects with the properties url , type (MIME type), filename , and size (file size in bytes). Unknown properties are null. This property is undefined for messages that do not contain media files. Note: For files uploaded via the Telerivet web app, the URL is temporary and may not be valid for more than 1 day.
| read-only |
mms_parts |
array A list of parts in the MMS message (only for incoming MMS messages received via Telerivet Gateway Android app).
Each MMS part in the list is an object with the following properties:
- cid: MMS content-id
- type: MIME type
- filename: original filename
- size (int): number of bytes
- url: URL where the content for this part is stored (secret but publicly accessible, so you could link/embed it in a web page without having to re-host it yourself)
In general, the media property of the message is recommended for retrieving information about MMS media files, instead of mms_parts .
The mms_parts property is also only present when retrieving an individual MMS message by ID, not when querying a list of messages.
| read-only |
time_clicked |
UNIX timestamp If the message contains any short URLs, this is the first time that a short URL in the message was clicked. This property is undefined for messages that do not contain short URLs.
| read-only |
service_id |
ID of the service that handled the message (for voice calls, the service defines the call flow)
| read-only |
phone_id |
ID of the phone (basic route) that sent or received the message
| read-only |
contact_id |
ID of the contact that sent or received the message
| read-only |
route_id |
ID of the custom route that sent the message (if applicable)
| read-only |
broadcast_id |
ID of the broadcast that this message is part of (if applicable)
| read-only |
scheduled_id |
ID of the scheduled message that created this message is part of (if applicable)
| read-only |
user_id |
string, max 34 characters ID of the Telerivet user who sent the message (if applicable)
| read-only |
project_id |
ID of the project this contact belongs to
| read-only |
url |
string URL to this message in the Telerivet web app
| read-only |
|
Example[object Message] JSON: {
"id": "SM1629708e59c5c781",
"direction": "outgoing",
"status": "sent",
"message_type": "sms",
"source": "service",
"time_created": 1390347812,
"time_sent": 1390347814,
"time_updated": 1390347818,
"from_number": "+16505550001",
"to_number": "+16505550123",
"content": "Thank you for registering!",
"starred": true,
"simulated": false,
"label_ids": [
"LB4f3dac27154653e0"
],
"route_params": null,
"vars": {
"foo": "bar",
"baz": 42
},
"priority": 1,
"external_id": "142092393",
"num_parts": 1,
"price": 0.01,
"price_currency": "USD",
"duration": null,
"ring_time": null,
"audio_url": null,
"tts_lang": null,
"tts_voice": null,
"track_clicks": null,
"short_urls": null,
"network_code": null,
"media": null,
"mms_parts": null,
"time_clicked": null,
"service_id": "SV3d246818d0e3d1fb",
"phone_id": "PN4d246818d0ecd1fa",
"contact_id": "CTa1299c3d0e371023",
"route_id": "RT2a586298d3412adf",
"broadcast_id": "MB98918598dab29800",
"scheduled_id": "SEa502e6f9d23f1cb6",
"user_id": "URba3e403e98f49735",
"project_id": "PJ2ad0100821a98bea",
"url": "https://telerivet.com/p/asdf/message/SM1629708e59c5c781"
} |
Object Type: Broadcast
Represents a collection of related outgoing messages.
Typically, messages in a broadcast have the same content template and were sent at the same time; however, a broadcast can also contain messages with unrelated content and messages that were sent at different times.
A broadcast is automatically created when sending a message to a group of contacts.
Attributesid |
string, max 34 characters | read-only |
recipients |
array of objects List of recipients. Each recipient is an object with a string type property, which may be "phone_number" , "group" , or "filter" .
If the type is "phone_number" , the phone_number property will be set to the recipient's phone number.
If the type is "group" , the group_id property will be set to the ID of the group, and the group_name property will be set to the name of the group.
If the type is "filter" , the filter_type property (string) and filter_params property (object) describe the filter used to send the broadcast. (API clients should not rely on a particular value or format of the filter_type or filter_params properties, as they may change without notice.)
| read-only |
title |
string Title of the broadcast. If a title was not provided when the broadcast was sent, it is automatically set to a human readable description of the first few recipients (possibly truncated)
| read-only |
time_created |
UNIX timestamp Time the broadcast was sent in Telerivet
| read-only |
last_message_time |
UNIX timestamp Time the most recent message was queued to send in this broadcast
| read-only |
last_send_time |
UNIX timestamp Time the most recent message was sent (or failed to send) in this broadcast, or null if no messages have been sent yet
| read-only |
status_counts |
object An object whose keys are the possible status codes ("queued" , "sent" , "failed" , "failed_queued" , "delivered" , "not_delivered" , and "cancelled" ), and whose values are the number of messages in the broadcast currently in that status.
| read-only |
message_count |
int The total number of messages created for this broadcast. For large broadcasts, the messages may not be created immediately after the broadcast is sent. The message_count includes messages in any status, including messages that are still queued.
| read-only |
estimated_count |
int The estimated number of messages in this broadcast when it is complete. The estimated_count is calculated at the time the broadcast is sent. When the broadcast is completed, the estimated_count may differ from message_count if there are any blocked contacts among the recipients (blocked contacts are included in estimated_count but not in message_count ), if any contacts don't have phone numbers, or if the group membership changed while the broadcast was being sent.
| read-only |
message_type |
string Type of message sent from this broadcast
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | read-only |
content |
string The text content of the message (null for USSD messages and calls)
| read-only |
audio_url |
string For voice calls, the URL of an MP3 file to play when the contact answers the call
| read-only |
tts_lang |
string For voice calls, the language of the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | read-only |
tts_voice |
string For voice calls, the text-to-speech voice
Possible Values: female, male | read-only |
replace_variables |
bool Set to true if Telerivet will render variables like [[contact.name]] in the message content, false otherwise
| read-only |
status |
string The current status of the broadcast.
Possible Values: queuing, sending, complete, cancelled | read-only |
source |
string How the message originated within Telerivet
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | read-only |
simulated |
bool Whether this message was simulated within Telerivet for testing (and not actually sent to or received by a real phone)
| read-only |
track_clicks |
boolean If true, URLs in the message content will automatically be replaced with unique short URLs.
| read-only |
clicked_count |
int The number of messages in this broadcast containing short links that were clicked. At most one click per message is counted. If track_clicks is false, this property will be null.
| read-only |
label_ids |
array of string IDs of LabelList of IDs of labels applied to all messages in the broadcast
| read-only |
media |
array For text messages containing media files, this is an array of objects with the properties url , type (MIME type), filename , and size (file size in bytes). Unknown properties are null. This property is undefined for messages that do not contain media files. Note: For files uploaded via the Telerivet web app, the URL is temporary and may not be valid for more than 1 day.
| read-only |
vars |
object Custom variables stored for this broadcast. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| read-only |
route_params |
object Route-specific parameters for the messages in the broadcast. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send messages in this broadcast. The corresponding value is an object with route-specific parameters to use when sending messages with that type of route.
| read-only |
price |
number The total price of all messages in this broadcast, if known.
| read-only |
price_currency |
string The currency of the message price, if applicable.
| read-only |
reply_count |
int The number of replies received in response to a message sent in this broadcast. (Replies are not included in message_count ,status_counts , or price .)
| read-only |
last_reply_time |
UNIX timestamp Time the most recent reply was received in response to a message sent in this broadcast, or null if no replies have been sent yet
| read-only |
route_id |
string, max 34 characters ID of the phone or route used to send the broadcast (if applicable)
| read-only |
service_id |
The service associated with this broadcast (for voice calls, the service defines the call flow)
| read-only |
user_id |
string, max 34 characters ID of the Telerivet user who sent the broadcast (if applicable)
| read-only |
project_id |
ID of the project this broadcast belongs to
| read-only |
|
Example[object Broadcast] JSON: {
"id": "MB2489812e59c5c781",
"recipients": [
{
"type": "phone_number",
"phone_number": "+16505550123"
},
{
"type": "group",
"group_id": "CG02139128391fa",
"group_name": "Subscribers"
},
{
"type": "filter",
"filter_type": "contacts_page",
"filter_params": {
"not_group": "CGc2e2dc93f4061f06",
"vars.country": {
"not_exists": "1"
}
}
}
],
"title": "+16505550123, Subscribers, Contact Filter",
"time_created": 1390348075,
"last_message_time": 1390348085,
"last_send_time": 1390348086,
"status_counts": {
"queued": 4124,
"sent": 1242,
"failed": 259,
"failed_queued": 0,
"delivered": 2492,
"not_delivered": 241,
"cancelled": 0
},
"message_count": 8358,
"estimated_count": 12942,
"message_type": "sms",
"content": "Hello [[contact.name]]!",
"audio_url": null,
"tts_lang": null,
"tts_voice": null,
"replace_variables": true,
"status": "queuing",
"source": "service",
"simulated": false,
"track_clicks": null,
"clicked_count": 12,
"label_ids": [
"LB4f3dac27154653e0"
],
"media": null,
"vars": {
"foo": "bar",
"baz": 42
},
"route_params": null,
"price": 13.34,
"price_currency": "USD",
"reply_count": 43,
"last_reply_time": 1390348132,
"route_id": "RT2a586298d3412adf",
"service_id": "SV3d246818d0e3d1fb",
"user_id": "URba3e403e98f49735",
"project_id": "PJ2ad0100821a98bea"
} |
project.sendMessage(options)
Sends one message (SMS, MMS, chat app message, voice call, or USSD request).
ArgumentsOptionsmessage_type | string, optional Type of message to send. If text , will use the default text message type for the selected route.
Possible Values: text, sms, mms, ussd, call, chat, service Default: text | content | string, required if sending SMS message Content of the message to send (if message_type is call , the text will be spoken during a text-to-speech call)
| to_number | string, required if contact_id not set Phone number to send the message to
| contact_id | string ID of Contact, required if to_number not set ID of the contact to send the message to
| route_id | string, optional ID of the phone or route to send the message from
Default: default sender route ID for your project | status_url | string, optional Webhook callback URL to be notified when message status changes
| status_secret | string, optional POST parameter 'secret' passed to status_url
| replace_variables | bool, optional Set to true to evaluate variables like [[contact.name]] in message content. (See available variables) (is_template parameter also accepted)
Default: false | track_clicks | boolean, optional If true, URLs in the message content will automatically be replaced with unique short URLs.
Default: false | short_link_params | object, optional If track_clicks is true, short_link_params may be used to specify custom parameters for each short link in the message. The following parameters are supported:
domain (string): A custom short domain name to use for the short links. The domain name must already be registered for your project or organization.
expiration_sec (integer): The number of seconds after the message is created (queued to send) when the short links will stop forwarding to the destination URL.
If null, the short links will not expire.
| media_urls | array, optional URLs of media files to attach to the text message. If message_type is sms , short links to each URL will be appended to the end of the content (separated by a new line).
By default, each file must have a https:// or http:// URL, which requires the file to be uploaded somewhere that is accessible via the internet. For media files that are not already accessible via the internet, the media_urls parameter also supports data URIs with the file data encoded via Base64 (e.g. "data:image/png;base64,..."), with a maximum file size of 2 MB. To send media via data URIs, contact Telerivet to request enabling the data URIs feature for your project.
| route_params | object, optional Route-specific parameters for the message. The parameters object should have one or more keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value should be an object with route-specific parameters to use if the message is sent by that type of route.
| label_ids | array of string IDs of Label, optional List of IDs of labels to add to this message
| vars | object, optional Custom variables to store with the message
| priority | int, optional Priority of the message. Telerivet will attempt to send messages with higher priority numbers first (for example, so you can prioritize an auto-reply ahead of a bulk message to a large group).
Possible Values: 1, 2 Default: 1 | simulated | bool, optional Set to true to test the Telerivet API without actually sending a message from the route
Default: false | service_id | Service that defines the call flow of the voice call (when message_type is call )
| audio_url | string, optional The URL of an MP3 file to play when the contact answers the call (when message_type is call ).
If audio_url is provided, the text-to-speech voice is not used to say content , although you can optionally use content to indicate the script for the audio.
For best results, use an MP3 file containing only speech. Music is not recommended because the audio quality will be low when played over a phone line.
| tts_lang | string, optional The language of the text-to-speech voice (when message_type is call )
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE Default: en-US | tts_voice | string, optional The name of the text-to-speech voice (when message_type=call)
Possible Values: female, male Default: female |
Return TypeMessage | Examplevar sent_msg = project.sendMessage({
content: "hello world",
to_number: "+16505550123"
});
|
project.sendBroadcast(options)
Sends a text message (optionally with mail-merge templates) or voice call to a group or a list of up to 500 phone numbers.
With message_type =service , invokes an automated service (such as a poll) for a group or list of phone numbers. Any service that can be triggered for a contact can be invoked via this method, whether or not the service actually sends a message.
ArgumentsOptionsmessage_type | string, optional Type of message to send. If text , will use the default text message type for the selected route.
Possible Values: text, sms, mms, call, chat, service Default: text | content | string, required if sending SMS message Content of the message to send
| group_id | string ID of Group, required if to_numbers not set ID of the group to send the message to
| to_numbers | array of strings, required if group_id not set List of up to 500 phone numbers to send the message to
| route_id | string ID of Phone, optional ID of the phone or route to send the message from
Default: default sender route ID | title | string, optional Title of the broadcast. If a title is not provided, a title will automatically be generated from the recipient group name or phone numbers.
| status_url | string, optional Webhook callback URL to be notified when message status changes
| status_secret | string, optional POST parameter 'secret' passed to status_url
| label_ids | array of string IDs of Label, optional Array of IDs of labels to add to all messages sent (maximum 5). Does not apply when message_type =service , since the labels are determined by the service itself.
| exclude_contact_id | string, optional Optionally excludes one contact from receiving the message (only when group_id is set)
| replace_variables | bool, optional Set to true to evaluate variables like [[contact.name]] in message content (See available variables) (is_template parameter also accepted)
Default: false | track_clicks | boolean, optional If true, URLs in the message content will automatically be replaced with unique short URLs.
Default: false | short_link_params | object, optional If track_clicks is true, short_link_params may be used to specify custom parameters for each short link in the message. The following parameters are supported:
domain (string): A custom short domain name to use for the short links. The domain name must already be registered for your project or organization.
expiration_sec (integer): The number of seconds after the message is created (queued to send) when the short links will stop forwarding to the destination URL.
If null, the short links will not expire.
| media_urls | array, optional URLs of media files to attach to the text message. If message_type is sms , short links to each URL will be appended to the end of the content (separated by a new line).
By default, each file must have a https:// or http:// URL, which requires the file to be uploaded somewhere that is accessible via the internet. For media files that are not already accessible via the internet, the media_urls parameter also supports data URIs with the file data encoded via Base64 (e.g. "data:image/png;base64,..."), with a maximum file size of 2 MB. To send media via data URIs, contact Telerivet to request enabling the data URIs feature for your project.
| vars | object, optional Custom variables to set for each message
| route_params | object, optional Route-specific parameters for the messages in the broadcast. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send messages in this broadcast. The corresponding value is an object with route-specific parameters to use when sending messages with that type of route.
| service_id | string ID of Service, required if message_type is service Service to invoke for each recipient (when message_type is call or service )
| audio_url | string, optional The URL of an MP3 file to play when the contact answers the call (when message_type is call ).
If audio_url is provided, the text-to-speech voice is not used to say content , although you can optionally use content to indicate the script for the audio.
For best results, use an MP3 file containing only speech. Music is not recommended because the audio quality will be low when played over a phone line.
| tts_lang | string, optional The language of the text-to-speech voice (when message_type is call )
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE Default: en-US | tts_voice | string, optional The name of the text-to-speech voice (when message_type=call)
Possible Values: female, male Default: female |
Return TypeBroadcast | Examplevar broadcast = project.sendBroadcast({
content: "hello [[contact.name]]!",
to_numbers: ["+14155550123", "+14255550234", "+16505550345"],
status_url: "https://example.com/sms_status.php",
status_secret: "t0psecr3t",
replace_variables: true
});
|
project.sendMulti(options)
Sends up to 100 different messages in a single API request. This method is significantly faster than sending a separate API request for each message.
ArgumentsOptionsmessages | array, required Array of up to 100 objects with content and to_number properties. Each object may also contain the optional properties status_url , status_secret , vars , and/or priority , which override the parameters of the same name defined below, to allow passing different values for each message.
| message_type | string, optional Type of message to send. If text , will use the default text message type for the selected route.
Possible Values: text, sms, mms, call, chat, service Default: text | route_id | string ID of Phone, optional ID of the phone or route to send the messages from
Default: default sender route ID | broadcast_id | ID of an existing broadcast to associate the messages with
| broadcast_title | string, optional Title of broadcast to create (when broadcast_id is not provided).
When sending more than 100 messages over multiple API requests, you can associate all messages with the same broadcast by providing a broadcast_title parameter in the first
API request, then retrieving the broadcast_id property from the API response, and passing it as the broadcast_id parameter in subsequent API requests.
| status_url | string, optional Webhook callback URL to be notified when message status changes
| status_secret | string, optional POST parameter 'secret' passed to status_url
| label_ids | array of string IDs of Label, optional Array of IDs of labels to add to each message (maximum 5)
| replace_variables | bool, optional Set to true to evaluate variables like [[contact.name]] in message content (See available variables) (is_template parameter also accepted)
Default: false | track_clicks | boolean, optional If true, URLs in the message content will automatically be replaced with unique short URLs.
Default: false | short_link_params | object, optional If track_clicks is true, short_link_params may be used to specify custom parameters for each short link in the message. The following parameters are supported:
domain (string): A custom short domain name to use for the short links. The domain name must already be registered for your project or organization.
expiration_sec (integer): The number of seconds after the message is created (queued to send) when the short links will stop forwarding to the destination URL.
If null, the short links will not expire.
| media_urls | array, optional URLs of media files to attach to the text message. If message_type is sms , short links to each URL will be appended to the end of the content (separated by a new line).
By default, each file must have a https:// or http:// URL, which requires the file to be uploaded somewhere that is accessible via the internet. For media files that are not already accessible via the internet, the media_urls parameter also supports data URIs with the file data encoded via Base64 (e.g. "data:image/png;base64,..."), with a maximum file size of 2 MB. To send media via data URIs, contact Telerivet to request enabling the data URIs feature for your project.
| route_params | object, optional Route-specific parameters to apply to all messages. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send messages. The corresponding value is an object with route-specific parameters to use when sending messages with that type of route.
| vars | object, optional Custom variables to store with the message
| priority | int, optional Priority of the message. Telerivet will attempt to send messages with higher priority numbers first (for example, so you can prioritize an auto-reply ahead of a bulk message to a large group).
Possible Values: 1, 2 Default: 1 | simulated | bool, optional Set to true to test the Telerivet API without actually sending a message from the route
Default: false |
Return Typeobject Return Value Propertiesmessages |
array
List of objects representing each newly created message, with the same length and order as provided in the messages parameter in the API request.
Each object has the id and status properties, and may have the property error_message .
(Other properties of the Message object are omitted in order to reduce the amount of redundant data sent in each API response.)
If the messages parameter in the API request contains items with to_number values that are associated with blocked contacts, the id and status properties corresponding to those items will be null, and no messages will be sent to those numbers.
| broadcast_id |
string
ID of broadcast that these messages are associated with, if broadcast_id or broadcast_title parameter is provided in the API request.
|
| Exampleproject.sendMulti({
messages: [{'content': "example 1", 'to_number': "+16505550123"}, {'content': "example 2", 'to_number': "+16505550124"}],
broadcast_title: "API Broadcast",
status_url: "https://example.com/sms_status.php",
status_secret: "t0psecr3t",
replace_variables: true
});
|
project.queryMessages(options)
Queries messages within the given project.
ArgumentsOptionslabel_id | string ID of Label, optional Filter messages with a label
| direction | string, optional Filter messages by direction
Possible Values: incoming, outgoing | message_type | string, optional Filter messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | source | string, optional Filter messages by source
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | starred | bool, optional Filter messages by starred/unstarred
| status | string, optional Filter messages by status
Possible Values: ignored, processing, received, sent, queued, failed, failed_queued, cancelled, delivered, not_delivered, read | time_created[min] | UNIX timestamp, optional Filter messages created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter messages created before a particular time
| external_id | string, optional Filter messages by ID from an external provider
Allowed Modifiers: external_id[ne], external_id[exists] (?) | contact_id | ID of the contact who sent/received the message
Allowed Modifiers: contact_id[ne], contact_id[exists] (?) | phone_id | string ID of Phone, optional ID of the phone (basic route) that sent/received the message
| broadcast_id | ID of the broadcast containing the message
Allowed Modifiers: broadcast_id[ne], broadcast_id[exists] (?) | scheduled_id | ID of the scheduled message that created this message
Allowed Modifiers: scheduled_id[ne], scheduled_id[exists] (?) | group_id | string ID of Group, optional Filter messages sent or received by contacts in a particular group. The group must be a normal group, not a dynamic group.
| sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Message | Examplecursor = project.queryMessages({
direction: "incoming",
message_type: "sms"
});
cursor.limit(50);
while (cursor.hasNext()) {
var message = cursor.next();
// do something with message
}
|
message.removeLabel(label)
Removes a label from the given message.
ArgumentsReturn Typeundefined | Examplevar label = project.initLabelById(label_id);
message.removeLabel(label);
|
project.receiveMessage(options)
Add an incoming message to Telerivet. Acts the same as if the message was received by a phone. Also triggers any automated services that apply to the message.
ArgumentsOptionscontent | string, required unless `message_type` is `call` Content of the incoming message
| message_type | string, optional Possible Values: sms, call, chat Default: sms | from_number | string, required Phone number that sent the incoming message
| phone_id | string ID of Phone, required ID of the phone (basic route) that received the message
| to_number | string, optional Phone number that the incoming message was sent to
Default: phone number of the phone that received the message | simulated | bool, optional If true, Telerivet will not send automated replies to actual phones
| starred | bool, optional True if this message should be starred
| label_ids | array of string IDs of Label, optional Array of IDs of labels to add to this message (maximum 5)
| vars | object, optional Custom variables to set for this message
|
Return TypeMessage | Examplevar message = project.receiveMessage({
content: "help",
message_type: "sms",
from_number: "+16505550193",
to_number: "+16505551212"
});
|
project.getMessageFields()
Gets a list of all custom fields defined for messages in this project. The return value is an array of objects with the properties 'name', 'variable', 'type', 'order', 'readonly', and 'lookup_key'. (Fields are automatically created any time a Contact's 'vars' property is updated.)
ArgumentsNone Return Typearray | Exampleproject.getMessageFields();
|
project.initBroadcastById(id)
Initializes the Telerivet broadcast with the given ID without making an API request.
ArgumentsReturn TypeBroadcast | Examplevar broadcast = project.initBroadcastById(broadcast_id);
|
project.getBroadcastById(id)
Retrieves the broadcast with the given ID.
ArgumentsReturn TypeBroadcast | Examplevar broadcast = project.getBroadcastById(broadcast_id);
|
project.queryBroadcasts(options)
Queries broadcasts within the given project.
ArgumentsOptionstime_created[min] | UNIX timestamp, optional Filter broadcasts created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter broadcasts created before a particular time
| last_message_time[min] | UNIX timestamp, optional Filter broadcasts with most recent message on or after a particular time
| last_message_time[max] | UNIX timestamp, optional Filter broadcasts with most recent message before a particular time
| sort | string, optional Sort the results based on a field
Possible Values: default, last_message_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Broadcast | Examplecursor = project.queryBroadcasts();
cursor.limit(50);
while (cursor.hasNext()) {
var broadcast = cursor.next();
// do something with broadcast
}
|
project.initMessageById(id)
Initializes the Telerivet message with the given ID without making an API request.
ArgumentsReturn TypeMessage | Examplevar message = project.initMessageById(message_id);
|
project.getMessageById(id)
Retrieves the message with the given ID.
ArgumentsReturn TypeMessage | Examplevar message = project.getMessageById(message_id);
|
message.hasLabel(label)
Returns true if this message has a particular label, false otherwise.
ArgumentsReturn Typebool | Examplevar label = project.initLabelById(label_id);
message.hasLabel(label);
|
message.addLabel(label)
Adds a label to the given message.
ArgumentsReturn Typeundefined | Examplevar label = project.initLabelById(label_id);
message.addLabel(label);
|
broadcast.cancel()
Cancels sending a broadcast that has not yet been completely sent. No additional messages will be queued, and any existing queued messages will be cancelled when they would otherwise have been sent (except for messages already queued on the Telerivet Android app, which will not be automatically cancelled).
ArgumentsNone Return TypeBroadcast | Examplevar broadcast = project.initBroadcastById(broadcast_id);
var broadcast = broadcast.cancel();
|
message.delete()
ArgumentsNone Return Typeundefined | Examplemessage.delete();
|
message.cancel()
Cancels sending a message that has not yet been sent. Returns the updated message object. Only valid for outgoing messages that are currently in the queued, retrying, or cancelled states. For other messages, the API will return an error with the code 'not_cancellable'.
ArgumentsNone Return TypeMessage | Examplevar message = message.cancel();
|
message.resend(options)
Resends a message, for example if the message failed to send or if it was not delivered. If the message was originally in the queued, retrying, failed, or cancelled states, then Telerivet will return the same message object. Otherwise, Telerivet will create and return a new message object.
ArgumentsOptionsroute_id | string, optional ID of the phone or route to send the message from
|
Return TypeMessage | Examplevar message = message.resend({
route_id: "PN4d246818d0ecd1fa"
});
|
message.save()
Saves any fields that have changed for this message.
ArgumentsNone Return Typeundefined | Examplemessage.starred = true;
message.vars.foo = "bar";
message.vars.baz = 42;
message.save();
|
project.setMessageFieldMetadata(variable, options)
Allows customizing how a custom message field is displayed in the Telerivet web app.
The variable path parameter can contain the characters a-z, A-Z, 0-9, and _, and may be up to 32 characters in length.
Argumentsvariable | string, required The variable name of the field to create or update.
| options | object, required |
Optionsname | string, max 64 characters, optional Display name for the field
| type | string, optional Possible Values: text, long_text, secret, phone_number, email, url, audio, date, date_time, number, boolean, checkbox, select, radio, route | order | int, optional Order in which to display the field
| items | array, required if type is `select` Array of up to 100 objects containing value and label string properties to show in the dropdown list when type is select . Each value and label must be between 1 and 256 characters in length.
| hide_values | bool, optional Set to true to avoid showing values of this field on the Messages page
|
Return Typeobject | Exampleproject.setMessageFieldMetadata("intent", {
name: "Intent",
type: "number",
order: 2
});
|
Scheduled Messages | |
Object Type: ScheduledMessage
Represents a scheduled message within Telerivet.
Attributesid |
string, max 34 characters ID of the scheduled message
| read-only |
content |
string Text content of the scheduled message
| updatable |
rrule |
string Recurrence rule for recurring scheduled messages, e.g. 'FREQ=MONTHLY' or 'FREQ=WEEKLY;INTERVAL=2'; see RFC2445.
| updatable |
timezone_id |
string | updatable |
recipients |
array of objects List of recipients. Each recipient is an object with a string type property, which may be "phone_number" , "group" , or "filter" .
If the type is "phone_number" , the phone_number property will be set to the recipient's phone number.
If the type is "group" , the group_id property will be set to the ID of the group, and the group_name property will be set to the name of the group.
If the type is "filter" , the filter_type property (string) and filter_params property (object) describe the filter used to send the broadcast. (API clients should not rely on a particular value or format of the filter_type or filter_params properties, as they may change without notice.)
| read-only |
recipients_str |
string A string with a human readable description of the first few recipients (possibly truncated)
| read-only |
group_id |
ID of the group to send the message to (null if the recipient is an individual contact, or if there are multiple recipients)
| updatable |
contact_id |
ID of the contact to send the message to (null if the recipient is a group, or if there are multiple recipients)
| updatable |
to_number |
string Phone number to send the message to (null if the recipient is a group, or if there are multiple recipients)
| updatable |
route_id |
string ID of the phone or route the message will be sent from
| updatable |
service_id |
The service associated with this message (for voice calls, the service defines the call flow)
| updatable |
audio_url |
string For voice calls, the URL of an MP3 file to play when the contact answers the call
| updatable |
tts_lang |
string For voice calls, the language of the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | updatable |
tts_voice |
string For voice calls, the text-to-speech voice
Possible Values: female, male | updatable |
message_type |
string Type of scheduled message
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | read-only |
time_created |
UNIX timestamp Time the scheduled message was created in Telerivet
| read-only |
start_time |
UNIX timestamp The time that the message will be sent (or first sent for recurring messages)
| updatable |
end_time |
UNIX timestamp Time after which a recurring message will stop (not applicable to non-recurring scheduled messages)
| updatable |
prev_time |
UNIX timestamp The most recent time that Telerivet has sent this scheduled message (null if it has never been sent)
| read-only |
next_time |
UNIX timestamp The next upcoming time that Telerivet will sent this scheduled message (null if it will not be sent again)
| read-only |
occurrences |
int Number of times this scheduled message has already been sent
| read-only |
replace_variables |
bool Set to true if Telerivet will render variables like [[contact.name]] in the message content, false otherwise
| updatable |
track_clicks |
boolean If true, URLs in the message content will automatically be replaced with unique short URLs
| updatable |
media |
array For text messages containing media files, this is an array of objects with the properties url , type (MIME type), filename , and size (file size in bytes). Unknown properties are null. This property is undefined for messages that do not contain media files. Note: For files uploaded via the Telerivet web app, the URL is temporary and may not be valid for more than 1 day.
| read-only |
route_params |
object Route-specific parameters to use when sending the message. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value is an object with route-specific parameters to use when sending a message with that type of route.
| updatable |
vars |
object Custom variables stored for this scheduled message (copied to Message when sent). Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
label_ids |
array of string IDs of LabelIDs of labels to add to the Message
| updatable |
relative_scheduled_id |
string ID of the relative scheduled message this scheduled message was created from, if applicable
| read-only |
project_id |
string ID of the project this scheduled message belongs to
| read-only |
|
Example[object ScheduledMessage] JSON: {
"id": "SEfaf2411ed3584f08",
"content": "hello world!",
"rrule": "COUNT=1",
"timezone_id": "America/Los_Angeles",
"recipients": [
{
"type": "phone_number",
"phone_number": "+16505550123"
},
{
"type": "group",
"group_id": "CG02139128391fa",
"group_name": "Subscribers"
}
],
"recipients_str": "+16505550123, Subscribers",
"group_id": null,
"contact_id": null,
"to_number": null,
"route_id": "PN4d246818d0ecd1fa",
"service_id": "SV3d246818d0e3d1fb",
"audio_url": null,
"tts_lang": null,
"tts_voice": null,
"message_type": "sms",
"time_created": 1395617416,
"start_time": 1395617516,
"end_time": null,
"prev_time": null,
"next_time": 1395617516,
"occurrences": 0,
"replace_variables": false,
"track_clicks": null,
"media": null,
"route_params": null,
"vars": {
"foo": "bar",
"baz": 42
},
"label_ids": [
"LB4f3dac27154653e0"
],
"relative_scheduled_id": "PJ2ad0100821a98bea",
"project_id": "PJ2ad0100821a98bea"
} |
Object Type: RelativeScheduledMessage
A relative scheduled message is a message that is scheduled relative to a date stored as a custom field for each recipient contact.
This allows scheduling messages on a different date for each contact, for example on their birthday, a certain number of days before an appointment, or a certain number of days after enrolling in a campaign.
Telerivet will automatically create a ScheduledMessage for each contact matching a RelativeScheduledMessage.
Any service that can be manually triggered for a contact (including polls) may also be scheduled via a relative scheduled message, whether or not the service actually sends a message.
Attributesid |
string, max 34 characters ID of the relative scheduled message
| read-only |
content |
string Text content of the relative scheduled message
| updatable |
time_of_day |
string Time of day when scheduled messages will be sent in HH:MM format (with hours from 00 to 23)
| updatable |
date_variable |
string Custom contact variable storing date or date/time values relative to which messages will be scheduled.
| updatable |
offset_scale |
string The type of interval (day/week/month/year) that will be used to adjust the scheduled date relative to the date stored in the contact's date_variable, when offset_count is non-zero (D=day, W=week, M=month, Y=year)
Possible Values: D, W, M, Y | updatable |
offset_count |
int The number of days/weeks/months/years to adjust the date of the scheduled message relative relative to the date stored in the contact's date_variable. May be positive, negative, or zero.
| updatable |
rrule |
string Recurrence rule for recurring scheduled messages, e.g. 'FREQ=MONTHLY' or 'FREQ=WEEKLY;INTERVAL=2'; see RFC2445.
| updatable |
end_time |
UNIX timestamp Time after which recurring messages will stop (not applicable to non-recurring scheduled messages)
| updatable |
timezone_id |
string | updatable |
recipients_str |
string A string with a human readable description of the recipient
| read-only |
group_id |
ID of the group to send the message to (null if the recipient is an individual contact)
| updatable |
contact_id |
ID of the contact to send the message to (null if the recipient is a group)
| updatable |
to_number |
string Phone number to send the message to (null if the recipient is a group)
| updatable |
route_id |
string ID of the phone or route the message will be sent from
| updatable |
service_id |
The service associated with this message (for voice calls, the service defines the call flow)
| updatable |
audio_url |
string For voice calls, the URL of an MP3 file to play when the contact answers the call
| updatable |
tts_lang |
string For voice calls, the language of the text-to-speech voice
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE | updatable |
tts_voice |
string For voice calls, the text-to-speech voice
Possible Values: female, male | updatable |
message_type |
string Type of scheduled message
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | read-only |
time_created |
UNIX timestamp Time the relative scheduled message was created in Telerivet
| read-only |
replace_variables |
bool Set to true if Telerivet will render variables like [[contact.name]] in the message content, false otherwise
| updatable |
track_clicks |
boolean If true, URLs in the message content will automatically be replaced with unique short URLs
| updatable |
media |
array For text messages containing media files, this is an array of objects with the properties url , type (MIME type), filename , and size (file size in bytes). Unknown properties are null. This property is undefined for messages that do not contain media files. Note: For files uploaded via the Telerivet web app, the URL is temporary and may not be valid for more than 1 day.
| read-only |
route_params |
object Route-specific parameters to use when sending the message. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value is an object with route-specific parameters to use when sending a message with that type of route.
| updatable |
vars |
object Custom variables stored for this scheduled message (copied to each ScheduledMessage and Message when sent). Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
label_ids |
array of string IDs of LabelIDs of labels to add to the Message
| updatable |
project_id |
string ID of the project this relative scheduled message belongs to
| read-only |
|
Example[object RelativeScheduledMessage] JSON: {
"id": "SEfaf2411ed3584f08",
"content": "hello world!",
"time_of_day": "15:07",
"date_variable": "date",
"offset_scale": "D",
"offset_count": 3,
"rrule": "COUNT=1",
"end_time": null,
"timezone_id": "America/Los_Angeles",
"recipients_str": "Subscribers",
"group_id": null,
"contact_id": null,
"to_number": null,
"route_id": "PN4d246818d0ecd1fa",
"service_id": "SV3d246818d0e3d1fb",
"audio_url": null,
"tts_lang": null,
"tts_voice": null,
"message_type": "sms",
"time_created": 1395617416,
"replace_variables": false,
"track_clicks": null,
"media": null,
"route_params": null,
"vars": {
"foo": "bar",
"baz": 42
},
"label_ids": [
"LB4f3dac27154653e0"
],
"project_id": "PJ2ad0100821a98bea"
} |
project.scheduleMessage(options)
Schedules a message to a group or single contact. Note that Telerivet only sends scheduled messages approximately once every 15 seconds, so it is not possible to control the exact second at which a scheduled message is sent.
Only one of the parameters group_id, to_number, and contact_id should be provided.
With message_type =service , schedules an automated service (such as a poll) to be invoked for a group or list of phone numbers. Any service that can be triggered for a contact can be scheduled via this method, whether or not the service actually sends a message.
ArgumentsOptionsmessage_type | string, optional Possible Values: text, sms, mms, ussd, call, chat, service Default: text | content | string, required if sending text message Content of the message to schedule
| group_id | string ID of Group, optional ID of the group to send the message to
| to_number | string, optional Phone number to send the message to
| contact_id | ID of the contact to send the message to
| start_time | UNIX timestamp, required if start_time_offset not set The time that the message will be sent (or first sent for recurring messages)
| start_time_offset | int, required if start_time not set Number of seconds from now until the message is sent
| rrule | string, optional Default: COUNT=1 (one-time scheduled message, does not repeat) | route_id | string ID of Phone, optional ID of the phone or route to send the message from
Default: default sender route ID | service_id | string ID of Service, required if message_type is service Service to invoke for each recipient (when message_type is call or service )
| audio_url | string, optional The URL of an MP3 file to play when the contact answers the call (when message_type is call ).
If audio_url is provided, the text-to-speech voice is not used to say content , although you can optionally use content to indicate the script for the audio.
For best results, use an MP3 file containing only speech. Music is not recommended because the audio quality will be low when played over a phone line.
| tts_lang | string, optional The language of the text-to-speech voice (when message_type is call )
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE Default: en-US | tts_voice | string, optional The name of the text-to-speech voice (when message_type=call)
Possible Values: female, male Default: female | track_clicks | boolean, optional If true, URLs in the message content will automatically be replaced with unique short URLs.
Default: false | short_link_params | object, optional If track_clicks is true, short_link_params may be used to specify custom parameters for each short link in the message. The following parameters are supported:
domain (string): A custom short domain name to use for the short links. The domain name must already be registered for your project or organization.
expiration_sec (integer): The number of seconds after the message is created (queued to send) when the short links will stop forwarding to the destination URL.
If null, the short links will not expire.
| replace_variables | bool, optional Set to true to evaluate variables like [[contact.name]] in message content (is_template parameter also accepted)
Default: false | media_urls | array, optional URLs of media files to attach to the text message. If message_type is sms , short links to each URL will be appended to the end of the content (separated by a new line).
By default, each file must have a https:// or http:// URL, which requires the file to be uploaded somewhere that is accessible via the internet. For media files that are not already accessible via the internet, the media_urls parameter also supports data URIs with the file data encoded via Base64 (e.g. "data:image/png;base64,..."), with a maximum file size of 2 MB. To send media via data URIs, contact Telerivet to request enabling the data URIs feature for your project.
| route_params | object, optional Route-specific parameters to use when sending the message. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value is an object with route-specific parameters to use when sending a message with that type of route.
| label_ids | array of string IDs of Label, optional Array of IDs of labels to add to the sent messages (maximum 5). Does not apply when message_type =service , since the labels are determined by the service itself.
| timezone_id | string, optional Default: project default timezone | end_time | UNIX timestamp, optional Time after which a recurring message will stop (not applicable to non-recurring scheduled messages)
| end_time_offset | int, optional Number of seconds from now until the recurring message will stop
| vars | object, optional Custom variables to set for this scheduled message, which will be copied to each message sent from this scheduled message
|
Return TypeScheduledMessage | Examplevar scheduled_msg = project.scheduleMessage({
content: "Reminder!",
to_number: "+16505550234",
start_time_offset: 86400
});
|
project.queryScheduledMessages(options)
Queries scheduled messages within the given project.
ArgumentsOptionsmessage_type | string, optional Filter scheduled messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | time_created | UNIX timestamp, optional Filter scheduled messages by time_created
Allowed Modifiers: time_created[min], time_created[max] (?) | next_time | UNIX timestamp, optional Filter scheduled messages by next_time
Allowed Modifiers: next_time[min], next_time[max], next_time[exists] (?) | relative_scheduled_id | Filter scheduled messages created for a relative scheduled message
| sort | string, optional Sort the results based on a field
Possible Values: default, next_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of ScheduledMessage | Examplecursor = project.queryScheduledMessages({
message_type: "sms",
next_time: {'min': 1742421745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var scheduled_msg = cursor.next();
// do something with scheduled_msg
}
|
scheduled_msg.save()
Saves any fields or custom variables that have changed for this scheduled message.
ArgumentsNone Return Typeundefined | Examplevar scheduled_msg = project.initScheduledMessageById(scheduled_msg_id);
scheduled_msg.content = "hello world!";
scheduled_msg.rrule = "COUNT=1";
scheduled_msg.timezone_id = "America/Los_Angeles";
scheduled_msg.route_id = "PN4d246818d0ecd1fa";
scheduled_msg.service_id = "SV3d246818d0e3d1fb";
scheduled_msg.start_time = 1395617516;
scheduled_msg.replace_variables = false;
scheduled_msg.vars.foo = "bar";
scheduled_msg.vars.baz = 42;
scheduled_msg.label_ids = ["LB4f3dac27154653e0"];
scheduled_msg.save();
|
scheduled_msg.delete()
Cancels this scheduled message.
ArgumentsNone Return Typeundefined | Examplevar scheduled_msg = project.initScheduledMessageById(scheduled_msg_id);
scheduled_msg.delete();
|
project.createRelativeScheduledMessage(options)
Creates a relative scheduled message. This allows scheduling messages on a different date for each contact, for example on their birthday, a certain number of days before an appointment, or a certain number of days after enrolling in a campaign.
Telerivet will automatically create a ScheduledMessage for each contact matching a RelativeScheduledMessage.
Relative scheduled messages can be created for a group or an individual contact, although dynamic groups are not supported. Only one of the parameters group_id, to_number, and contact_id should be provided.
With message_type=service, schedules an automated service (such as a poll). Any service that can be triggered for a contact can be scheduled via this method, whether or not the service actually sends a message.
ArgumentsOptionsmessage_type | string, optional Possible Values: text, sms, mms, call, chat, service Default: text | content | string, required if sending text message Content of the message to schedule
| group_id | string ID of Group, optional ID of the group to send the message to. Dynamic groups are not supported.
| to_number | string, optional Phone number to send the message to
| contact_id | ID of the contact to send the message to
| time_of_day | string, required Time of day when scheduled messages will be sent in HH:MM format (with hours from 00 to 23)
| timezone_id | string, optional Default: project default timezone | date_variable | string, required Custom contact variable storing date or date/time values relative to which messages will be scheduled.
| offset_scale | string, optional The type of interval (day/week/month/year) that will be used to adjust the scheduled date relative to the date stored in the contact's date_variable, when offset_count is non-zero (D=day, W=week, M=month, Y=year)
Possible Values: D, W, M, Y Default: D | offset_count | int, optional The number of days/weeks/months/years to adjust the date of the scheduled message relative relative to the date stored in the custom contact variable identified by the date_variable parameter. May be positive, negative, or zero.
Default: 0 | rrule | string, optional Default: COUNT=1 (one-time scheduled message, does not repeat) | route_id | string ID of Phone, optional ID of the phone or route to send the message from
Default: default sender route ID | service_id | string ID of Service, required if message_type is service Service to invoke for each recipient (when message_type is call or service )
| audio_url | string, optional The URL of an MP3 file to play when the contact answers the call (when message_type is call ).
If audio_url is provided, the text-to-speech voice is not used to say content , although you can optionally use content to indicate the script for the audio.
For best results, use an MP3 file containing only speech. Music is not recommended because the audio quality will be low when played over a phone line.
| tts_lang | string, optional The language of the text-to-speech voice (when message_type is call )
Possible Values: en-US, en-GB, en-GB-WLS, en-AU, en-IN, da-DK, nl-NL, fr-FR, fr-CA, de-DE, is-IS, it-IT, pl-PL, pt-BR, pt-PT, ru-RU, es-ES, es-US, sv-SE Default: en-US | tts_voice | string, optional The name of the text-to-speech voice (when message_type=call)
Possible Values: female, male Default: female | track_clicks | boolean, optional If true, URLs in the message content will automatically be replaced with unique short URLs.
Default: false | short_link_params | object, optional If track_clicks is true, short_link_params may be used to specify custom parameters for each short link in the message. The following parameters are supported:
domain (string): A custom short domain name to use for the short links. The domain name must already be registered for your project or organization.
expiration_sec (integer): The number of seconds after the message is created (queued to send) when the short links will stop forwarding to the destination URL.
If null, the short links will not expire.
| replace_variables | bool, optional Set to true to evaluate variables like [[contact.name]] in message content
Default: false | media_urls | array, optional URLs of media files to attach to the text message. If message_type is sms , short links to each URL will be appended to the end of the content (separated by a new line).
By default, each file must have a https:// or http:// URL, which requires the file to be uploaded somewhere that is accessible via the internet. For media files that are not already accessible via the internet, the media_urls parameter also supports data URIs with the file data encoded via Base64 (e.g. "data:image/png;base64,..."), with a maximum file size of 2 MB. To send media via data URIs, contact Telerivet to request enabling the data URIs feature for your project.
| route_params | object, optional Route-specific parameters to use when sending the message. The parameters object may have keys matching the phone_type field of a phone (basic route) that may be used to send the message. The corresponding value is an object with route-specific parameters to use when sending a message with that type of route.
| label_ids | array of string IDs of Label, optional Array of IDs of labels to add to the sent messages (maximum 5). Does not apply when message_type =service , since the labels are determined by the service itself.
| end_time | UNIX timestamp, optional Time after which a recurring message will stop (not applicable to non-recurring scheduled messages)
| end_time_offset | int, optional Number of seconds from now until the recurring message will stop
| vars | object, optional Custom variables to set for this relative scheduled message, which will be copied to each message sent from this scheduled message
|
Return TypeRelativeScheduledMessage | Examplevar rel_scheduled_msg = project.createRelativeScheduledMessage({
content: "Hi [[contact.name]], just following up!",
group_id: "GC123123123123123123",
time_of_day: "15:07",
date_variable: "date",
offset_scale: "D",
offset_count: 3,
rrule: "FREQ=MONTHLY",
replace_variables: true
});
|
project.queryRelativeScheduledMessages(options)
Queries relative scheduled messages within the given project.
ArgumentsOptionsmessage_type | string, optional Filter relative scheduled messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | time_created | UNIX timestamp, optional Filter relative scheduled messages by time_created
Allowed Modifiers: time_created[min], time_created[max] (?) | group_id | string ID of Group, optional Filter relative scheduled messages sent to a group
| contact_id | Filter relative scheduled messages sent to an individual contact
| sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of RelativeScheduledMessage | Examplecursor = project.queryRelativeScheduledMessages({
message_type: "sms"
});
cursor.limit(50);
while (cursor.hasNext()) {
var rel_scheduled_msg = cursor.next();
// do something with rel_scheduled_msg
}
|
rel_scheduled_msg.save()
Saves any fields or custom variables that have changed for this relative scheduled message.
ArgumentsNone Return Typeundefined | Examplevar rel_scheduled_msg = project.initRelativeScheduledMessageById(rel_scheduled_msg_id);
rel_scheduled_msg.content = "hello world!";
rel_scheduled_msg.time_of_day = "15:07";
rel_scheduled_msg.date_variable = "date";
rel_scheduled_msg.offset_scale = "D";
rel_scheduled_msg.offset_count = 3;
rel_scheduled_msg.rrule = "COUNT=1";
rel_scheduled_msg.timezone_id = "America/Los_Angeles";
rel_scheduled_msg.route_id = "PN4d246818d0ecd1fa";
rel_scheduled_msg.service_id = "SV3d246818d0e3d1fb";
rel_scheduled_msg.replace_variables = false;
rel_scheduled_msg.vars.foo = "bar";
rel_scheduled_msg.vars.baz = 42;
rel_scheduled_msg.label_ids = ["LB4f3dac27154653e0"];
rel_scheduled_msg.save();
|
rel_scheduled_msg.delete()
Deletes this relative scheduled message and any associated scheduled messages.
ArgumentsNone Return Typeundefined | Examplevar rel_scheduled_msg = project.initRelativeScheduledMessageById(rel_scheduled_msg_id);
rel_scheduled_msg.delete();
|
project.getScheduledMessageById(id)
Retrieves the scheduled message with the given ID.
Argumentsid | string, required ID of the scheduled message
|
Return TypeScheduledMessage | Examplevar scheduled_msg = project.getScheduledMessageById(scheduled_msg_id);
|
project.initScheduledMessageById(id)
Initializes the scheduled message with the given ID without making an API request.
Argumentsid | string, required ID of the scheduled message
|
Return TypeScheduledMessage | Examplevar scheduled_msg = project.initScheduledMessageById(scheduled_msg_id);
|
project.getRelativeScheduledMessageById(id)
Retrieves the scheduled message with the given ID.
Argumentsid | string, required ID of the relative scheduled message
|
Return TypeRelativeScheduledMessage | Examplevar rel_scheduled_msg = project.getRelativeScheduledMessageById(rel_scheduled_msg_id);
|
project.initRelativeScheduledMessageById(id)
Initializes the relative scheduled message with the given ID without making an API request.
Argumentsid | string, required ID of the relative scheduled message
|
Return TypeRelativeScheduledMessage | Examplevar rel_scheduled_msg = project.initRelativeScheduledMessageById(rel_scheduled_msg_id);
|
Contacts | |
Object Type: Contact
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
phone_number |
string Phone number of the contact
| updatable |
time_created |
UNIX timestamp Time the contact was added in Telerivet
| read-only |
time_updated |
UNIX timestamp Time the contact was last updated in Telerivet
| read-only |
send_blocked |
bool True if Telerivet is blocked from sending messages to this contact
| updatable |
conversation_status |
string Current status of the conversation with this contact
Possible Values: closed, active, handled | updatable |
last_message_time |
UNIX timestamp Last time the contact sent or received a message (null if no messages have been sent or received)
| read-only |
last_incoming_message_time |
UNIX timestamp Last time a message was received from this contact
| read-only |
last_outgoing_message_time |
UNIX timestamp Last time a message was sent to this contact
| read-only |
message_count |
int Total number of non-deleted messages sent to or received from this contact
| read-only |
incoming_message_count |
int Number of messages received from this contact
| read-only |
outgoing_message_count |
int Number of messages sent to this contact
| read-only |
last_message_id |
ID of the last message sent to or received from this contact (null if no messages have been sent or received)
| read-only |
default_route_id |
ID of the basic route (phone) or custom route that Telerivet will use by default to send messages to this contact (null if using project default route)
| updatable |
group_ids |
array of strings List of IDs of groups that this contact belongs to
| read-only |
vars |
object Custom variables stored for this contact. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this contact belongs to
| read-only |
url |
string URL to this contact in the Telerivet web app
| read-only |
|
Example[object Contact] JSON: {
"id": "CTa1299c3d0e371023",
"name": "John Smith",
"phone_number": "+16505550123",
"time_created": 1390348075,
"time_updated": 1390348099,
"send_blocked": false,
"conversation_status": "active",
"last_message_time": 1395881121,
"last_incoming_message_time": 1395881121,
"last_outgoing_message_time": 1395881032,
"message_count": 13,
"incoming_message_count": 2,
"outgoing_message_count": 11,
"last_message_id": "SM97f47ac232df154d",
"default_route_id": null,
"group_ids": [
"CGb0b7201b222fa609",
"CG5f5ff672ebdd6766"
],
"vars": {
"email": "jsmith@example.com",
"birthdate": "1953-01-05"
},
"project_id": "PJ2ad0100821a98bea",
"url": "https://telerivet.com/p/asdf/contact/CTa1299c3d0e371023"
} |
project.getOrCreateContact(options)
Retrieves OR creates and possibly updates a contact by name or phone number.
If a phone number is provided, by default, Telerivet will search for an existing contact with that phone number (including suffix matches to allow finding contacts with phone numbers in a different format). If a phone number is not provided but a name is provided, Telerivet will search for a contact with that exact name (case insensitive). This behavior can be modified by setting the lookup_key parameter to look up a contact by another field, including a custom variable.
If no existing contact is found, a new contact will be created.
Then that contact will be updated with any parameters provided (name , phone_number , vars , default_route_id , send_blocked , add_group_ids , remove_group_ids ).
ArgumentsOptionsname | string, optional | phone_number | string, optional Phone number of the contact
| lookup_key | string, optional The field used to search for a matching contact, or 'none' to always create a new contact. To search by a custom variable, precede the variable name with 'vars.'.
Possible Values: phone_number, name, id, vars.variable_name, none Default: phone_number | send_blocked | bool, optional True if Telerivet is blocked from sending messages to this contact
| default_route_id | string ID of Route, optional ID of the route to use by default to send messages to this contact
| add_group_ids | array of string IDs of Group, optional ID of one or more groups to add this contact as a member (max 20)
| id | ID of an existing contact (only used if lookup_key is 'id')
| remove_group_ids | array of string IDs of Group, optional ID of one or more groups to remove this contact as a member (max 20)
| vars | object, optional Custom variables and values to update on the contact. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
|
Return TypeContact | Examplevar contact = project.getOrCreateContact({
name: "John Smith",
phone_number: "5550123",
add_group_ids: ["CG37f46ac132ef1542", "CG47f46ac232ee0123"],
vars: {'email': "jsmith@example.com", 'birthdate': "1953-01-04", 'your_id': "12942938"}
});
|
project.queryContacts(options)
Queries contacts within the given project.
ArgumentsOptionsgroup_id | string ID of Group, optional Filter contacts within a group
| name | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | phone_number | string, optional Filter contacts by phone number
Allowed Modifiers: phone_number[ne], phone_number[prefix], phone_number[not_prefix], phone_number[gte], phone_number[gt], phone_number[lt], phone_number[lte], phone_number[exists] (?) | time_created | UNIX timestamp, optional Filter contacts by time created
Allowed Modifiers: time_created[min], time_created[max] (?) | last_message_time | UNIX timestamp, optional Filter contacts by last time a message was sent or received
Allowed Modifiers: last_message_time[min], last_message_time[max], last_message_time[exists] (?) | last_incoming_message_time | UNIX timestamp, optional Filter contacts by last time a message was received
Allowed Modifiers: last_incoming_message_time[min], last_incoming_message_time[max], last_incoming_message_time[exists] (?) | last_outgoing_message_time | UNIX timestamp, optional Filter contacts by last time a message was sent
Allowed Modifiers: last_outgoing_message_time[min], last_outgoing_message_time[max], last_outgoing_message_time[exists] (?) | incoming_message_count | int, optional Filter contacts by number of messages received from the contact
Allowed Modifiers: incoming_message_count[ne], incoming_message_count[min], incoming_message_count[max] (?) | outgoing_message_count | int, optional Filter contacts by number of messages sent to the contact
Allowed Modifiers: outgoing_message_count[ne], outgoing_message_count[min], outgoing_message_count[max] (?) | send_blocked | bool, optional Filter contacts by blocked status
| vars | object, optional Filter contacts by value of a custom variable (e.g. vars[email], vars[foo], etc.)
Allowed Modifiers: vars[foo][ne], vars[foo][prefix], vars[foo][not_prefix], vars[foo][gte], vars[foo][gt], vars[foo][lt], vars[foo][lte], vars[foo][min], vars[foo][max], vars[foo][exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name, phone_number, last_message_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Contact | Examplecursor = project.queryContacts({
name: {'prefix': "John"},
last_message_time: {'min': 1734645745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var contact = cursor.next();
// do something with contact
}
|
project.importContacts(options)
Creates and/or updates up to 200 contacts in a single API call. When creating or updating a large number of contacts, this method is significantly faster than sending a separate API request for each contact.
By default, if the phone number for any contact matches an existing contact, the existing contact will be updated with any information provided. This behavior can be modified by setting the lookup_key parameter to look up contacts by another field, including a custom variable.
If any contact was not found matching the provided lookup_key , a new contact will be created.
ArgumentsOptionscontacts | array, required Array of up to 200 objects which may contain the properties name (string), phone_number (string), vars (object), and send_blocked (boolean). All properties are optional, unless used as a lookup key; however, either a name or phone_number property must be provided for new contacts.
| lookup_key | string, optional The field used to search for a matching contact, or 'none' to always create a new contact. To search by a custom variable, precede the variable name with 'vars.'.
Possible Values: phone_number, id, vars.variable_name, none Default: phone_number | add_group_ids | array of string IDs of Group, optional ID of one or more groups to add these contacts as members (max 5)
| remove_group_ids | array of string IDs of Group, optional ID of one or more groups to remove these contacts as members (max 5)
| default_route_id | string ID of Route, optional ID of the route to use by default to send messages to these contacts
|
Return Typeobject Return Value Propertiescontacts |
array
List of objects representing each contact, with the same length and order as provided in the contacts parameter in the API request. Each object has a string id property.
|
| Examplevar res = project.importContacts({
contacts: [{'name': "John Smith", 'phone_number': "5550123"}, {'name': "Jane Doe", 'phone_number': "5550124", 'vars': {'foo': "bar", 'baz': 12}}],
add_group_ids: ["CG37f46ac132ef1542", "CG47f46ac232ee0123"]
});
|
contact.delete()
ArgumentsNone Return Typeundefined | Examplecontact.delete();
|
project.getContactFields()
Gets a list of all custom fields defined for contacts in this project. The return value is an array of objects with the properties 'name', 'variable', 'type', 'order', 'readonly', and 'lookup_key'. (Fields are automatically created any time a Contact's 'vars' property is updated.)
ArgumentsNone Return Typearray | Exampleproject.getContactFields();
|
project.initContactById(id)
Initializes the Telerivet contact with the given ID without making an API request.
ArgumentsReturn TypeContact | Examplevar contact = project.initContactById(contact_id);
|
project.getContactById(id)
Retrieves the contact with the given ID.
ArgumentsReturn TypeContact | Examplevar contact = project.getContactById(contact_id);
|
contact.save()
Saves any fields or custom variables that have changed for this contact.
ArgumentsNone Return Typeundefined | Examplecontact.name = "John Smith";
contact.phone_number = "+16505550123";
contact.send_blocked = false;
contact.conversation_status = "active";
contact.vars.email = "jsmith@example.com";
contact.vars.birthdate = "1953-01-05";
contact.save();
|
contact.queryMessages(options)
Queries messages sent or received by this contact.
ArgumentsOptionsdirection | string, optional Filter messages by direction
Possible Values: incoming, outgoing | message_type | string, optional Filter messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | source | string, optional Filter messages by source
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | starred | bool, optional Filter messages by starred/unstarred
| status | string, optional Filter messages by status
Possible Values: ignored, processing, received, sent, queued, failed, failed_queued, cancelled, delivered, not_delivered, read | time_created[min] | UNIX timestamp, optional Filter messages created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter messages created before a particular time
| external_id | string, optional Filter messages by ID from an external provider
Allowed Modifiers: external_id[ne], external_id[exists] (?) | contact_id | ID of the contact who sent/received the message
Allowed Modifiers: contact_id[ne], contact_id[exists] (?) | phone_id | string ID of Phone, optional ID of the phone (basic route) that sent/received the message
| broadcast_id | ID of the broadcast containing the message
Allowed Modifiers: broadcast_id[ne], broadcast_id[exists] (?) | scheduled_id | ID of the scheduled message that created this message
Allowed Modifiers: scheduled_id[ne], scheduled_id[exists] (?) | group_id | string ID of Group, optional Filter messages sent or received by contacts in a particular group. The group must be a normal group, not a dynamic group.
| sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Message | Examplecursor = contact.queryMessages({
direction: "incoming",
message_type: "sms"
});
cursor.limit(50);
while (cursor.hasNext()) {
var message = cursor.next();
// do something with message
}
|
contact.removeFromGroup(group)
Removes this contact from a group.
ArgumentsReturn Typeundefined | Examplevar group = project.initGroupById(group_id);
contact.removeFromGroup(group);
|
contact.addToGroup(group)
Adds this contact to a group.
ArgumentsReturn Typeundefined | Examplevar group = project.initGroupById(group_id);
contact.addToGroup(group);
|
contact.isInGroup(group)
Returns true if this contact is in a particular group, false otherwise.
ArgumentsReturn Typebool | Examplevar group = project.initGroupById(group_id);
contact.isInGroup(group);
|
contact.queryServiceStates(options)
Queries this contact's current states for any service
ArgumentsOptionsid | string, optional Allowed Modifiers: id[ne], id[prefix], id[not_prefix], id[gte], id[gt], id[lt], id[lte] (?) | vars | object, optional Filter states by value of a custom variable (e.g. vars[email], vars[foo], etc.)
Allowed Modifiers: vars[foo][ne], vars[foo][prefix], vars[foo][not_prefix], vars[foo][gte], vars[foo][gt], vars[foo][lt], vars[foo][lte], vars[foo][min], vars[foo][max], vars[foo][exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of ContactServiceState | Examplecursor = contact.queryServiceStates({
id: "q1"
});
cursor.limit(50);
while (cursor.hasNext()) {
var state = cursor.next();
// do something with state
}
|
contact.queryDataRows(options)
Queries data rows associated with this contact (in any data table).
ArgumentsOptionstime_created | UNIX timestamp, optional Filter data rows by the time they were created
Allowed Modifiers: time_created[min], time_created[max] (?) | sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of DataRow | Examplecursor = contact.queryDataRows();
cursor.limit(50);
while (cursor.hasNext()) {
var row = cursor.next();
// do something with row
}
|
contact.queryScheduledMessages(options)
Queries messages scheduled to this contact (not including messages scheduled to groups that this contact is a member of)
ArgumentsOptionsmessage_type | string, optional Filter scheduled messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | time_created | UNIX timestamp, optional Filter scheduled messages by time_created
Allowed Modifiers: time_created[min], time_created[max] (?) | next_time | UNIX timestamp, optional Filter scheduled messages by next_time
Allowed Modifiers: next_time[min], next_time[max], next_time[exists] (?) | relative_scheduled_id | Filter scheduled messages created for a relative scheduled message
| sort | string, optional Sort the results based on a field
Possible Values: default, next_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of ScheduledMessage | Examplecursor = contact.queryScheduledMessages({
message_type: "sms",
next_time: {'min': 1742421745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var scheduled_msg = cursor.next();
// do something with scheduled_msg
}
|
contact.queryGroups(options)
Queries groups for which this contact is a member.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | dynamic | bool, optional Filter groups by dynamic/non-dynamic
| sort | string, optional Sort the results based on a field
Possible Values: default, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Group | Examplecursor = contact.queryGroups();
cursor.limit(50);
while (cursor.hasNext()) {
var group = cursor.next();
// do something with group
}
|
project.setContactFieldMetadata(variable, options)
Allows customizing how a custom contact field is displayed in the Telerivet web app.
The variable path parameter can contain the characters a-z, A-Z, 0-9, and _, and may be up to 32 characters in length.
Argumentsvariable | string, required The variable name of the field to create or update.
| options | object, required |
Optionsname | string, max 64 characters, optional Display name for the field
| type | int, optional Possible Values: text, long_text, secret, phone_number, email, url, audio, date, date_time, number, boolean, checkbox, select, radio, route | order | int, optional Order in which to display the field
| items | array, required if type is `select` Array of up to 100 objects containing value and label string properties to show in the dropdown list when type is select . Each value and label must be between 1 and 256 characters in length.
| readonly | bool, optional Set to true to prevent editing the field in the Telerivet web app
| lookup_key | bool, optional Set to true to allow using this field as a lookup key when importing contacts via the Telerivet web app
| show_on_conversation | bool, optional Set to true to show field on Conversations tab
|
Return Typeobject | Exampleproject.setContactFieldMetadata("age", {
name: "Age",
type: "number",
order: 2
});
|
Routes | |
Object Type: Phone
Represents a basic route (i.e. a phone or gateway) that you use to send/receive messages via Telerivet.
Basic Routes were formerly referred to as "Phones" within Telerivet. API methods, parameters, and properties related to Basic Routes continue to use the term "Phone" to maintain backwards compatibility.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
phone_number |
string Phone number or sender ID
| updatable |
phone_type |
string Type of this phone/route (e.g. android, twilio, nexmo, etc)
| read-only |
country |
string 2-letter country code (ISO 3166-1 alpha-2) where phone is from
| read-only |
send_paused |
bool True if sending messages is currently paused, false if the phone can currently send messages
| updatable |
time_created |
UNIX timestamp Time the phone was created in Telerivet
| read-only |
last_active_time |
UNIX timestamp Approximate time this phone last connected to Telerivet
| read-only |
vars |
object Custom variables stored for this phone. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this phone belongs to
| read-only |
battery |
int Current battery level, on a scale from 0 to 100, as of the last time the phone connected to Telerivet (only present for Android phones)
| read-only |
charging |
bool True if the phone is currently charging, false if it is running on battery, as of the last time it connected to Telerivet (only present for Android phones)
| read-only |
internet_type |
string String describing the current type of internet connectivity for an Android phone, for example WIFI or MOBILE (only present for Android phones)
| read-only |
app_version |
string Currently installed version of Telerivet Android app (only present for Android phones)
| read-only |
android_sdk |
int Android SDK level, indicating the approximate version of the Android OS installed on this phone; see list of Android SDK levels (only present for Android phones)
| read-only |
mccmnc |
string Code indicating the Android phone's current country (MCC) and mobile network operator (MNC); see Mobile country code Wikipedia article (only present for Android phones). Note this is a string containing numeric digits, not an integer.
| read-only |
manufacturer |
string Android phone manufacturer (only present for Android phones)
| read-only |
model |
string Android phone model (only present for Android phones)
| read-only |
send_limit |
int Maximum number of SMS messages per hour that can be sent by this Android phone. To increase this limit, install additional SMS expansion packs in the Telerivet Gateway app. (only present for Android phones)
| read-only |
url |
string URL to this phone in the Telerivet web app
| read-only |
|
Example[object Phone] JSON: {
"id": "PN4d246818d0ecd1fa",
"name": "Android Phone 1",
"phone_number": "+16505550001",
"phone_type": "android",
"country": "TZ",
"send_paused": false,
"time_created": 1390343779,
"last_active_time": 1390353800,
"vars": {
"foo": 42
},
"project_id": "PJ2ad0100821a98bea",
"battery": 95,
"charging": false,
"internet_type": "WIFI",
"app_version": "3.1.17",
"android_sdk": 17,
"mccmnc": "23203",
"manufacturer": "LGE",
"model": "Nexus 4",
"send_limit": 900,
"url": "https://telerivet.com/p/asdf/phone/PN4d246818d0ecd1fa"
} |
Object Type: Route
Represents a custom route that can be used to send messages via one or more basic routes (phones).
Custom Routes were formerly referred to simply as "Routes" within Telerivet. API methods, parameters, and properties related to Custom Routes continue to use the term "Route" to maintain backwards compatibility.
Custom routing rules can currently only be configured via Telerivet's web UI.
Attributesid |
string, max 34 characters Telerivet's internal ID for the route
| read-only |
name |
string | updatable |
vars |
object Custom variables stored for this route. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this route belongs to
| read-only |
|
Example[object Route] JSON: {
"id": "RTed8af84c2679ac09",
"name": "Custom Route",
"vars": {
"foo": "bar",
"baz": 42
},
"project_id": "PJ2ad0100821a98bea"
} |
project.queryPhones(options)
Queries basic routes within the given project.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | phone_number | string, optional Filter phones by phone number
Allowed Modifiers: phone_number[ne], phone_number[prefix], phone_number[not_prefix], phone_number[gte], phone_number[gt], phone_number[lt], phone_number[lte] (?) | last_active_time | UNIX timestamp, optional Filter phones by last active time
Allowed Modifiers: last_active_time[min], last_active_time[max], last_active_time[exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name, phone_number Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Phone | Examplecursor = project.queryPhones();
cursor.limit(50);
while (cursor.hasNext()) {
var phone = cursor.next();
// do something with phone
}
|
project.getPhoneById(id)
Retrieves the basic route with the given ID.
ArgumentsReturn TypePhone | Examplevar phone = project.getPhoneById(phone_id);
|
project.initPhoneById(id)
Initializes the basic route with the given ID without making an API request.
ArgumentsReturn TypePhone | Examplevar phone = project.initPhoneById(phone_id);
|
project.queryRoutes(options)
Queries custom routes that can be used to send messages (not including Phones).
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Route | Examplecursor = project.queryRoutes();
cursor.limit(50);
while (cursor.hasNext()) {
var route = cursor.next();
// do something with route
}
|
project.getRouteById(id)
Gets a custom route by ID
ArgumentsReturn TypeRoute | Examplevar route = project.getRouteById(route_id);
|
project.initRouteById(id)
Initializes a custom route by ID without making an API request.
ArgumentsReturn TypeRoute | Examplevar route = project.initRouteById(route_id);
|
phone.queryMessages(options)
Queries messages sent or received by this basic route.
ArgumentsOptionsdirection | string, optional Filter messages by direction
Possible Values: incoming, outgoing | message_type | string, optional Filter messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | source | string, optional Filter messages by source
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | starred | bool, optional Filter messages by starred/unstarred
| status | string, optional Filter messages by status
Possible Values: ignored, processing, received, sent, queued, failed, failed_queued, cancelled, delivered, not_delivered, read | time_created[min] | UNIX timestamp, optional Filter messages created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter messages created before a particular time
| external_id | string, optional Filter messages by ID from an external provider
Allowed Modifiers: external_id[ne], external_id[exists] (?) | contact_id | ID of the contact who sent/received the message
Allowed Modifiers: contact_id[ne], contact_id[exists] (?) | phone_id | string ID of Phone, optional ID of the phone (basic route) that sent/received the message
| broadcast_id | ID of the broadcast containing the message
Allowed Modifiers: broadcast_id[ne], broadcast_id[exists] (?) | scheduled_id | ID of the scheduled message that created this message
Allowed Modifiers: scheduled_id[ne], scheduled_id[exists] (?) | group_id | string ID of Group, optional Filter messages sent or received by contacts in a particular group. The group must be a normal group, not a dynamic group.
| sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Message | Examplecursor = phone.queryMessages({
direction: "incoming",
message_type: "sms"
});
cursor.limit(50);
while (cursor.hasNext()) {
var message = cursor.next();
// do something with message
}
|
phone.save()
Saves any fields or custom variables that have changed for this basic route.
ArgumentsNone Return Typeundefined | Examplephone.name = "Android Phone 1";
phone.phone_number = "+16505550001";
phone.send_paused = false;
phone.vars.foo = 42;
phone.save();
|
route.save()
Saves any fields or custom variables that have changed for this custom route.
ArgumentsNone Return Typeundefined | Examplevar route = project.initRouteById(route_id);
route.name = "Custom Route";
route.vars.foo = "bar";
route.vars.baz = 42;
route.save();
|
Services | |
Object Type: Service
Represents an automated service on Telerivet, for example a poll, auto-reply, webhook service, etc.
A service, generally, defines some automated behavior that can be invoked/triggered in a particular context, and may be invoked either manually or when a particular event occurs.
Most commonly, services work in the context of a particular message, when the message is originally received by Telerivet.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
service_type |
string | read-only |
active |
bool Whether the service is active or inactive. Inactive services are not automatically triggered and cannot be invoked via the API.
| updatable |
priority |
int A number that determines the order that services are triggered when a particular event occurs (smaller numbers are triggered first). Any service can determine whether or not execution "falls-through" to subsequent services (with larger priority values) by setting the return_value variable within Telerivet's Rules Engine.
| updatable |
contexts |
object A key/value map where the keys are the names of contexts supported by this service (e.g. message, contact), and the values are themselves key/value maps where the keys are event names and the values are all true. (This structure makes it easy to test whether a service can be invoked for a particular context and event.)
| read-only |
vars |
object Custom variables stored for this service. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this service belongs to
| read-only |
response_table_id |
ID of the data table where responses to this service will be stored
| updatable |
phone_ids |
string IDs of phones (basic routes) associated with this service, or null if the service is associated with all routes. Only applies for service types that handle incoming messages, voice calls, or USSD sessions.
| updatable |
apply_mode |
string If apply_mode is unhandled , the service will not be triggered if another service has already handled the incoming message. If apply_mode is always , the service will always be triggered regardless of other services. Only applies to services that handle incoming messages.
Possible Values: always, unhandled | updatable |
contact_number_filter |
string If contact_number_filter is long_number , this service will only be triggered if the contact phone number has at least 7 digits (ignoring messages from shortcodes and alphanumeric senders). If contact_number_filter is all , the service will be triggered for all contact phone numbers. Only applies to services that handle incoming messages.
Possible Values: long_number, all | updatable |
show_action |
bool Whether this service is shown in the 'Actions' menu within the Telerivet web app when the service is active. Only provided for service types that are manually triggered.
| updatable |
direction |
string Determines whether the service handles incoming voice calls, outgoing voice calls, or both. Only applies to services that handle voice calls.
Possible Values: incoming, outgoing, both | updatable |
webhook_url |
string URL that a third-party can invoke to trigger this service. Only provided for services that are triggered by a webhook request.
| read-only |
|
Example[object Service] JSON: {
"id": "SVee45c8ae4e32889a",
"name": "Poll Service",
"service_type": "messaging_poll",
"active": true,
"priority": 1,
"contexts": {
"message": {
"incoming_message": true
},
"contact": {
"default": true
}
},
"vars": {
"foo": "bar",
"baz": 42
},
"project_id": "PJ2ad0100821a98bea",
"response_table_id": "DTf9fe14d9c306aed9",
"phone_ids": null,
"apply_mode": null,
"contact_number_filter": null,
"show_action": null,
"direction": null,
"webhook_url": null
} |
Object Type: ContactServiceState
Represents the current state of a particular contact for a particular Telerivet service.
Some automated services (including polls) are 'stateful'. For polls, Telerivet needs to keep track of which question the contact is currently answering, and stores store the ID of each contact's current question (e.g. 'q1' or 'q2') as the ID of the contact's state for the poll service. Any type of conversation-like service will also need to store state for each contact.
For this type of entity, the 'id' field is NOT a read-only unique ID (unlike all other types of entities). Instead it is an arbitrary string that identifies the contact's current state within your poll/conversation; many contacts may have the same state ID, and it may change over time. Additional custom fields may be stored in the 'vars'.
Initially, the state 'id' for any contact is null. When saving the state, setting the 'id' to null is equivalent to resetting the state (so all 'vars' will be deleted); if you want to save custom variables, the state 'id' must be non-null.
Many Telerivet services are stateless, such as auto-replies or keyword-based services where the behavior only depends on the current message, and not any previous messages sent by the same contact. Telerivet doesn't store any state for contacts that interact with stateless services.
Attributesid |
string, max 63 characters Arbitrary string representing the contact's current state for this service, e.g. 'q1', 'q2', etc.
| updatable |
contact_id |
| read-only |
service_id |
| read-only |
vars |
object Custom variables stored for this contact/service state. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
time_created |
UNIX timestamp Time the state was first created in Telerivet
| read-only |
time_updated |
UNIX timestamp Time the state was last updated in Telerivet
| read-only |
project_id |
ID of the project this contact/service state belongs to
| read-only |
|
Example[object ContactServiceState] JSON: {
"id": "q1",
"contact_id": "CTa1299c3d0e371023",
"service_id": "SVee45c8ae4e32889a",
"vars": {
"q1": "yes",
"q2": "no"
},
"time_created": 1395617416,
"time_updated": 1395617440,
"project_id": "PJ2ad0100821a98bea"
} |
service.invoke(options)
Manually invoke this service in a particular context.
For example, to send a poll to a particular contact (or resend the current question), you can invoke the poll service with context=contact, and contact_id as the ID of the contact to send the poll to. (To trigger a service to multiple contacts, use project.sendBroadcast. To schedule a service in the future, use project.scheduleMessage.)
Or, to manually apply a service for an incoming message, you can invoke the service with context =message , event =incoming_message , and message_id as the ID of the incoming message. (This is normally not necessary, but could be used if you want to override Telerivet's standard priority-ordering of services.)
ArgumentsOptionscontext | string, required The name of the context in which this service is invoked
Possible Values: message, call, ussd_session, row, contact, project | event | string, optional The name of the event that is triggered (must be supported by this service)
Default: default | message_id | string ID of Message, required if context is 'message' The ID of the message this service is triggered for
| contact_id | The ID of the contact this service is triggered for (either contact_id or phone_number is required if context is 'contact')
| phone_number | string, optional The phone number of the contact this service is triggered for (either contact_id or phone_number is required if context is 'contact'). If no contact exists with this phone number, a new contact will be created.
| variables | object, optional Object containing up to 25 temporary variable names and their corresponding values to set when invoking the service. Values may be strings, numbers, or boolean (true/false). String values may be up to 4096 bytes in length. Arrays and objects are not supported. Within Custom Actions, each variable can be used like [[$name]] (with a leading $ character and surrounded by double square brackets). Within a Cloud Script API service or JavaScript action, each variable will be available as a global JavaScript variable like $name (with a leading $ character).
| route_id | string, optional The ID of the phone or route that the service will use for sending messages by default
| async | bool, optional If set to true, the service will be invoked asynchronously. By default, queued services will be invoked one at a time for each project.
|
Return Typeobject Return Value Propertiesreturn_value |
any
Return value of the service. May be any JSON type (boolean, number, string, array, object, or null). (Undefined if async=true.)
| log_entries |
array
Array of log entry strings generated by the service. (Undefined if async=true.)
| errors |
array
Array of error message strings generated by the service. (Undefined if async=true.)
| sent_messages |
array of objects
Array of messages sent by the service.
| airtime_transactions |
array of objects
Array of airtime transactions sent by the service (Undefined if async=true.)
|
| Examplevar otherService = project.initServiceById(service_id);
otherService.invoke({
context: "contact",
contact_id: contact.id,
variables: {'first_name': "John", 'age': 30}
});
|
project.createService(options)
Creates a new automated service.
Only certain types of automated services can be created via the API. Other types of services can only be created via the web app.
Although Custom Actions services cannot be created directly via the API, they may be converted to a template,
and then instances of the template can be created via this method with service_type =custom_template_instance . Converting a service
to a template requires the Service Templates feature to be enabled for the organization.
ArgumentsOptionsname | string, optional Name of the service to create, which must be unique in the project. If a name is not provided, a unique default name will be generated.
| service_type | string, required Type of service to create. The following service types can be created via the API:
- incoming_message_webhook
- incoming_message_script
- contact_script
- message_script
- data_row_script
- webhook_script
- voice_script
- ussd_script
- project_script
- custom_template_instance
Other types of services can only be created via the web app.
| config | object, required Configuration specific to the service type .
incoming_message_webhook:
url | The webhook URL that will be triggered when an incoming message is received (string) |
secret | Optional string that will be passed as the `secret` POST parameter to the webhook URL. (object) |
incoming_message_script, contact_script, message_script, data_row_script, webhook_script, voice_script, ussd_script, project_script:
code | The JavaScript code to run when the service is triggered (max 100 KB). To run code longer than 100 KB, use a Cloud Script Module. (string) |
custom_template_instance:
template_service_id | ID of the service template (string). The service template must be available to the current project or organization. |
params | Key/value pairs for all service template parameters (object). If the values satisfy the validation rules specified in the service template, they will also be copied to the `vars` property of the service. Any values not associated with service template parameters will be ignored.
|
| vars | string, optional Custom variables and values to set for this service. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| active | bool, optional Whether the service is initially active or inactive. Inactive services are not automatically triggered and cannot be invoked via the API.
Default: true | response_table_id | ID of a data table where responses will be stored, or null to disable automatically storing responses. If the response_table_id parameter is not provided, a data table may automatically be created with the same name as the service if the service collects responses.
| phone_ids | array of string IDs of Phone, optional IDs of phones (basic routes) to associate with this service, or null to associate this service with all routes. Only applies for service types that handle incoming messages, voice calls, or USSD sessions.
| message_types | array, optional Types of messages that this service should handle. Only applies to services that handle incoming messages.
Possible Values: text, call, sms, mms, ussd_session, chat | show_action | bool, optional Whether to show this service in the Actions menu within the Telerivet web app when the service is active. Only applies for service types that are manually triggered.
Default: true | contact_number_filter | string, optional If contact_number_filter is long_number , this service will only be triggered if the contact phone number has at least 7 digits (ignoring messages from shortcodes and alphanumeric senders). If contact_number_filter is all , the service will be triggered for all contact phone numbers. Only applies to services that handle incoming messages.
Possible Values: long_number, all Default: long_number | direction | string, optional Determines whether the service handles incoming voice calls, outgoing voice calls, or both. Only applies to services that handle voice calls.
Possible Values: incoming, outgoing, both Default: both | priority | int, optional A number that determines the order that services are triggered when an event occurs (e.g. when an incoming message is received). Smaller numbers are triggered first. The priority is ignored for services that are triggered directly.
| apply_mode | string, optional If apply_mode is unhandled , the service will not be triggered if another service has already handled the incoming message. If apply_mode is always , the service will always be triggered regardless of other services. Only applies to services that handle incoming messages.
Possible Values: always, unhandled Default: unhandled |
Return TypeService | Examplevar service = project.createService({
name: "Example Service",
service_type: "incoming_message_webhook",
config: {'url': "https://your-company.example.com/webhook", 'secret': "abcdefg123"},
vars: {'example': 42},
active: true
});
|
project.queryServices(options)
Queries services within the given project.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | active | bool, optional Filter services by active/inactive state
| context | string, optional Filter services that can be invoked in a particular context
Possible Values: message, call, ussd_session, row, contact, project | sort | string, optional Sort the results based on a field
Possible Values: default, priority, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Service | Examplecursor = project.queryServices({
active: true,
context: "message"
});
cursor.limit(50);
while (cursor.hasNext()) {
var service = cursor.next();
// do something with service
}
|
project.getServiceById(id)
Retrieves the service with the given ID.
ArgumentsReturn TypeService | Examplevar service = project.getServiceById(service_id);
|
project.initServiceById(id)
Initializes the service with the given ID without making an API request.
ArgumentsReturn TypeService | Examplevar service = project.initServiceById(service_id);
|
service.setConfig(options)
Updates configuration specific to the type of automated service.
Only certain types of services support updating their configuration via the API.
Note: when updating a service of type custom_template_instance,
the validation script will be invoked when calling this method.
ArgumentsReturn Typeobject | Exampleservice.setConfig({'url': "https://your-company.example.com/webhook", 'secret': "asdf123"});
|
service.getConfig()
Gets configuration specific to the type of automated service.
Only certain types of services provide their configuration via the API.
ArgumentsNone Return Typeobject | Exampleservice.getConfig();
|
service.save()
Saves any fields or custom variables that have changed for this service.
ArgumentsNone Return Typeundefined | Exampleservice.name = "Poll Service";
service.active = true;
service.priority = 1;
service.vars.foo = "bar";
service.vars.baz = 42;
service.response_table_id = "DTf9fe14d9c306aed9";
service.save();
|
project.queryServiceLogs(options)
Queries service log entries associated with this project.
Note: Service logs are automatically deleted and no longer available via the API after approximately one month.
ArgumentsOptionsservice_id | Filter logs generated by a particular service
| message_id | Filter service logs related to a particular message
| contact_id | Filter service logs related to a particular contact. Ignored if using the message_id parameter.
| time_created | UNIX timestamp, optional Filter service logs by the time they were created
Allowed Modifiers: time_created[min], time_created[max] (?) | execution_stats | bool, optional Show detailed execution stats for each log entry, if available.
| sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of object
Returned Item Propertiestime_created |
UNIX timestamp
The time when the log entry was created
| content |
string
| elapsed_ms |
int
Elapsed time in milliseconds, if available.
| service_id |
string
ID of the service associated with this log entry. Not returned when querying log entries for a particular service.
| message_id |
string
ID of the message associated with this log entry. Not returned when querying log entries for a particular message.
| contact_id |
string
ID of the contact associated with this log entry. Not returned when querying log entries for a particular message or contact.
| api_request_count |
int
The total number of API requests triggered via the Cloud Script API. (Only provided if execution_stats=true.)
| api_request_ms |
int
The total execution time of all API requests triggered via the Cloud Script API. (Only provided if execution_stats=true.)
| http_request_count |
int
The total number of external HTTP requests triggered via the Cloud Script API. (Only provided if execution_stats=true.)
| http_request_ms |
int
The total execution time of all external HTTP requests triggered via the Cloud Script API. (Only provided if execution_stats=true.)
| webhook_count |
int
The total number of Webhook API requests triggered. (Only provided if execution_stats=true.)
| requests |
array
Details about each API request, external HTTP request, and Cloud Script Module loaded via the Cloud Script API. (Only provided if execution_stats=true.)
Each item in the array has the following properties:
- type (string):
api_request , http_request , or module_load
- resource (string): A string specific to the type of request.
For module_load, this is the module path. For api_request, it contains the HTTP
method, path, and query string. For http_request, it contains the HTTP method and
URL.
- elapsed_ms (int): Number of milliseconds elapsed in fetching
this resource
- status_code (int): Response status code, if available
|
| Examplecursor = project.queryServiceLogs({
execution_stats: true
});
cursor.limit(50);
while (cursor.hasNext()) {
var obj = cursor.next();
// do something with obj
}
|
service.queryContactStates(options)
Query the current states of contacts for this service.
ArgumentsOptionsid | string, optional Allowed Modifiers: id[ne], id[prefix], id[not_prefix], id[gte], id[gt], id[lt], id[lte] (?) | vars | object, optional Filter states by value of a custom variable (e.g. vars[email], vars[foo], etc.)
Allowed Modifiers: vars[foo][ne], vars[foo][prefix], vars[foo][not_prefix], vars[foo][gte], vars[foo][gt], vars[foo][lt], vars[foo][lte], vars[foo][min], vars[foo][max], vars[foo][exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of ContactServiceState | Examplecursor = service.queryContactStates({
id: "q1"
});
cursor.limit(50);
while (cursor.hasNext()) {
var state = cursor.next();
// do something with state
}
|
service.getContactState(contact)
Gets the current state for a particular contact for this service.
If the contact doesn't already have a state, this method will return a valid state object with id=null. However this object would not be returned by queryContactStates() unless it is saved with a non-null state id.
Argumentscontact | The contact whose state you want to retrieve.
|
Return TypeContactServiceState | Example
var state = service.getContactState(contact);
|
service.setContactState(contact, options)
Initializes or updates the current state for a particular contact for the given service. If the state id is null, the contact's state will be reset.
Argumentscontact | The contact whose state you want to update.
| options | object, required |
Optionsid | string, max 63 characters, required Arbitrary string representing the contact's current state for this service, e.g. 'q1', 'q2', etc.
| vars | object, optional Custom variables stored for this contact's state. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
|
Return TypeContactServiceState | Example
var state = service.setContactState(contact, {
id: "q1",
vars: {'foo': "bar"}
});
|
service.resetContactState(contact)
Resets the current state for a particular contact for the given service.
Argumentscontact | The contact whose state you want to reset.
|
Return TypeContactServiceState | Example
var state = service.resetContactState(contact);
|
service.delete()
ArgumentsNone Return Typeundefined | Exampleservice.delete();
|
Labels | |
Object Type: Label
Represents a label used to organize messages within Telerivet.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
time_created |
UNIX timestamp Time the label was created in Telerivet
| read-only |
vars |
object Custom variables stored for this label. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this label belongs to
| read-only |
|
Example[object Label] JSON: {
"id": "LB4f3dac27154653e0",
"name": "Important",
"time_created": 1392254503,
"vars": {
"foo": "bar",
"baz": 42
},
"project_id": "PJ2ad0100821a98bea"
} |
project.queryLabels(options)
Queries labels within the given project.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Label | Examplecursor = project.queryLabels();
cursor.limit(50);
while (cursor.hasNext()) {
var label = cursor.next();
// do something with label
}
|
project.getOrCreateLabel(name)
Gets or creates a label by name.
ArgumentsReturn TypeLabel | Examplevar label = project.getOrCreateLabel("Important");
|
project.getLabelById(id)
Retrieves the label with the given ID.
ArgumentsReturn TypeLabel | Examplevar label = project.getLabelById(label_id);
|
project.initLabelById(id)
Initializes the label with the given ID without making an API request.
ArgumentsReturn TypeLabel | Examplevar label = project.initLabelById(label_id);
|
label.queryMessages(options)
Queries messages with the given label.
ArgumentsOptionsdirection | string, optional Filter messages by direction
Possible Values: incoming, outgoing | message_type | string, optional Filter messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | source | string, optional Filter messages by source
Possible Values: phone, provider, web, api, service, webhook, scheduled, integration | starred | bool, optional Filter messages by starred/unstarred
| status | string, optional Filter messages by status
Possible Values: ignored, processing, received, sent, queued, failed, failed_queued, cancelled, delivered, not_delivered, read | time_created[min] | UNIX timestamp, optional Filter messages created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter messages created before a particular time
| external_id | string, optional Filter messages by ID from an external provider
Allowed Modifiers: external_id[ne], external_id[exists] (?) | contact_id | ID of the contact who sent/received the message
Allowed Modifiers: contact_id[ne], contact_id[exists] (?) | phone_id | string ID of Phone, optional ID of the phone (basic route) that sent/received the message
| broadcast_id | ID of the broadcast containing the message
Allowed Modifiers: broadcast_id[ne], broadcast_id[exists] (?) | scheduled_id | ID of the scheduled message that created this message
Allowed Modifiers: scheduled_id[ne], scheduled_id[exists] (?) | group_id | string ID of Group, optional Filter messages sent or received by contacts in a particular group. The group must be a normal group, not a dynamic group.
| sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Message | Examplevar label = project.initLabelById(label_id);
cursor = label.queryMessages({
direction: "incoming",
message_type: "sms"
});
cursor.limit(50);
while (cursor.hasNext()) {
var message = cursor.next();
// do something with message
}
|
label.save()
Saves any fields that have changed for the label.
ArgumentsNone Return Typeundefined | Examplevar label = project.initLabelById(label_id);
label.name = "Important";
label.vars.foo = "bar";
label.vars.baz = 42;
label.save();
|
label.delete()
Deletes the given label (Note: no messages are deleted.)
ArgumentsNone Return Typeundefined | Examplevar label = project.initLabelById(label_id);
label.delete();
|
Groups | |
Object Type: Group
Represents a group used to organize contacts within Telerivet.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
dynamic |
bool Whether this is a dynamic or normal group
| read-only |
num_members |
int Number of contacts in the group (null if the group is dynamic)
| read-only |
time_created |
UNIX timestamp Time the group was created in Telerivet
| read-only |
allow_sending |
bool True if messages can be sent to this group, false otherwise.
| updatable |
add_time_variable |
string Variable name of a custom contact field that will automatically be set to the current date/time on any contact that is added to the group. This variable will only be set if the contact does not already have a value for this variable.
| updatable |
vars |
object Custom variables stored for this group. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this group belongs to
| read-only |
|
Example[object Group] JSON: {
"id": "CGb0b7201b222fa609",
"name": "Subscribers",
"dynamic": false,
"num_members": 142,
"time_created": 1390343845,
"allow_sending": null,
"add_time_variable": "subscription_time",
"vars": {
"foo": "bar",
"baz": 42
},
"project_id": "PJ2ad0100821a98bea"
} |
project.queryGroups(options)
Queries groups within the given project.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | dynamic | bool, optional Filter groups by dynamic/non-dynamic
| sort | string, optional Sort the results based on a field
Possible Values: default, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Group | Examplecursor = project.queryGroups();
cursor.limit(50);
while (cursor.hasNext()) {
var group = cursor.next();
// do something with group
}
|
project.getOrCreateGroup(name)
Retrieves or creates a group by name.
ArgumentsReturn TypeGroup | Examplevar group = project.getOrCreateGroup("Subscribers");
|
project.getGroupById(id)
Retrieves the group with the given ID.
ArgumentsReturn TypeGroup | Examplevar group = project.getGroupById(group_id);
|
project.initGroupById(id)
Initializes the group with the given ID without making an API request.
ArgumentsReturn TypeGroup | Examplevar group = project.initGroupById(group_id);
|
group.queryContacts(options)
Queries contacts that are members of the given group.
ArgumentsOptionsname | string, optional Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | phone_number | string, optional Filter contacts by phone number
Allowed Modifiers: phone_number[ne], phone_number[prefix], phone_number[not_prefix], phone_number[gte], phone_number[gt], phone_number[lt], phone_number[lte], phone_number[exists] (?) | time_created | UNIX timestamp, optional Filter contacts by time created
Allowed Modifiers: time_created[min], time_created[max] (?) | last_message_time | UNIX timestamp, optional Filter contacts by last time a message was sent or received
Allowed Modifiers: last_message_time[min], last_message_time[max], last_message_time[exists] (?) | last_incoming_message_time | UNIX timestamp, optional Filter contacts by last time a message was received
Allowed Modifiers: last_incoming_message_time[min], last_incoming_message_time[max], last_incoming_message_time[exists] (?) | last_outgoing_message_time | UNIX timestamp, optional Filter contacts by last time a message was sent
Allowed Modifiers: last_outgoing_message_time[min], last_outgoing_message_time[max], last_outgoing_message_time[exists] (?) | incoming_message_count | int, optional Filter contacts by number of messages received from the contact
Allowed Modifiers: incoming_message_count[ne], incoming_message_count[min], incoming_message_count[max] (?) | outgoing_message_count | int, optional Filter contacts by number of messages sent to the contact
Allowed Modifiers: outgoing_message_count[ne], outgoing_message_count[min], outgoing_message_count[max] (?) | send_blocked | bool, optional Filter contacts by blocked status
| vars | object, optional Filter contacts by value of a custom variable (e.g. vars[email], vars[foo], etc.)
Allowed Modifiers: vars[foo][ne], vars[foo][prefix], vars[foo][not_prefix], vars[foo][gte], vars[foo][gt], vars[foo][lt], vars[foo][lte], vars[foo][min], vars[foo][max], vars[foo][exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name, phone_number, last_message_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Contact | Examplevar group = project.initGroupById(group_id);
cursor = group.queryContacts({
name: {'prefix': "John"},
last_message_time: {'min': 1734645745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var contact = cursor.next();
// do something with contact
}
|
group.queryScheduledMessages(options)
Queries scheduled messages to the given group.
ArgumentsOptionsmessage_type | string, optional Filter scheduled messages by message_type
Possible Values: sms, mms, ussd, ussd_session, call, chat, service | time_created | UNIX timestamp, optional Filter scheduled messages by time_created
Allowed Modifiers: time_created[min], time_created[max] (?) | next_time | UNIX timestamp, optional Filter scheduled messages by next_time
Allowed Modifiers: next_time[min], next_time[max], next_time[exists] (?) | relative_scheduled_id | Filter scheduled messages created for a relative scheduled message
| sort | string, optional Sort the results based on a field
Possible Values: default, next_time Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of ScheduledMessage | Examplevar group = project.initGroupById(group_id);
cursor = group.queryScheduledMessages({
message_type: "sms",
next_time: {'min': 1742421745}
});
cursor.limit(50);
while (cursor.hasNext()) {
var scheduled_msg = cursor.next();
// do something with scheduled_msg
}
|
group.save()
Saves any fields that have changed for this group.
ArgumentsNone Return Typeundefined | Examplevar group = project.initGroupById(group_id);
group.name = "Subscribers";
group.add_time_variable = "subscription_time";
group.vars.foo = "bar";
group.vars.baz = 42;
group.save();
|
group.delete()
Deletes this group (Note: no contacts are deleted.)
ArgumentsNone Return Typeundefined | Examplevar group = project.initGroupById(group_id);
group.delete();
|
Data Tables | |
Object Type: DataTable
Represents a custom data table that can store arbitrary rows.
For example, poll services use data tables to store a row for each response.
DataTables are schemaless -- each row simply stores custom variables. Each variable name is equivalent to a different "column" of the data table.
Telerivet refers to these variables/columns as "fields", and automatically creates a new field for each variable name used in a row of the table.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
num_rows |
int Number of rows in the table. For performance reasons, this number may sometimes be out-of-date.
| read-only |
show_add_row |
bool Whether to allow adding or importing rows via the web app
| updatable |
show_stats |
bool Whether to show summary charts (pie charts, bar charts, tables of top values) for this data table in the web app
| updatable |
show_contact_columns |
bool Whether to show 'Contact Name' and 'Phone Number' columns in the web app
| updatable |
vars |
object Custom variables stored for this data table. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
project_id |
ID of the project this data table belongs to
| read-only |
|
Example[object DataTable] JSON: {
"id": "DTf9f77c9ba69cce50",
"name": "Poll Responses",
"num_rows": 1032,
"show_add_row": false,
"show_stats": true,
"show_contact_columns": true,
"vars": {
"foo": "bar",
"baz": 42
},
"project_id": "PJ2ad0100821a98bea"
} |
Object Type: DataRow
Represents a row in a custom data table.
For example, each response to a poll is stored as one row in a data table. If a poll has a question with ID 'q1', the verbatim response to that question would be stored in row.vars.q1, and the response code would be stored in row.vars.q1_code.
Each custom variable name within a data row corresponds to a different column/field of the data table.
Attributesid |
string, max 34 characters | read-only |
contact_id |
ID of the contact this row is associated with (or null if not associated with any contact)
| updatable |
from_number |
string Phone number that this row is associated with (or null if not associated with any phone number)
| updatable |
vars |
object Custom variables stored for this data row. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
time_created |
UNIX timestamp The time this row was created in Telerivet
| read-only |
time_updated |
UNIX timestamp The time this row was last updated in Telerivet
| read-only |
table_id |
ID of the table this data row belongs to
| read-only |
project_id |
ID of the project this data row belongs to
| read-only |
|
Example[object DataRow] JSON: {
"id": "DRd442e170d6133590",
"contact_id": "CTa1299c3d0e371023",
"from_number": "+16505550123",
"vars": {
"q1": "yes",
"q2": "no"
},
"time_created": 1395102559,
"time_updated": 1395102578,
"table_id": "DTf9f77c9ba69cce50",
"project_id": "PJ2ad0100821a98bea"
} |
project.getOrCreateDataTable(name)
Gets or creates a data table by name.
ArgumentsReturn TypeDataTable | Examplevar table = project.getOrCreateDataTable("Election Reports");
|
project.getDataTableById(id)
Retrieves the data table with the given ID.
ArgumentsReturn TypeDataTable | Examplevar table = project.getDataTableById(table_id);
|
project.initDataTableById(id)
Initializes the data table with the given ID without making an API request.
ArgumentsReturn TypeDataTable | Examplevar table = project.initDataTableById(table_id);
|
table.queryRows(options)
Queries rows in this data table.
ArgumentsOptionstime_created | UNIX timestamp, optional Filter data rows by the time they were created
Allowed Modifiers: time_created[min], time_created[max] (?) | contact_id | Filter data rows associated with a particular contact
| vars | object, optional Filter data rows by value of a custom variable (e.g. vars[q1], vars[foo], etc.)
Allowed Modifiers: vars[foo][ne], vars[foo][prefix], vars[foo][not_prefix], vars[foo][gte], vars[foo][gt], vars[foo][lt], vars[foo][lte], vars[foo][min], vars[foo][max], vars[foo][exists] (?) | sort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of DataRow | Examplevar table = project.initDataTableById(table_id);
cursor = table.queryRows({
vars: {'q1': "yes", 'q2': "no"}
});
cursor.limit(50);
while (cursor.hasNext()) {
var row = cursor.next();
// do something with row
}
|
table.createRow(options)
Adds a new row to this data table.
ArgumentsOptionscontact_id | ID of the contact that this row is associated with (if applicable)
| from_number | string, optional Phone number that this row is associated with (if applicable)
| vars | string, optional Custom variables and values to set for this data row. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
|
Return TypeDataRow | Examplevar table = project.initDataTableById(table_id);
var row = table.createRow({
from_number: "+16505550123",
vars: {'q1': "yes", 'q2': "no"}
});
|
row.save()
Saves any fields or custom variables that have changed for this data row.
ArgumentsNone Return Typeundefined | Examplevar table = project.initDataTableById(table_id);
var row = table.initRowById(row_id);
row.contact_id = "CTa1299c3d0e371023";
row.from_number = "+16505550123";
row.vars.q1 = "yes";
row.vars.q2 = "no";
row.save();
|
row.delete()
ArgumentsNone Return Typeundefined | Examplevar table = project.initDataTableById(table_id);
var row = table.initRowById(row_id);
row.delete();
|
table.getRowById(id)
Retrieves the row in the given table with the given ID.
ArgumentsReturn TypeDataRow | Examplevar table = project.initDataTableById(table_id);
var row = table.getRowById(row_id);
|
table.initRowById(id)
Initializes the row in the given table with the given ID, without making an API request.
ArgumentsReturn TypeDataRow | Examplevar table = project.initDataTableById(table_id);
var row = table.initRowById(row_id);
|
table.getFields()
Gets a list of all fields (columns) defined for this data table. The return value is an array of objects with the properties 'name', 'variable', 'type', 'order', 'readonly', and 'lookup_key'. (Fields are automatically created any time a DataRow's 'vars' property is updated.)
ArgumentsNone Return Typearray | Examplevar table = project.initDataTableById(table_id);
table.getFields();
|
table.setFieldMetadata(variable, options)
Allows customizing how a field (column) is displayed in the Telerivet web app.
The variable path parameter can contain the characters a-z, A-Z, 0-9, and _, and may be up to 32 characters in length.
Argumentsvariable | string, required The variable name of the field to create or update.
| options | object, required |
Optionsname | string, max 64 characters, optional Display name for the field
| type | string, optional Possible Values: text, long_text, secret, phone_number, email, url, audio, date, date_time, number, boolean, checkbox, select, radio, route | order | int, optional Order in which to display the field
| items | array, required if type is `select` Array of up to 100 objects containing value and label string properties to show in the dropdown list when type is select . Each value and label must be between 1 and 256 characters in length.
| readonly | bool, optional Set to true to prevent editing the field in the Telerivet web app
| lookup_key | bool, optional Set to true to allow using this field as a lookup key when importing rows via the Telerivet web app
|
Return Typeobject | Examplevar table = project.initDataTableById(table_id);
table.setFieldMetadata("q1", {
name: "Question 1",
type: "number",
order: 2
});
|
table.countRowsByValue(variable)
Returns the number of rows for each value of a given variable. This can be used to get the total number of responses for each choice in a poll, without making a separate query for each response choice. The return value is an object mapping values to row counts, e.g. {"yes":7,"no":3}
Argumentsvariable | string, required Variable of field to count by.
|
Return Typeobject | Examplevar table = project.initDataTableById(table_id);
table.countRowsByValue("q1_code");
|
table.save()
Saves any fields that have changed for this data table.
ArgumentsNone Return Typeundefined | Examplevar table = project.initDataTableById(table_id);
table.name = "Poll Responses";
table.show_add_row = false;
table.show_stats = true;
table.show_contact_columns = true;
table.vars.foo = "bar";
table.vars.baz = 42;
table.save();
|
table.delete()
Permanently deletes the given data table, including all its rows
ArgumentsNone Return Typeundefined | Examplevar table = project.initDataTableById(table_id);
table.delete();
|
project.queryDataTables(options)
Queries data tables within the given project.
ArgumentsOptionsname | string, optional Filter data tables by name
Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?) | sort | string, optional Sort the results based on a field
Possible Values: default, name Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of DataTable | Examplecursor = project.queryDataTables();
cursor.limit(50);
while (cursor.hasNext()) {
var table = cursor.next();
// do something with table
}
|
Projects | |
Object Type: Project
Represents a Telerivet project.
Provides methods for sending and scheduling messages, as well as accessing, creating and updating a variety of entities, including contacts, messages, scheduled messages, groups, labels, phones, services, and data tables.
Attributesid |
string, max 34 characters | read-only |
name |
string | updatable |
timezone_id |
string | updatable |
url_slug |
string Unique string used as a component of the project's URL in the Telerivet web app
| updatable |
default_route_id |
string The ID of a basic route or custom route that will be used to send messages by default (via both the API and web app), unless a particular route ID is specified when sending the message.
| updatable |
auto_create_contacts |
bool If true, a contact will be automatically created for each unique phone number that a message is sent to or received from. If false, contacts will not automatically be created (unless contact information is modified by an automated service). The Conversations tab in the web app will only show messages that are associated with a contact.
| updatable |
vars |
object Custom variables stored for this project. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
organization_id |
ID of the organization this project belongs to
| read-only |
url |
string URL to this project in the Telerivet web app
| read-only |
|
Example[object Project] JSON: {
"id": "PJ2ad0100821a98bea",
"name": "Example Project",
"timezone_id": "America/Los_Angeles",
"url_slug": "asdf",
"default_route_id": null,
"auto_create_contacts": true,
"vars": {
"foo": "bar",
"baz": 42
},
"organization_id": "AC1230123421123123",
"url": "https://telerivet.com/p/asdf"
} |
project.getUsers()
Returns an array of user accounts that have access to this project. Each item in the array is an object containing id , email , and name properties. (The id corresponds to the user_id property of the Message object.)
ArgumentsNone Return Typearray | Exampleproject.getUsers();
|
project.getMessageStats(options)
Retrieves statistics about messages sent or received via Telerivet. This endpoint returns historical data that is computed shortly after midnight each day in the project's time zone, and does not contain message statistics for the current day.
ArgumentsOptionsstart_date | string, required Start date of message statistics, in YYYY-MM-DD format
| end_date | string, required End date of message statistics (inclusive), in YYYY-MM-DD format
| rollup | string, optional Date interval to group by
Possible Values: day, week, month, year, all Default: day | properties | string, optional Comma separated list of properties to group by
Possible Values: org_id, org_name, org_industry, project_id, project_name, user_id, user_email, user_name, phone_id, phone_name, phone_type, direction, source, status, network_code, network_name, message_type, service_id, service_name, simulated, link | metrics | string, required Comma separated list of metrics to return (summed for each distinct value of the requested properties)
Possible Values: count, num_parts, duration, price | currency | string, optional Three-letter ISO 4217 currency code used when returning the 'price' field. If the original price was in a different currency, it will be converted to the requested currency using the approximate current exchange rate.
Default: USD | filters | object, optional Key-value pairs of properties and corresponding values; the returned statistics will only include messages where the property matches the provided value. Only the following properties are supported for filters: user_id , phone_id , direction , source , status , service_id , simulated , message_type , network_code
|
Return Typeobject Return Value Propertiesintervals |
array
List of objects representing each date interval containing at least one message matching the filters.
Each object has the following properties:
start_time | The UNIX timestamp of the start of the interval (int) |
end_time | The UNIX timestamp of the end of the interval, exclusive (int) |
start_date | The date of the start of the interval in YYYY-MM-DD format (string) |
end_date | The date of the end of the interval in YYYY-MM-DD format, inclusive (string) |
groups | Array of groups for each combination of requested property values matching the filters (array)
Each object has the following properties:
properties | An object of key/value pairs for each distinct value of the requested properties (object) |
metrics | An object of key/value pairs for each requested metric (object) |
|
|
| Exampleproject.getMessageStats({
start_date: "2022-01-01",
end_date: "2022-12-31",
rollup: "month",
properties: "phone_name,status,direction",
metrics: "count,num_parts,price",
currency: "USD",
filters: {'direction': "outgoing", 'source': "api"}
});
|
project.save()
Saves any fields or custom variables that have changed for the project.
ArgumentsNone Return Typeundefined | Exampleproject.name = "Example Project";
project.timezone_id = "America/Los_Angeles";
project.url_slug = "asdf";
project.auto_create_contacts = true;
project.vars.foo = "bar";
project.vars.baz = 42;
project.save();
|
Airtime Transactions | |
Object Type: AirtimeTransaction
Attributesid |
string ID of the airtime transaction
| read-only |
to_number |
string Destination phone number in international format (no leading +)
| read-only |
operator_name |
string | read-only |
country |
string | read-only |
time_created |
UNIX timestamp The time that the airtime transaction was created on Telerivet's servers
| read-only |
transaction_time |
UNIX timestamp The time that the airtime transaction was sent, or null if it has not been sent
| read-only |
status |
string Current status of airtime transaction (successful , failed , cancelled , queued , processing , submitted , pending_approval , or pending_payment )
| read-only |
status_text |
string Error or success message returned by airtime provider, if available
| read-only |
value |
string Value of airtime sent to destination phone number, in units of value_currency
| read-only |
value_currency |
string | read-only |
price |
string Price charged for airtime transaction, in units of price_currency
| read-only |
price_currency |
string | read-only |
contact_id |
string ID of the contact the airtime was sent to
| read-only |
service_id |
string ID of the service that sent the airtime
| read-only |
project_id |
string ID of the project that the airtime transaction belongs to
| read-only |
external_id |
string The ID of this transaction from an external airtime gateway provider, if available.
| read-only |
user_id |
string, max 34 characters ID of the Telerivet user who sent the airtime transaction (if applicable)
| read-only |
vars |
object Custom variables stored for this transaction. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| updatable |
|
Example[object AirtimeTransaction] JSON: {
"id": "ATb11111211217d11f",
"to_number": "639123123123",
"operator_name": "Globe Philippines",
"country": "PH",
"time_created": 1390347812,
"transaction_time": 1390347813,
"status": "successful",
"status_text": "Transaction successful",
"value": 25,
"value_currency": "PHP",
"price": 0.63,
"price_currency": "USD",
"contact_id": "CTa01111211217d24e",
"service_id": "SVb12345211217d35f",
"project_id": "PJ012345211217c11a",
"external_id": "GLYV2R8GHY8LS17Y0S0G",
"user_id": "URba3e403e98f49735",
"vars": {
"foo": "bar",
"baz": 42
}
} |
project.queryAirtimeTransactions(options)
Returns information about each airtime transaction.
ArgumentsOptionstime_created[min] | UNIX timestamp, optional Filter transactions created on or after a particular time
| time_created[max] | UNIX timestamp, optional Filter transactions created before a particular time
| contact_id | string, optional Filter transactions sent to a particular contact
| to_number | string, optional Filter transactions sent to a particular phone number
| service_id | string, optional Filter transactions sent by a particular service
| status | string, optional Filter transactions by status
Possible Values: pending, queued, processing, submitted, successful, failed, cancelled, pending_payment, pending_approval | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of AirtimeTransaction | Examplecursor = project.queryAirtimeTransactions();
cursor.limit(50);
while (cursor.hasNext()) {
var airtimetransaction = cursor.next();
// do something with airtimetransaction
}
|
project.getAirtimeTransactionById(id)
Gets an airtime transaction by ID
Argumentsid | string, required ID of the airtime transaction
|
Return TypeAirtimeTransaction | Examplevar airtimetransaction = project.getAirtimeTransactionById(airtimetransaction_id);
|
project.initAirtimeTransactionById(id)
Initializes an airtime transaction by ID without making an API request.
Argumentsid | string, required ID of the airtime transaction
|
Return TypeAirtimeTransaction | Examplevar airtimetransaction = project.initAirtimeTransactionById(airtimetransaction_id);
|
Organizations | |
organization.getMessageStats(options)
Retrieves statistics about messages sent or received via Telerivet. This endpoint returns historical data that is computed shortly after midnight each day in the project's time zone, and does not contain message statistics for the current day.
ArgumentsOptionsstart_date | string, required Start date of message statistics, in YYYY-MM-DD format
| end_date | string, required End date of message statistics (inclusive), in YYYY-MM-DD format
| rollup | string, optional Date interval to group by
Possible Values: day, week, month, year, all Default: day | properties | string, optional Comma separated list of properties to group by
Possible Values: org_id, org_name, org_industry, project_id, project_name, user_id, user_email, user_name, phone_id, phone_name, phone_type, direction, source, status, network_code, network_name, message_type, service_id, service_name, simulated, link | metrics | string, required Comma separated list of metrics to return (summed for each distinct value of the requested properties)
Possible Values: count, num_parts, duration, price | currency | string, optional Three-letter ISO 4217 currency code used when returning the 'price' field. If the original price was in a different currency, it will be converted to the requested currency using the approximate current exchange rate.
Default: USD | filters | object, optional Key-value pairs of properties and corresponding values; the returned statistics will only include messages where the property matches the provided value. Only the following properties are supported for filters: user_id , phone_id , direction , source , status , service_id , simulated , message_type , network_code
|
Return Typeobject Return Value Propertiesintervals |
array
List of objects representing each date interval containing at least one message matching the filters.
Each object has the following properties:
start_time | The UNIX timestamp of the start of the interval (int) |
end_time | The UNIX timestamp of the end of the interval, exclusive (int) |
start_date | The date of the start of the interval in YYYY-MM-DD format (string) |
end_date | The date of the end of the interval in YYYY-MM-DD format, inclusive (string) |
groups | Array of groups for each combination of requested property values matching the filters (array)
Each object has the following properties:
properties | An object of key/value pairs for each distinct value of the requested properties (object) |
metrics | An object of key/value pairs for each requested metric (object) |
|
|
| Examplevar organization = tr.initOrganizationById(organization_id);
organization.getMessageStats({
start_date: "2022-01-01",
end_date: "2022-12-31",
rollup: "month",
properties: "phone_name,status,direction",
metrics: "count,num_parts,price",
currency: "USD",
filters: {'direction': "outgoing", 'source': "api"}
});
|
Batch Tasks | |
Object Type: Task
Represents an asynchronous task that is applied to all entities matching a filter.
Tasks include services applied to contacts, messages, or data rows; adding or removing contacts from a group; blocking or unblocking sending messages to a contact;
updating a custom variable; deleting contacts, messages, or data rows; or exporting data to CSV.
Attributesid |
string, max 34 characters | read-only |
task_type |
string | read-only |
task_params |
object | read-only |
filter_type |
string Type of filter defining the rows that the task is applied to
| read-only |
filter_params |
object Parameters defining the rows that the task is applied to (specific to filter_type ). See project.createTask.
| read-only |
time_created |
UNIX timestamp Time the task was created in Telerivet
| read-only |
time_active |
UNIX timestamp Time Telerivet started executing the task
| read-only |
time_complete |
UNIX timestamp Time Telerivet finished executing the task
| read-only |
total_rows |
int The total number of rows matching the filter (null if not known)
| read-only |
current_row |
int The number of rows that have been processed so far
| read-only |
status |
string The current status of the task
Possible Values: created, queued, active, complete, failed, cancelled | read-only |
vars |
object Custom variables stored for this task. Variable names may be up to 32 characters in length and can contain the characters a-z, A-Z, 0-9, and _.
Values may be strings, numbers, or boolean (true/false).
String values may be up to 4096 bytes in length when encoded as UTF-8.
Up to 100 variables are supported per object.
Setting a variable to null will delete the variable.
| read-only |
table_id |
ID of the data table this task is applied to (if applicable)
| read-only |
user_id |
string, max 34 characters ID of the Telerivet user who created the task (if applicable)
| read-only |
project_id |
ID of the project this task belongs to
| read-only |
|
Example[object Task] JSON: {
"id": "DE1189812e59c5c781",
"task_type": "add_group_members",
"task_params": {
"group_id": "CG1123812e59c5c456"
},
"filter_type": "query_contacts",
"filter_params": {
"last_message_time": {
"min": 1615334071
}
},
"time_created": 1390348075,
"time_active": 1390348076,
"time_complete": null,
"total_rows": 12000,
"current_row": 3000,
"status": "active",
"vars": {
"foo": "bar",
"baz": 42
},
"table_id": null,
"user_id": "URba3e403e98f49735",
"project_id": "PJ2ad0100821a98bea"
} |
project.createTask(options)
Creates and starts an asynchronous task that is applied to all entities matching a filter (e.g. contacts, messages, or data rows).
Tasks are designed to efficiently process a large number of entities. When processing a large number of entities,
tasks are much faster than using the API to query and loop over all objects matching a filter.
Several different types of tasks are supported, including applying services to contacts, messages, or data rows;
adding or removing contacts from a group; blocking or unblocking sending messages to a contact; updating a custom variable;
deleting contacts, messages, or data rows; or exporting data to CSV.
When using a task to apply a Custom Actions or Cloud Script API service (apply_service_to_contacts , apply_service_to_rows , or apply_service_to_messages ),
the task variable will be available within the service. The service can use custom variables on the task object (e.g. task.vars.example ), such as
to store aggregate statistics for the rows matching the filter.
ArgumentsOptionstask_type | string, required Type of task to create. Each task_type applies to a certain type of entity (such as a contact, message, or data row).
Tasks for contacts:
- update_contact_var
- add_group_members
- remove_group_members
- set_conversation_status
- set_send_blocked
- apply_service_to_contacts
- delete_contacts
- export_contacts
Tasks for data rows:
- update_row_var
- apply_service_to_rows
- delete_rows
- export_rows
Tasks for messages:
- cancel_messages
- resend_messages
- retry_message_services
- apply_service_to_messages
- add_label
- remove_label
- update_message_var
- delete_messages
- export_messages
| task_params | object, optional Parameters applied to all matching rows (specific to task_type ).
apply_service_to_contacts, apply_service_to_messages, apply_service_to_rows:
service_id | The ID of the service to apply (string) |
variables | Optional object containing up to 25 temporary variable names and their corresponding values to set when invoking the service. Values may be strings, numbers, or boolean (true/false). String values may be up to 4096 bytes in length. Arrays and objects are not supported. Within Custom Actions, each variable can be used like [[$name]] (with a leading $ character and surrounded by double square brackets). Within a Cloud Script API service or JavaScript action, each variable will be available as a global JavaScript variable like $name (with a leading $ character). (object) |
update_contact_var, update_message_var, update_row_var:
variable | The custom variable name (string) |
value | The value to set (string, boolean, float, null) |
add_group_members, remove_group_members:
group_id | The ID of the group (string) |
add_label, remove_label:
label_id | The ID of the label (string) |
resend_messages:
route_id | ID of the new route to use, or null to use the original route (string) |
set_send_blocked:
send_blocked | true to block sending messages, false to unblock sending messages (boolean) |
set_conversation_status:
conversation_status | "active", "handled", or "closed" (string) |
export_contacts, export_messages, export_rows:
storage_id | ID of a storage provider where the CSV file will be saved. (string)
Currently only AWS S3 is supported as a storage provider.
This requires creating a S3 bucket in your own AWS account, as well as an IAM user with access key and secret that has permission to write to that bucket.
You can configure your own S3 bucket as a storage provider on the Storage Providers page.
Direct downloads are not supported when exporting data via the API.
(string) |
filename | Path within the storage backend where the CSV file will be saved |
column_ids | IDs of columns to save in the CSV file. If not provided, all default columns will be saved. (array of strings, optional) |
delete_contacts, delete_messages, delete_rows, cancel_messages, retry_message_services:
No parameters.
| filter_type | string, required Type of filter defining the rows that the task is applied to.
Each filter_type queries a certain type of entity (such as contacts, messages, or data rows).
In general, the task_type and the filter_type must return the same type of entity; however, tasks applied to contacts (other than export_contacts ) can also be applied
when the filter returns entities that are associated with a contact, such as messages or data rows. (Note that in this case, it is possible for the task to be applied multiple times to an individual contact if multiple messages or data rows are associated with the same contact.)
Possible Values: query_contacts, contact_ids, query_rows, row_ids, query_messages, message_ids | filter_params | object, required Parameters defining the rows that the task is applied to (specific to filter_type ).
query_contacts :
The same filter parameters as used by project.queryContacts. If you want to apply the task to all contacts, use the parameters {"all": true}.
contact_ids :
`contact_ids` | IDs of up to 100 contacts to apply this task to (array of strings) |
query_messages :
The same filter parameters as used by project.queryMessages. If you want to apply the task to all messages, use the parameters {"all": true}.
message_ids :
`message_ids` | IDs of up to 100 messages to apply this task to (array of strings) |
query_rows :
The same filter parameters as used by table.queryRows. If you want to apply the task to all rows in the table, use the parameters {"all": true}.
row_ids :
`row_ids` | IDs of up to 100 data rows to apply this task to (array of strings) |
| table_id | ID of the data table this task is applied to (if applicable).
Required if filter_type is query_rows or row_ids .
| vars | object, optional Initial custom variables to set for the task.
If the task applies a service, the service can read and write custom variables on the task object (e.g. task.vars.example ), such as
to store aggregate statistics for the rows matching the filter.
| on_complete | string, optional Name of a JavaScript function defined at the global scope of the calling Cloud Script service (or a subroutine if called from a Custom Actions service) which will be called when the task is complete.
When this function is called, the completed task will be available as the task variable (and also a parameter to the JavaScript function).
|
Return TypeTask | Examplevar task = project.createTask({
task_type: "add_group_members",
task_params: {'group_id': "CG1123812e59c5c456"},
filter_type: "query_contacts",
filter_params: {'last_message_time': {'min': 1615334071}}
});
|
task.cancel()
Cancels a task that is not yet complete.
ArgumentsNone Return TypeTask | Examplevar task = project.initTaskById(task_id);
var task = task.cancel();
|
project.queryTasks(options)
Queries batch tasks within the given project.
ArgumentsOptionssort | string, optional Sort the results based on a field
Possible Values: default Default: default | sort_dir | string, optional Sort the results in ascending or descending order
Possible Values: asc, desc Default: asc | page_size | int, optional Number of results returned per page (max 500)
Default: 50 | offset | int, optional Number of items to skip from beginning of result set
Default: 0 |
Return TypeAPICursor of Task | Examplecursor = project.queryTasks();
cursor.limit(50);
while (cursor.hasNext()) {
var task = cursor.next();
// do something with task
}
|
project.getTaskById(id)
Retrieves the task with the given ID.
ArgumentsReturn TypeTask | Examplevar task = project.getTaskById(task_id);
|
project.initTaskById(id)
Initializes the task with the given ID without making an API request.
ArgumentsReturn TypeTask | Examplevar task = project.initTaskById(task_id);
|
Rules Engine Variables
Some Cloud Script API functions and methods (such as sendReply with the replaceVariables parameter)
accept strings containing variable names in double square brackets, like "Hello [[contact.name]]!" .
Variable names in double square brackets refer to variables defined within the Rules Engine, which are not necessarily the same as
the variables available natively within the Cloud Script environment.
In addition, the replaceVariables function can be called anywhere within a service to evaluate Rules Engine variables in the current context.
The variables available within the Rules Engine vary depending on the context when the service is invoked (e.g. for a contact or a message):
When calling methods such as project.sendMessage or project.scheduleMessage with a replace_variables parameter,
variables in double square brackets are not evaluated in the context of the calling service. Instead, these variables refer to the
outgoing message and are evaluated at the time the message is sent (which may be later).
|
|
|
|