TutorialsREST APIWebhook API
Cloud Script API
Overview Creating/Running Scripts Examples Global Objects Storing Custom Data Filtering Queries Messages Contacts Broadcasts Projects Labels Groups Phones Data Tables Data Rows Scheduled Messages Services Contact/Service State Message Routes Mobile Money Receipts
Rules EngineIntegrations

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 uses JavaScript 1.6, enabling your scripts to use the entire 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.

A script is just a sequence of JavaScript statements. When your script is triggered, Telerivet executes the statements starting at the first line. Telerivet implicitly wraps your script in a function, so you can use return to end the script before the last line.

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 the Rules Engine.

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 provide source control, keep version history, reuse code across multiple projects, and share automated services with other Telerivet users.

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

btc
1 BTC = $498.3333

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.

Global Objects

Telerivet's script engine defines all of the standard built-in functions and objects defined the core JavaScript 1.6 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

The current contact

state
Context: Message or voice call

The current state for the current contact on this service

phone
Context: Message or voice call

The current phone

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

The current message

call
Context: Voice call

The current call

contact
Context: Contact

The current contact

state
Context: Contact

The current state for the current contact on this service

service

The current automated service

project

The current Telerivet project

$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.

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)

global

The JavaScript global object itself

Context: Message or voice call

sendReply(content)

Sends an SMS reply to the phone number that sent the incoming message. For more advanced options, see project.sendMessage.

Arguments

content
string, required

Content of the SMS reply

Return Type

undefined

Example

Context: Message or voice call

starMessage()

Adds a "star" to the current message.

Arguments

None

Return Type

undefined

Example

Context: 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 specifiedinterval. An optional timeout handler function can be registered to run at that time, for example to re-prompt the user and callwaitForResponse again.

Arguments

stateId
string, required

ID of the next state in the messaging flow (same as first argument to addResponseHandler)

options
object, optional

Options

timeoutDays
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 Type

undefined

Example

Context: Message

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.

Arguments

stateId
string, required

ID of the state in the messaging flow (same as argument to waitForResponse)

callback
function, required

Callback function with no arguments

Return Type

undefined

Example

Context: Message

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.

Arguments

timeoutId
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 Type

undefined

Example

Context: Voice call

sayText(text)

Says text in the current voice call using a built-in text-to-speech voice.

Arguments

text
string, required

The text to say

Return Type

undefined

Example

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.

Arguments

lang
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 Type

undefined

Example

Context: Voice call

playAudio(url)

Plays an audio file in the current voice call.

Arguments

url
string, required

The URL of the audio file (must start with http:// or https:// ). Audio files should be in mp3 format.

Return Type

undefined

Example

Context: Voice call

recordAudio(variableName)

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.

Arguments

variableName
string, required

Variable name on the call

Return Type

undefined

Example

Context: Voice call

promptKey(variableName)

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.

Arguments

variableName
string, required

Variable name on the call

Return Type

undefined

Example

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.

Arguments

variableName
string, required

Variable name on the call

options
object, optional

Options

submitOnHash
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

Return Type

undefined

Example

Context: Voice call

forwardCall(phoneNumber)

Forwards the call to another phone number.

Arguments

phoneNumber
string, required

The phone number to dial.

Return Type

undefined

Example

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 igits 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.

Arguments

variableName
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 Type

undefined

Example

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.

Arguments

eventName
string, required

Name of the event

Possible Values: call_complete
callback
function, required

Callback function with no arguments

Return Type

undefined

Example

Context: Voice call

hangUp()

Hangs up the current voice call.

Arguments

None

Return Type

undefined

Example

sendSMS(toNumber, content)

Sends an SMS message to a phone number (using the default route). For more advanced options, see project.sendMessage.

Arguments

toNumber
string, required

Phone number to send the message to

content
string, required

Content of the SMS message

Return Type

undefined

Example

sendGroupSMS(groupName, content)

Sends an SMS message to a group. For more advanced options, see project.sendMessages.

Arguments

groupName
string, required

Name of group to send the message to

content
string, required

Content of the SMS message

Return Type

undefined

Example

sendUSSD(mmiCode)

Sends a USSD request (using the default route). For more advanced options, see project.sendMessage.

Arguments

mmiCode
string, required

The MMI/USSD code to send, e.g. *102#. Always ends in '#' character.

Return Type

undefined

Example

sendEmail(emailAddress, subject, body)

Sends a plain-text email notification from Telerivet's servers. The 'From' address will appear as 'Telerivet User', and the 'Reply-To' address will be the account owner's email address.

Arguments

emailAddress
string, required

Email address to send the email to.

subject
string, required

Subject of the email

body
string, required

Body text of the email

Return Type

undefined

Example

stopRules()

Prevents Telerivet from executing any rules after this script within the same service.

Arguments

None

Return Type

undefined

Example

httpClient.request(url, options)

Fetches a external URL over HTTP or HTTPS, such as an API or a web page.

Arguments

url
string, required

The URL to request. Must use http:// or https:// protocol; custom port numbers are not allowed.

options
object, optional

Options

method
string, optional

The HTTP method to use

Possible Values: GET, POST, PUT, 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 or PUT 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

Return Type

object

Return Value Properties

status
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

Example

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 scriptengine 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.

Arguments

path
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

Example

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.

Arguments

str
string, required

The string to log

Return Type

undefined

Example

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.

Arguments

None

Return Type

undefined

Example

MessageOrIVRCallGlobal

Global Variables:

contact
Context: Message or voice call

The current contact

state
Context: Message or voice call

The current state for the current contact on this service

phone
Context: Message or voice call

The current phone

Context: Message or voice call

sendReply(content)

Sends an SMS reply to the phone number that sent the incoming message. For more advanced options, see project.sendMessage.

Arguments

content
string, required

Content of the SMS reply

Return Type

undefined

Example

Context: Message or voice call

starMessage()

Adds a "star" to the current message.

Arguments

None

Return Type

undefined

Example

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

The current message

Context: 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 specifiedinterval. An optional timeout handler function can be registered to run at that time, for example to re-prompt the user and callwaitForResponse again.

Arguments

stateId
string, required

ID of the next state in the messaging flow (same as first argument to addResponseHandler)

options
object, optional

Options

timeoutDays
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 Type

undefined

Example

Context: Message

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.

Arguments

stateId
string, required

ID of the state in the messaging flow (same as argument to waitForResponse)

callback
function, required

Callback function with no arguments

Return Type

undefined

Example

Context: Message

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.

Arguments

timeoutId
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 Type

undefined

Example

IVRCallGlobal

Global Variables:

call
Context: Voice call

The current call

Context: Voice call

sayText(text)

Says text in the current voice call using a built-in text-to-speech voice.

Arguments

text
string, required

The text to say

Return Type

undefined

Example

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.

Arguments

lang
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 Type

undefined

Example

Context: Voice call

playAudio(url)

Plays an audio file in the current voice call.

Arguments

url
string, required

The URL of the audio file (must start with http:// or https:// ). Audio files should be in mp3 format.

Return Type

undefined

Example

Context: Voice call

recordAudio(variableName)

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.

Arguments

variableName
string, required

Variable name on the call

Return Type

undefined

Example

Context: Voice call

promptKey(variableName)

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.

Arguments

variableName
string, required

Variable name on the call

Return Type

undefined

Example

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.

Arguments

variableName
string, required

Variable name on the call

options
object, optional

Options

submitOnHash
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

Return Type

undefined

Example

Context: Voice call

forwardCall(phoneNumber)

Forwards the call to another phone number.

Arguments

phoneNumber
string, required

The phone number to dial.

Return Type

undefined

Example

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 igits 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.

Arguments

variableName
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 Type

undefined

Example

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.

Arguments

eventName
string, required

Name of the event

Possible Values: call_complete
callback
function, required

Callback function with no arguments

Return Type

undefined

Example

Context: Voice call

hangUp()

Hangs up the current voice call.

Arguments

None

Return Type

undefined

Example

ContactGlobal

Global Variables:

contact
Context: Contact

The current contact

state
Context: Contact

The current state for the current contact on this service

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

$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.

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)

sendSMS(toNumber, content)

Sends an SMS message to a phone number (using the default route). For more advanced options, see project.sendMessage.

Arguments

toNumber
string, required

Phone number to send the message to

content
string, required

Content of the SMS message

Return Type

undefined

Example

sendGroupSMS(groupName, content)

Sends an SMS message to a group. For more advanced options, see project.sendMessages.

Arguments

groupName
string, required

Name of group to send the message to

content
string, required

Content of the SMS message

Return Type

undefined

Example

sendUSSD(mmiCode)

Sends a USSD request (using the default route). For more advanced options, see project.sendMessage.

Arguments

mmiCode
string, required

The MMI/USSD code to send, e.g. *102#. Always ends in '#' character.

Return Type

undefined

Example

sendEmail(emailAddress, subject, body)

Sends a plain-text email notification from Telerivet's servers. The 'From' address will appear as 'Telerivet User', and the 'Reply-To' address will be the account owner's email address.

Arguments

emailAddress
string, required

Email address to send the email to.

subject
string, required

Subject of the email

body
string, required

Body text of the email

Return Type

undefined

Example

stopRules()

Prevents Telerivet from executing any rules after this script within the same service.

Arguments

None

Return Type

undefined

Example

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.

Arguments

url
string, required

The URL to request. Must use http:// or https:// protocol; custom port numbers are not allowed.

options
object, optional

Options

method
string, optional

The HTTP method to use

Possible Values: GET, POST, PUT, 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 or PUT 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

Return Type

object

Return Value Properties

status
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

Example

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 scriptengine 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.

Arguments

path
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

Example

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.

Arguments

str
string, required

The string to log

Return Type

undefined

Example

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.

Arguments

None

Return Type

undefined

Example

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.

Arguments

None

Return Type

int

Example

cursor.hasNext()

Returns true if there are any more entities in the result set, false otherwise

Arguments

None

Return Type

bool

Example

cursor.next()

Returns the next entity in the result set.

Arguments

None

Return Type

Entity

Example

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.

Arguments

limit
int, required

The maximum number of entities to fetch from the server (may require multiple API calls if greater than 200)

Return Type

the current APICursor object

Example

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.

Arguments

None

Return Type

array

Example

DOMParser

Provides an API for parsing XML or HTML documents, such as responses from XML APIs or web pages. See https://developer.mozilla.org/en-US/docs/Web/API/DOMParser for additional details and examples.

var parser = new DOMParser()

Creates a new DOMParser

Arguments

None

Return Type

DOMParser

Example

parser.parseFromString(xmlSource, supportedType)

Arguments

xmlSource
string, required

String containing XML source

supportedType
string, required

Type of document

Possible Values: text/html, text/xml, application/xml

Return Type

DOMDocument

Example

XMLSerializer

Provides an API for constructing XML or HTML documents, such as requests to XML APIs. See https://developer.mozilla.org/en-US/docs/XMLSerializer for additional details and examples.

var serializer = new XMLSerializer()

Arguments

None

Return Type

XMLSerializer

Example

serializer.serializeToString(domDocument)

Arguments

domDocument
DOMDocument, required

DOM document to serialize

Return Type

string

Example

JSON

Utility functions for parsing/serializing JSON

JSON.stringify(obj)

Arguments

obj
string, required

Object to serialize as JSON

Return Type

string

Example

JSON.parse(str)

Arguments

str
string, required

JSON-encoded string to parse

Return Type

string

Example

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.

Arguments

phoneNumber
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 Type

string

Example

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.

Arguments

phoneNumber
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 Type

string

Example

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.

Arguments

phoneNumber
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 Type

string

Example

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.

Arguments

phoneNumber
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 Type

string

Example

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.

Arguments

phoneNumber
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 Type

string

Example

Base64

Utility functions for encoding/decoding from Base64

Base64.encode(str)

Encodes a string in Base64 (using the UTF-8 representation).

Arguments

str
string, required

String to encode in Base64

Return Type

string

Example

Base64.decode(base64str)

Decodes a Base64-encoded string (using the UTF-8 representation).

Arguments

base64str
string, required

Base64-encoded string to encode

Return Type

string

Example

_ (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. 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

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

prefixFilter objects where the field starts with the parameter value (case-insensitive). Only applicable for string fields.
not_prefixFilter objects where the field does not start with the parameter value (case-insensitive). Only applicable for string fields.
existsIf 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.
gteFilter 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.
gtFilter 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.
ltFilter 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.
lteFilter 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.
minFilter objects where the value is greater than or equal to the parameter value (inclusive), always performing a numeric comparison. Not applicable for string fields.
maxFilter objects where the value is less than the parameter value (non-inclusive), always performing a numeric comparison. Not applicable for string fields.
neFilter objects where the field does not match the parameter value exactly (case-insensitive).
eqFilter objects where the field matches the parameter value exactly (case-insensitive). This is the same as not using any modifier.

Example

Messages

Object Type: Message

Represents a single message.

Attributes

id
string, max 34 characters

ID of the message

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-only
message_type
string

Type of the message

Possible Values: sms, mms, ussd, call
read-only
source
string

How the message originated within Telerivet

Possible Values: phone, provider, web, api, service, webhook, scheduled
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
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 Label

List of IDs of labels applied to this message

read-only
vars
object

Custom variables stored for this message

updatable
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
external_id
string

The ID of this message from an external SMS gateway provider (e.g. Twilio or Nexmo), if available.

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
mms_parts
array

A list of parts in the MMS message, the same as returned by the getMMSParts method. Note: This property is only present when retrieving an individual MMS message by ID, not when querying a list of messages. In other cases, use getMMSParts.

read-only
service_id
string ID of Service

ID of the service that handled the message (for voice calls, the service defines the call flow)

read-only
phone_id
string ID of Phone

ID of the phone that sent or received the message

read-only
contact_id
string ID of Contact

ID of the contact that sent or received the message

read-only
route_id
string ID of Route

ID of the route that sent the message (if applicable)

read-only
broadcast_id
string ID of Broadcast

ID of the broadcast that 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
string ID of Project

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,"from_number":"+16505550001","to_number":"+16505550123","content":"Thank you for registering!","starred":true,"simulated":false,"label_ids":["LB4f3dac27154653e0"],"vars":{"foo":"bar","baz":42},"external_id":"142092393","price":0.01,"price_currency":"USD","duration":null,"ring_time":null,"audio_url":null,"tts_lang":null,"tts_voice":null,"mms_parts":null,"service_id":"SV3d246818d0e3d1fb","phone_id":"PN4d246818d0ecd1fa","contact_id":"CTa1299c3d0e371023","route_id":"RT2a586298d3412adf","broadcast_id":"MB98918598dab29800","user_id":"URba3e403e98f49735","project_id":"PJ2ad0100821a98bea","url":"https://telerivet.com/p/asdf/message/SM1629708e59c5c781"}

message.hasLabel(label)

Returns true if this message has a particular label, false otherwise.

Arguments

label
Label, required

Return Type

bool

Example

message.addLabel(label)

Adds a label to the given message.

Arguments

label
Label, required

Return Type

undefined

Example

message.removeLabel(label)

Removes a label from the given message.

Arguments

label
Label, required

Return Type

undefined

Example

message.getMMSParts()

Retrieves a list of MMS parts for this message (empty for non-MMS messages). 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)

Arguments

None

Return Type

array

Example

message.save()

Saves any fields that have changed for this message.

Arguments

None

Return Type

undefined

Example

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.

Arguments

options
object, optional

Options

route_id
string, optional

ID of the phone or route to send the message from

Return Type

Message

Example

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'.

Arguments

None

Return Type

Message

Example

message.delete()

Deletes this message.

Arguments

None

Return Type

undefined

Example

project.sendMessage(options)

Sends one message (SMS, voice call, or USSD request).

Arguments

options
object, required

Options

message_type
string, optional

Type of message to send

Possible Values: sms, ussd, call
Default: sms
content
string, required if sending SMS message

Content of the message to send (if message_type=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 phone ID for your project
service_id
string ID of Service, optional

Service that defines the call flow of the voice call (when message_type=call)

audio_url
string, optional

The URL of an MP3 file to play when the contact answers the call (when messagetype=call). If audiourl 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=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
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

is_template
bool, optional

Set to true to evaluate variables like [[contact.name]] in message content. (See available variables)

Default: false
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 (currently only observed for Android phones). 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).

Default: 1
user_id
string, optional

ID of the Telerivet user account that sent the message (use project.getUsers to look up user IDs). In order to use this parameter, the user account associated with the API key must have administrator permissions for the project, and the user account associated with the user_id parameter must have access to the project.

Default: User account associated with the API key

Return Type

Message

Example

project.sendMessages(options)

Sends an SMS message (optionally with mail-merge templates) or voice call to a group or a list of up to 500 phone numbers

Arguments

options
object, required

Options

message_type
string, optional

Type of message to send

Possible Values: sms, call
Default: sms
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 phone ID
service_id
string ID of Service, optional

Service that defines the call flow of the voice call (when message_type=call)

audio_url
string, optional

The URL of an MP3 file to play when the contact answers the call (when messagetype=call). If audiourl 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=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
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)

exclude_contact_id
string, optional

Optionally excludes one contact from receiving the message (only when group_id is set)

is_template
bool, optional

Set to true to evaluate variables like [[contact.name]] in message content (See available variables)

Default: false
vars
object, optional

Custom variables to set for each message

Return Type

object

Return Value Properties

count_queued
int

Number of messages queued to send

broadcast_id
string

ID of broadcast created for this message batch. If count_queued is 0 or 1, a broadcast will not be created, and the broadcast_id property will be null.

Example

project.queryMessages(options)

Queries messages within the given project.

Arguments

options
object, optional

Options

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, call
source
string, optional

Filter messages by source

Possible Values: phone, provider, web, api, service, webhook, scheduled
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
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

contact_id
string, optional

ID of the contact who sent/received the message

phone_id
string, optional

ID of the phone that sent/received the message

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Message

Example

project.getMessageById(id)

Retrieves the message with the given ID.

Arguments

id
string, required

ID of the message

Return Type

Message

Example

project.initMessageById(id)

Initializes the Telerivet message with the given ID without making an API request.

Arguments

id
string, required

ID of the message

Return Type

Message

Example

Contacts

Object Type: Contact

Attributes

id
string, max 34 characters

ID of the contact

read-only
name
string

Name of the contact

updatable
phone_number
string

Phone number of the contact

updatable
time_created
UNIX timestamp

Time the contact was added in Telerivet

read-only
send_blocked
bool

True if Telerivet is blocked from sending messages to this contact

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
string ID of Message

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
string ID of Phone

ID of the phone or 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

updatable
project_id
string ID of Project

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,"send_blocked":false,"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"}

contact.queryMessages(options)

Queries messages sent or received by this contact.

Arguments

options
object, optional

Options

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, call
source
string, optional

Filter messages by source

Possible Values: phone, provider, web, api, service, webhook, scheduled
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
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

contact_id
string, optional

ID of the contact who sent/received the message

phone_id
string, optional

ID of the phone that sent/received the message

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Message

Example

contact.queryGroups(options)

Queries groups for which this contact is a member.

Arguments

options
object, optional

Options

name
string, optional

Filter groups by name

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Group

Example

contact.queryScheduledMessages(options)

Queries messages scheduled to this contact (not including messages scheduled to groups that this contact is a member of)

Arguments

options
object, optional

Options

message_type
string, optional

Filter scheduled messages by message_type

Possible Values: sms, mms, ussd, call
time_created
UNIX timestamp, optional

Filter scheduled messages by time_created

Allowed Modifiers: time_created[ne], time_created[min], time_created[max] (?)
next_time
UNIX timestamp, optional

Filter scheduled messages by next_time

Allowed Modifiers: next_time[exists], next_time[ne], next_time[min], next_time[max] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of ScheduledMessage

Example

contact.queryDataRows(options)

Queries data rows associated with this contact (in any data table).

Arguments

options
object, optional

Options

time_created
UNIX timestamp, optional

Filter data rows by the time they were created

Allowed Modifiers: time_created[ne], 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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of DataRow

Example

contact.queryServiceStates(options)

Queries this contact's current states for any service

Arguments

options
object, optional

Options

id
string, optional

Filter states by id

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][exists], 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of ContactServiceState

Example

contact.isInGroup(group)

Returns true if this contact is in a particular group, false otherwise.

Arguments

group
Group, required

Return Type

bool

Example

contact.addToGroup(group)

Adds this contact to a group.

Arguments

group
Group, required

Return Type

undefined

Example

contact.removeFromGroup(group)

Removes this contact from a group.

Arguments

group
Group, required

Return Type

undefined

Example

contact.save()

Saves any fields or custom variables that have changed for this contact.

Arguments

None

Return Type

undefined

Example

contact.delete()

Deletes this contact.

Arguments

None

Return Type

undefined

Example

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 lookupkey 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, phonenumber, vars, default_route_id, send_blocked, add_group_ids, remove_group_ids).

Arguments

options
object, optional

Options

name
string, optional

Name of the contact

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
string ID of Contact, optional

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

Return Type

Contact

Example

project.queryContacts(options)

Queries contacts within the given project.

Arguments

options
object, optional

Options

name
string, optional

Filter contacts by name

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] (?)
time_created
UNIX timestamp, optional

Filter contacts by time created

Allowed Modifiers: time_created[ne], 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[exists], last_message_time[ne], last_message_time[min], last_message_time[max] (?)
last_incoming_message_time
UNIX timestamp, optional

Filter contacts by last time a message was received

Allowed Modifiers: last_incoming_message_time[exists], last_incoming_message_time[ne], last_incoming_message_time[min], last_incoming_message_time[max] (?)
last_outgoing_message_time
UNIX timestamp, optional

Filter contacts by last time a message was sent

Allowed Modifiers: last_outgoing_message_time[exists], last_outgoing_message_time[ne], last_outgoing_message_time[min], last_outgoing_message_time[max] (?)
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][exists], 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Contact

Example

project.getContactById(id)

Retrieves the contact with the given ID.

Arguments

id
string, required

ID of the contact

Return Type

Contact

Example

project.initContactById(id)

Initializes the Telerivet contact with the given ID without making an API request.

Arguments

id
string, required

ID of the contact

Return Type

Contact

Example

Broadcasts

Object Type: Broadcast

Attributes

id
string, max 34 characters

ID of the broadcast

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
recipients_str
string

A string with 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, call
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
is_template
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
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
label_ids
array of string IDs of Label

List of IDs of labels applied to all messages in the broadcast

read-only
vars
object

Custom variables stored for this message

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
user_id
string, max 34 characters

ID of the Telerivet user who sent the broadcast (if applicable)

read-only
project_id
string ID of Project

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"}}}],"recipients_str":"+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,"is_template":true,"status":"queuing","source":"service","simulated":false,"label_ids":["LB4f3dac27154653e0"],"vars":{"foo":"bar","baz":42},"price":13.34,"price_currency":"USD","reply_count":43,"last_reply_time":1390348132,"route_id":"RT2a586298d3412adf","user_id":"URba3e403e98f49735","project_id":"PJ2ad0100821a98bea"}

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).

Arguments

None

Return Type

Broadcast

Example

project.queryBroadcasts(options)

Queries broadcasts within the given project.

Arguments

options
object, optional

Options

time_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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Broadcast

Example

project.getBroadcastById(id)

Retrieves the broadcast with the given ID.

Arguments

id
string, required

ID of the broadcast

Return Type

Broadcast

Example

project.initBroadcastById(id)

Initializes the Telerivet broadcast with the given ID without making an API request.

Arguments

id
string, required

ID of the broadcast

Return Type

Broadcast

Example

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.

Attributes

id
string, max 34 characters

ID of the project

read-only
name
string

Name of the project

updatable
timezone_id
string
read-only
url_slug
string

Unique string used as a component of the project's URL in the Telerivet web app

read-only
vars
object

Custom variables stored for this project

updatable
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","vars":{"foo":"bar","baz":42},"url":"https://telerivet.com/p/asdf"}

project.initRouteById(id)

Initializes a custom route by ID without making an API request.

Arguments

id
string, required

ID of the route

Return Type

Route

Example

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.)

Arguments

None

Return Type

array

Example

project.save()

Saves any fields or custom variables that have changed for the project.

Arguments

None

Return Type

undefined

Example

See also:

Labels

Object Type: Label

Represents a label used to organize messages within Telerivet.

Attributes

id
string, max 34 characters

ID of the label

read-only
name
string

Name of the label

updatable
time_created
UNIX timestamp

Time the label was created in Telerivet

read-only
vars
object

Custom variables stored for this label

updatable
project_id
string ID of Project

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.

Arguments

options
object, optional

Options

name
string, optional

Filter labels 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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Label

Example

project.getOrCreateLabel(name)

Gets or creates a label by name.

Arguments

name
string, required

Name of the label

Return Type

Label

Example

project.getLabelById(id)

Retrieves the label with the given ID.

Arguments

id
string, required

ID of the label

Return Type

Label

Example

project.initLabelById(id)

Initializes the label with the given ID without making an API request.

Arguments

id
string, required

ID of the label

Return Type

Label

Example

label.queryMessages(options)

Queries messages with the given label.

Arguments

options
object, optional

Options

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, call
source
string, optional

Filter messages by source

Possible Values: phone, provider, web, api, service, webhook, scheduled
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
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

contact_id
string, optional

ID of the contact who sent/received the message

phone_id
string, optional

ID of the phone that sent/received the message

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Message

Example

label.save()

Saves any fields that have changed for the label.

Arguments

None

Return Type

undefined

Example

label.delete()

Deletes the given label (Note: no messages are deleted.)

Arguments

None

Return Type

undefined

Example

Groups

Object Type: Group

Represents a group used to organize contacts within Telerivet.

Attributes

id
string, max 34 characters

ID of the group

read-only
name
string

Name of the group

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
vars
object

Custom variables stored for this group

updatable
project_id
string ID of Project

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,"vars":{"foo":"bar","baz":42},"project_id":"PJ2ad0100821a98bea"}

project.queryGroups(options)

Queries groups within the given project.

Arguments

options
object, optional

Options

name
string, optional

Filter groups by name

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Group

Example

project.getOrCreateGroup(name)

Retrieves or creates a group by name.

Arguments

name
string, required

Name of the group

Return Type

Group

Example

project.getGroupById(id)

Retrieves the group with the given ID.

Arguments

id
string, required

ID of the group

Return Type

Group

Example

project.initGroupById(id)

Initializes the group with the given ID without making an API request.

Arguments

id
string, required

ID of the group

Return Type

Group

Example

group.queryContacts(options)

Queries contacts that are members of the given group.

Arguments

options
object, optional

Options

name
string, optional

Filter contacts by name

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] (?)
time_created
UNIX timestamp, optional

Filter contacts by time created

Allowed Modifiers: time_created[ne], 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[exists], last_message_time[ne], last_message_time[min], last_message_time[max] (?)
last_incoming_message_time
UNIX timestamp, optional

Filter contacts by last time a message was received

Allowed Modifiers: last_incoming_message_time[exists], last_incoming_message_time[ne], last_incoming_message_time[min], last_incoming_message_time[max] (?)
last_outgoing_message_time
UNIX timestamp, optional

Filter contacts by last time a message was sent

Allowed Modifiers: last_outgoing_message_time[exists], last_outgoing_message_time[ne], last_outgoing_message_time[min], last_outgoing_message_time[max] (?)
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][exists], 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Contact

Example

group.queryScheduledMessages(options)

Queries scheduled messages to the given group.

Arguments

options
object, optional

Options

message_type
string, optional

Filter scheduled messages by message_type

Possible Values: sms, mms, ussd, call
time_created
UNIX timestamp, optional

Filter scheduled messages by time_created

Allowed Modifiers: time_created[ne], time_created[min], time_created[max] (?)
next_time
UNIX timestamp, optional

Filter scheduled messages by next_time

Allowed Modifiers: next_time[exists], next_time[ne], next_time[min], next_time[max] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of ScheduledMessage

Example

group.save()

Saves any fields that have changed for this group.

Arguments

None

Return Type

undefined

Example

group.delete()

Deletes this group (Note: no contacts are deleted.)

Arguments

None

Return Type

undefined

Example

Phones

Object Type: Phone

Represents a phone or gateway that you use to send/receive messages via Telerivet.

Attributes

id
string, max 34 characters

ID of the phone

read-only
name
string

Name of the phone

updatable
phone_number
string

Phone number of the phone

updatable
phone_type
string

Type of this phone/gateway (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

updatable
project_id
string ID of Project

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 http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels (only present for Android phones)

read-only
mccmnc
string

Code indicating the Android phone's current country (MCC) and mobile network operator (MNC); see http://en.wikipedia.org/wiki/Mobile_country_code (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"}

project.queryPhones(options)

Queries phones within the given project.

Arguments

options
object, optional

Options

name
string, optional

Filter phones by name

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[exists], last_active_time[ne], last_active_time[min], last_active_time[max] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Phone

Example

project.getPhoneById(id)

Retrieves the phone with the given ID.

Arguments

id
string, required

Return Type

Phone

Example

project.initPhoneById(id)

Initializes the phone with the given ID without making an API request.

Arguments

id
string, required

Return Type

Phone

Example

phone.queryMessages(options)

Queries messages sent or received by this phone.

Arguments

options
object, optional

Options

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, call
source
string, optional

Filter messages by source

Possible Values: phone, provider, web, api, service, webhook, scheduled
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
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

contact_id
string, optional

ID of the contact who sent/received the message

phone_id
string, optional

ID of the phone that sent/received the message

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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Message

Example

phone.save()

Saves any fields or custom variables that have changed for this phone.

Arguments

None

Return Type

undefined

Example

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.

Attributes

id
string, max 34 characters

ID of the data table

read-only
name
string

Name of the data table

updatable
num_rows
int

Number of rows in the table

read-only
vars
object

Custom variables stored for this data table

updatable
project_id
string ID of Project

ID of the project this data table belongs to

read-only

Example

[object DataTable] JSON: {"id":"DTf9f77c9ba69cce50","name":"Poll Responses","num_rows":1032,"vars":{"foo":"bar","baz":42},"project_id":"PJ2ad0100821a98bea"}

project.queryDataTables(options)

Queries data tables within the given project.

Arguments

options
object, optional

Options

name
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of DataTable

Example

project.getOrCreateDataTable(name)

Gets or creates a data table by name.

Arguments

name
string, required

Name of the data table

Return Type

DataTable

Example

project.getDataTableById(id)

Retrieves the data table with the given ID.

Arguments

id
string, required

ID of the data table

Return Type

DataTable

Example

project.initDataTableById(id)

Initializes the data table with the given ID without making an API request.

Arguments

id
string, required

ID of the data table

Return Type

DataTable

Example

table.initRowById(id)

Initializes the row in the given table with the given ID, without making an API request.

Arguments

id
string, required

ID of the row

Return Type

DataRow

Example

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' and 'variable'. (Fields are automatically created any time a DataRow's 'vars' property is updated.)

Arguments

None

Return Type

array

Example

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}

Arguments

variable
string, required

Variable of field to count by.

Return Type

object

Example

table.save()

Saves any fields that have changed for this data table.

Arguments

None

Return Type

undefined

Example

table.delete()

Permanently deletes the given data table, including all its rows

Arguments

None

Return Type

undefined

Example

See also:

Data Rows

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.

Attributes

id
string, max 34 characters

ID of the data row

read-only
contact_id
string ID of Contact

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

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
string ID of DataTable

ID of the table this data row belongs to

read-only
project_id
string ID of Project

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"}

table.queryRows(options)

Queries rows in this data table.

Arguments

options
object, optional

Options

time_created
UNIX timestamp, optional

Filter data rows by the time they were created

Allowed Modifiers: time_created[ne], time_created[min], time_created[max] (?)
contact_id
string ID of Contact, optional

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][exists], 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of DataRow

Example

table.createRow(options)

Adds a new row to this data table.

Arguments

options
object, optional

Options

contact_id
string ID of Contact, optional

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

Return Type

DataRow

Example

table.getRowById(id)

Retrieves the row in the given table with the given ID.

Arguments

id
string, required

ID of the row

Return Type

DataRow

Example

row.save()

Saves any fields or custom variables that have changed for this data row.

Arguments

None

Return Type

undefined

Example

row.delete()

Deletes this data row.

Arguments

None

Return Type

undefined

Example

Scheduled Messages

Object Type: ScheduledMessage

Represents a scheduled message within Telerivet.

Attributes

id
string, max 34 characters

ID of the scheduled message

read-only
content
string

Text content of the scheduled message

read-only
rrule
string

Recurrence rule for recurring scheduled messages, e.g. 'FREQ=MONTHLY' or 'FREQ=WEEKLY;INTERVAL=2'; see https://tools.ietf.org/html/rfc2445#section-4.3.10

read-only
timezone_id
string

Timezone ID used to compute times for recurring messages; see http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

read-only
group_id
string ID of Group

ID of the group to send the message to (null if scheduled to an individual contact)

read-only
contact_id
string ID of Contact

ID of the contact to send the message to (null if scheduled to a group)

read-only
to_number
string

Phone number to send the message to (null if scheduled to a group)

read-only
route_id
string

ID of the phone or route the message will be sent from

read-only
service_id
string ID of Service

The service associated with this message (for voice calls, the service defines the call flow)

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
message_type
string

Type of scheduled message

Possible Values: sms, ussd, call
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)

read-only
end_time
UNIX timestamp

Time after which a recurring message will stop (not applicable to non-recurring scheduled messages)

read-only
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
is_template
bool

Set to true if Telerivet will render variables like [[contact.name]] in the message content, false otherwise

read-only
vars
object

Custom variables stored for this scheduled message (copied to Message when sent)

updatable
label_ids
array of string IDs of Label

IDs of labels to add to the Message

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","group_id":null,"contact_id":"CTa1299c3d0e371023","to_number":"+16505550123","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,"is_template":false,"vars":{"foo":"bar","baz":42},"label_ids":["LB4f3dac27154653e0"],"project_id":"PJ2ad0100821a98bea"}

project.scheduleMessage(options)

Schedules an SMS message to a group or single contact. Note that Telerivet only sends scheduled messages approximately once per minute, so it is not possible to control the exact second at which a scheduled message is sent.

Arguments

options
object, required

Options

message_type
string, optional

Type of message to send

Possible Values: sms, ussd
Default: sms
content
string, required if sending SMS message

Content of the message to schedule

group_id
string ID of Group, required if to_number not set

ID of the group to send the message to

to_number
string, required if group_id not set

Phone number 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

A recurrence rule describing the how the schedule repeats, e.g. 'FREQ=MONTHLY' or 'FREQ=WEEKLY;INTERVAL=2'; see https://tools.ietf.org/html/rfc2445#section-4.3.10. (UNTIL is ignored; use end_time parameter instead).

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 phone ID
service_id
string ID of Service, optional

Service that defines the call flow of the voice call (when message_type=call)

audio_url
string, optional

The URL of an MP3 file to play when the contact answers the call (when messagetype=call). If audiourl 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=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
is_template
bool, optional

Set to true to evaluate variables like [[contact.name]] in message content

Default: false
label_ids
array of string IDs of Label, optional

Array of IDs of labels to add to the sent messages (maximum 5)

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

Return Type

ScheduledMessage

Example

project.queryScheduledMessages(options)

Queries scheduled messages within the given project.

Arguments

options
object, optional

Options

message_type
string, optional

Filter scheduled messages by message_type

Possible Values: sms, mms, ussd, call
time_created
UNIX timestamp, optional

Filter scheduled messages by time_created

Allowed Modifiers: time_created[ne], time_created[min], time_created[max] (?)
next_time
UNIX timestamp, optional

Filter scheduled messages by next_time

Allowed Modifiers: next_time[exists], next_time[ne], next_time[min], next_time[max] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of ScheduledMessage

Example

project.getScheduledMessageById(id)

Retrieves the scheduled message with the given ID.

Arguments

id
string, required

ID of the scheduled message

Return Type

ScheduledMessage

Example

project.initScheduledMessageById(id)

Initializes the scheduled message with the given ID without making an API request.

Arguments

id
string, required

ID of the scheduled message

Return Type

ScheduledMessage

Example

scheduled_msg.save()

Saves any fields or custom variables that have changed for this scheduled message.

Arguments

None

Return Type

undefined

Example

scheduled_msg.delete()

Cancels this scheduled message.

Arguments

None

Return Type

undefined

Example

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.

Attributes

id
string, max 34 characters

ID of the service

read-only
name
string

Name of the service

updatable
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

updatable
project_id
string ID of Project

ID of the project this service belongs to

read-only
label_id
string ID of Label

ID of the label containing messages sent or received by this service (currently only used for polls)

read-only
response_table_id
string ID of DataTable

ID of the data table where responses to this service will be stored (currently only used for polls)

read-only
sample_group_id
string ID of Group

ID of the group containing contacts that have been invited to interact with this service (currently only used for polls)

read-only
respondent_group_id
string ID of Group

ID of the group containing contacts that have completed an interaction with this service (currently only used for polls)

read-only
questions
array

Array of objects describing each question in a poll (only used for polls). Each object has the properties "id" (the question ID), "content" (the text of the question), and "questiontype" (either "multiplechoice", "missed_call", or "open").

read-only

Example

[object Service] JSON: {"id":"SVee45c8ae4e32889a","name":"Poll Service","active":true,"priority":1,"contexts":{"message":{"incoming_message":true},"contact":{"default":true}},"vars":{"foo":"bar","baz":42},"project_id":"PJ2ad0100821a98bea","label_id":"LB13d74c470068e8f0","response_table_id":"DTf9fe14d9c306aed9","sample_group_id":"CGed40999e54fe2f41","respondent_group_id":"CGaf6b9608bc67f1eb","questions":[{"id":"q1","content":"What is your answer to the first question?","question_type":"multiple_choice"},{"id":"q2","content":"What do you think about the second question?","question_type":"open"}]}

project.queryServices(options)

Queries services within the given project.

Arguments

options
object, optional

Options

name
string, optional

Filter services by name

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, 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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Service

Example

project.getServiceById(id)

Retrieves the service with the given ID.

Arguments

id
string, required

ID of the service

Return Type

Service

Example

project.initServiceById(id)

Initializes the service with the given ID without making an API request.

Arguments

id
string, required

ID of the service

Return Type

Service

Example

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 contactid as the ID of the contact to send the poll to. Or, to manually apply a service for an incoming message, you can invoke the service with context=message, event=incoming_message, and messageid 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.)

Arguments

options
object, required

Options

context
string, required

The name of the context in which this service is invoked

Possible Values: message, call, 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
string ID of Contact, required if context is 'contact'

The ID of the contact this service is triggered for

Return Type

object

Example

service.save()

Saves any fields or custom variables that have changed for this service.

Arguments

None

Return Type

undefined

Example

See also:

Contact/Service State

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.

Attributes

id
string, max 63 characters

Arbitrary string representing the contact's current state for this service, e.g. 'q1', 'q2', etc.

updatable
contact_id
string ID of Contact

ID of the contact

read-only
service_id
string ID of Service

ID of the service

read-only
vars
object

Custom variables stored for this contact/service state

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
string ID of Project

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.queryContactStates(options)

Query the current states of contacts for this service.

Arguments

options
object, optional

Options

id
string, optional

Filter states by id

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][exists], 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of ContactServiceState

Example

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.

Arguments

contact
Contact, required

The contact whose state you want to retrieve.

Return Type

ContactServiceState

Example

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.

Arguments

contact
Contact, required

The contact whose state you want to update.

options
object, required

Options

id
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

Return Type

ContactServiceState

Example

service.resetContactState(contact)

Resets the current state for a particular contact for the given service.

Arguments

contact
Contact, required

The contact whose state you want to reset.

Return Type

ContactServiceState

Example

Message Routes

Object Type: Route

Represents a custom route that can be used to send messages via one or more Phones. Note: Routing rules can currently only be configured via Telerivet's web UI.

Attributes

id
string, max 34 characters

Telerivet's internal ID for the route

read-only
name
string

The name of the route

updatable
vars
object

Custom variables stored for this route

updatable
project_id
string ID of Project

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.queryRoutes(options)

Queries custom routes that can be used to send messages (not including Phones).

Arguments

options
object, optional

Options

name
string, optional

Filter routes 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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of Route

Example

project.getRouteById(id)

Gets a custom route by ID

Arguments

id
string, required

ID of the route

Return Type

Route

Example

route.save()

Saves any fields or custom variables that have changed for this route.

Arguments

None

Return Type

undefined

Example

Mobile Money Receipts

Object Type: MobileMoneyReceipt

Represents a receipt received from a mobile money system such as Safaricom M-Pesa (Kenya), Vodacom M-Pesa (Tanzania), or Tigo Pesa (Tanzania). When your Android phone receives a SMS receipt from a supported mobile money service that Telerivet can understand, Telerivet will automatically parse it and create a MobileMoneyReceipt object.

Attributes

id
string, max 34 characters

Telerivet's internal ID for the receipt

read-only
tx_id
string

Transaction ID from the receipt

read-only
tx_type
string

Type of mobile money transaction

Possible Values: receive_money, send_money, pay_bill, deposit, withdrawal, airtime_purchase, balance_inquiry, reversal
read-only
currency
string

ISO 4217 Currency code for the transaction, e.g. KES or TZS. Amount, balance, and fee are expressed in units of this currency.

read-only
amount
number

Amount of this transaction; positive numbers indicate money added to your account, negative numbers indicate money removed from your account

read-only
balance
number

The current balance of your mobile money account (null if not available)

read-only
fee
number

The transaction fee charged by the mobile money system (null if not available)

read-only
name
string

The name of the other person in the transaction (null if not available)

read-only
phone_number
string

The phone number of the other person in the transaction (null if not available)

read-only
time_created
UNIX timestamp

The time this receipt was created in Telerivet

read-only
other_tx_id
string

The other transaction ID listed in the receipt (e.g. the transaction ID for a reversed transaction)

read-only
content
string

The raw content of the mobile money receipt

read-only
provider_id
string

Telerivet's internal ID for the mobile money provider

read-only
vars
object

Custom variables stored for this mobile money receipt

updatable
contact_id
string ID of Contact

ID of the contact associated with the name/phone number on the receipt. Note that some mobile money systems do not provide the other person's phone number, so it's possible Telerivet may not automatically assign a contact_id, or may assign it to a different contact with the same name.

updatable
phone_id
string ID of Phone

ID of the phone that received the receipt

read-only
message_id
string ID of Message

ID of the message corresponding to the receipt

read-only
project_id
string ID of Project

ID of the project this receipt belongs to

read-only

Example

[object MobileMoneyReceipt] JSON: {"id":"MRed8af84c2679ac08","tx_id":"PP140318.0329.F3210","tx_type":"receive_money","currency":"TZS","amount":75000,"balance":132000,"fee":null,"name":"JACK JACKSON","phone_number":"0650001234","time_created":1395102559,"other_tx_id":null,"content":"Umepokea Tsh 75,000 kutoka kwa JACK JACKSON, 0650001234. 18/03/2014 03:29 AM, Salio jipya 132,000, kumbukumbu no. PP140318.0329.F3210. Tuma Tsh 2000 kwa gharama ya Tsh 30 TU.Smile You are With Tigo.","provider_id":"tigopesa_tz","vars":{"foo":"bar","baz":42},"contact_id":"CT0c20f3118cc119a0","phone_id":"PN4d246818d0ecd1fa","message_id":"SMd8c822587310c069","project_id":"PJ2ad0100821a98bea"}

project.queryReceipts(options)

Queries mobile money receipts within the given project.

Arguments

options
object, optional

Options

tx_id
string, optional

Filter receipts by transaction ID

tx_type
string, optional

Filter receipts by transaction type

Possible Values: receive_money, send_money, pay_bill, deposit, withdrawal, airtime_purchase, balance_inquiry, reversal
tx_time
UNIX timestamp, optional

Filter receipts by transaction time

Allowed Modifiers: tx_time[ne], tx_time[min], tx_time[max] (?)
name
string, optional

Filter receipts by other person's name

Allowed Modifiers: name[ne], name[prefix], name[not_prefix], name[gte], name[gt], name[lt], name[lte] (?)
phone_number
string, optional

Filter receipts by other person's 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] (?)
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 200)

Default: 50
offset
int, optional

Number of items to skip from beginning of result set

Default: 0

Return Type

APICursor of MobileMoneyReceipt

Example

project.getReceiptById(id)

Retrieves the mobile money receipt with the given ID.

Arguments

id
string, required

ID of the mobile money receipt

Return Type

MobileMoneyReceipt

Example

project.initReceiptById(id)

Initializes the mobile money receipt with the given ID without making an API request.

Arguments

id
string, required

ID of the mobile money receipt

Return Type

MobileMoneyReceipt

Example

receipt.save()

Saves any fields or custom variables that have changed for this mobile money receipt.

Arguments

None

Return Type

undefined

Example

receipt.delete()

Deletes this receipt.

Arguments

None

Return Type

undefined

Example