id: cloud_script_api source: api_docs title: Cloud Script API TypeScript reference url: /api/script // Telerivet Cloud Script API TypeScript Declarations // Documentation: https://telerivet.com/api/script // // The Cloud Script API is a synchronous JavaScript API for working with a // Telerivet project (messages, contacts, groups, data tables, services, // routes, and more). The API is available in three execution contexts: // // 1. STANDALONE CODE - JavaScript passed to the run_script / // run_analysis_script tools (MCP / AI Operator). The code runs top-level, NOT as a // service: main() is not called automatically, so do not wrap the code // in a main() function — use top-level statements, and return a result // with a top-level `return `. Only the `project` global is available (plus // the httpClient and console objects and utility libraries); the service // context variables and functions (contact, sendReply, etc.) are not. // // Example (run_script / run_analysis_script tools): // var count = project.queryContacts({ time_created: { min: 1735689600 } }).count(); // console.log("Contacts created since 2025: " + count); // return { new_contacts: count }; // // 2. CLOUD SCRIPT SERVICES — automated services (service types ending in // _script) whose code defines a main() entry point and can use extra // context globals (contact, message, content, etc.) and functions // (sendReply, waitForResponse, addResponseHandler, etc.) depending on the service type. // See the CLOUD SCRIPT SERVICES sections of this reference. // // 3. CUSTOM ACTIONS SERVICES - JavaScript defined within a "run_script" // action in a custom actions service (service types ending in _actions). // The code runs at the top level (not within a main() method), // and can use most context globals (contact, message, content, etc.) and functions (sendReply, sendEmail, etc.) // depending on the service type; however, functions that configure callback handlers (e.g. addResponseHandler) are not available. // // Example ("run_script" custom action): // { // "type": "run_script", // "code": "project.sendMessage({ to_number: '+15554567890', content: 'Hello!' });" // } // // =========================================== // JavaScript Language Support // =========================================== // // Some ES2015 language features are not currently available in Telerivet's script engine, including: // - import, export, and class keywords // - spread operator (... in function calls) // - const keyword within loops // JavaScript code should avoid using these language features to avoid errors. // // =========================================== // CLASSES // =========================================== // Full declarations for each class are available from the // get_documentation tool with id 'cloud_script_api:', // e.g. 'cloud_script_api:Project'. // // Entity classes — instances are obtained through the `project` global // (e.g. project.queryContacts(...), project.getContactById(id)) or from // other entities; query* methods return a Cursor: // Cursor — Cursor for iterating over query results. // Entity — Base class for Telerivet entities. Most API objects (Message, Contact, Project, etc.) extend this class. // Message — Represents a single message. // ScheduledMessage — Represents a scheduled message within Telerivet. // RelativeScheduledMessage — A relative scheduled message is a message that is scheduled relative to a date stored as a custom field for each recipient contact. // ScheduledService — Represents a scheduled service within Telerivet. // Contact — A contact represents a person or other entity that can be communicated with via phone number or other messaging channel within a project. // Broadcast — Represents a collection of related outgoing messages. Typically, messages in a broadcast have the same content template and were sent at the same time; however, a broadcast can also contain messages with unrelated content and messages that were sent at different times. // Campaign — A campaign is something that is sent to a group of contacts on a particular schedule. // Task — Represents an asynchronous task that is applied to all entities matching a filter. // 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. // Label — Represents a label used to organize messages within Telerivet. // Group — Represents a group used to organize contacts within Telerivet. // Phone — Represents a basic route (i.e. a phone or gateway) that you use to send/receive messages via Telerivet. // Route — Represents a custom route that can be used to send messages via one or more basic routes (phones). // DataTable — Represents a custom data table that can store arbitrary rows. // DataRow — Represents a row in a custom data table. // DataView — Represents a view of a data table, defined by a saved filter on the table's rows. // Service — Represents an automated service on Telerivet, for example a poll, auto-reply, webhook service, etc. // ContactServiceState — Represents the current state of a particular contact for a particular Telerivet service. // MessageTemplate — Represents a reusable message template that can be used when composing or scheduling messages. // StoredFile — Represents a file stored in a Telerivet project, such as a media attachment for outgoing messages. // AirtimeTransaction — Represents a transaction where airtime is sent to a mobile phone number. This also is used to represent non-airtime value transfers such as data bundles or gift cards. // Webhook — Represents a webhook that is triggered when specific events occur within a project. // // Utility classes — available as globals in every execution context, used via static methods or constructors: // DOMParser — Provides an API for parsing XML or HTML documents, such as responses from XML APIs or web pages. Methods: new DOMParser(), .parseFromString(xmlSource, supportedType) // XMLSerializer — Provides an API for constructing XML or HTML documents, such as requests to XML APIs. Methods: new XMLSerializer(), .serializeToString(domDocument) // JSON — Utility functions for parsing/serializing JSON. Methods: JSON.stringify(obj), JSON.parse(str) // PhoneNumber — Utility functions for phone numbers. Methods: PhoneNumber.formatE164(phoneNumber, defaultIsoCountryCode), PhoneNumber.formatInternational(phoneNumber, defaultIsoCountryCode), PhoneNumber.formatInternationalRaw(phoneNumber, defaultIsoCountryCode), PhoneNumber.formatNational(phoneNumber, defaultIsoCountryCode), PhoneNumber.formatNationalRaw(phoneNumber, defaultIsoCountryCode), PhoneNumber.getCountry(phoneNumber, defaultIsoCountryCode), PhoneNumber.getCountryPrefix(phoneNumber, defaultIsoCountryCode) // Base64 — Utility functions for encoding/decoding from Base64. Methods: Base64.encode(str), Base64.decode(base64str) // // Service utility classes — available only in certain Cloud Script services (see 'cloud_script_api:services'): // HTTPRequest — Type of `request` variable in scripts that directly handle incoming HTTP requests. // =========================================== // THIRD-PARTY LIBRARIES // =========================================== // Available as globals in every execution context (no require() needed). // Full TypeScript declarations for each library are available from the // get_documentation tool with id 'cloud_script_api:', e.g. // 'cloud_script_api:moment'. // _ — Underscore.js utility library (version 1.6.0). Provides functional programming helpers for collections, arrays, objects, and functions. For full API documentation, see https://underscorejs.org/ // moment — Moment.js date/time library (version 2.7.0, with Moment Timezone 0.5.5-2016f). Provides parsing, validation, manipulation, and formatting of dates. For full API documentation, see https://momentjs.com/docs/ // CryptoJS — CryptoJS cryptography library (version 3.1.2). Provides cryptographic algorithms including hashing, HMAC, and encryption. For full API documentation, see https://cryptojs.gitbook.io/docs/ // =========================================== // Global Variables and Objects // =========================================== // The following globals are available in every execution context (standalone // code and Cloud Script services). /** The current project */ declare const project: Project; /** * HTTP client for making requests to external APIs and web pages. */ declare const httpClient: { /** * Fetches a external URL over HTTP or HTTPS, such as an API or a web page. * @param url The URL to request. Must use http:// or https:// protocol; custom port numbers are not allowed. */ request(url: string, options?: { /** The HTTP method to use. Default: GET */ method?: "GET" | "POST" | "PUT" | "PATCH" | "HEAD" | "OPTIONS" | "DELETE"; /** * 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) */ params?: object; /** * The content of a HTTP POST, PUT, or PATCH request. If this is an object, Telerivet will * serialize the key/value pairs as URL-encoded params (e.g. {a:1,b:'hello world'} would be * encoded as a=1&b=hello+world). If you want to send data as JSON instead, pass the result * of calling JSON.stringify. */ data?: string | object; /** Key/value pairs for custom HTTP headers to send with the request */ headers?: object; /** A string in the format "username:password" to use for HTTP Basic authentication */ basicAuth?: string; /** * Timeout for the HTTP request in milliseconds. If the requested timeout is less than 1 ms * or longer than the overall timeout for the service, the overall timeout for the service * will be used instead. */ timeout?: number; }): { /** The HTTP response status code (e.g. 200, 404, etc.) */ status: number; /** The content of the HTTP response */ content: string; /** A key/value map of the HTTP response headers */ headers: object; }; }; /** * Console for logging output. When triggered via a service, output appears in the service's logs (and the simulator window when testing); when triggered via the run_script/run_analysis_script tools, output is returned in the tool results. */ declare const console: { /** * Logs a custom string in the service logs, simulator window, or tool * results, in order to help with debugging. * @param str The string to log */ log(str: string): void; /** * Same as console.log, but the log line is prefixed with "info:". Only the * first 10 calls per script execution are logged. * @param str The string to log */ info(str: string): void; /** * Same as console.log, but the log line is prefixed with "warn:". Only the * first 10 calls per script execution are logged. * @param str The string to log */ warn(str: string): void; /** * Same as console.log, but the log line is prefixed with "error:". Only * the first 10 calls per script execution are logged. * @param str The string to log */ error(str: string): void; /** * Displays a stack trace to the simulator window (and saves it in the logs * for your service), in order to help with debugging. */ trace(): void; }; // =========================================== // FURTHER REFERENCE // =========================================== // 'cloud_script_api:' — full declarations of one class listed above (e.g. 'cloud_script_api:Project'). // 'cloud_script_api:services' — for code saved as a Cloud Script service (not needed for the run_script / run_analysis_script tools): the main() entry point, service code examples, the context variables (contact, message, content, ...) and functions (sendReply, waitForResponse, ...) available to each service type. // 'cloud_script_api:' — full declarations of one third-party library listed above (e.g. 'cloud_script_api:moment').