### Install semaphore-client-js Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Installs the semaphore-client-js library using npm. This is the first step to using the library in your Node.js project. ```bash npm install semaphore-client-js ``` -------------------------------- ### Install semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Installs the semaphore-client-js package using npm, yarn, or pnpm. This is the first step to using the client library in your project. ```bash npm install semaphore-client-js ``` ```bash yarn add semaphore-client-js ``` ```bash pnpm add semaphore-client-js ``` -------------------------------- ### Get Account Info Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Retrieve account information including credit balance and account status. ```APIDOC ## Get Account Info ### Description Retrieve account information including credit balance and account status. ### Method GET ### Endpoint /account/info ### Response #### Success Response (200) - **account_id** (string) - The account's unique identifier. - **account_name** (string) - The name of the account. - **status** (string) - The current status of the account. - **credit_balance** (number) - The remaining credit balance. #### Response Example ```json { "account_id": "acc-12345", "account_name": "My Business Account", "status": "active", "credit_balance": 1000.50 } ``` ``` -------------------------------- ### Get Sender Names Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Retrieve list of approved sender names for your account. ```APIDOC ## Get Sender Names ### Description Retrieve list of approved sender names for your account. ### Method GET ### Endpoint /account/sender-names ### Response #### Success Response (200) - **Array of SenderName objects** - **name** (string) - The sender name. - **status** (string) - The status of the sender name (e.g., 'approved', 'pending'). - **created_at** (string) - The timestamp when the sender name was created. #### Response Example ```json [ { "name": "MyApp", "status": "approved", "created_at": "2024-01-10T09:00:00Z" } ] ``` ``` -------------------------------- ### Error Handling with Semaphore Client JS Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Provides examples of how to catch and handle various specific errors (AuthenticationError, RateLimitError, ValidationError, etc.) thrown by the SemaphoreClient. Requires an API key. ```typescript import { SemaphoreClient, SemaphoreError, AuthenticationError, RateLimitError, ValidationError, NetworkError, TimeoutError, } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); try { await client.messages.send({ number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE', }); } catch (error) { if (error instanceof RateLimitError) { // Rate limited (429) - automatically retried, but exhausted retries console.log('Rate limited, retry after:', error.retryAfter, 'seconds'); } else if (error instanceof AuthenticationError) { // Invalid API key (401) console.log('Invalid API key'); } else if (error instanceof ValidationError) { // Invalid request parameters (400) console.log('Validation error:', error.message); console.log('Field:', error.field); } else if (error instanceof TimeoutError) { // Request timed out console.log('Request timed out after:', error.timeoutMs, 'ms'); console.log('Request context:', error.request); } else if (error instanceof NetworkError) { // Network connection failed console.log('Network error:', error.message); console.log('Cause:', error.cause); } else if (error instanceof SemaphoreError) { // Other API errors (5xx, etc.) console.log('API error:', error.message); console.log('Status:', error.statusCode); } } ``` -------------------------------- ### Get Transaction History Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Retrieve transaction history with optional pagination and date filtering. ```APIDOC ## Get Transaction History ### Description Retrieve transaction history with optional pagination and date filtering. ### Method GET ### Endpoint /account/transactions ### Parameters #### Query Parameters - **page** (number) - Optional - The page number for pagination. - **limit** (number) - Optional - The number of transactions per page. - **startDate** (string) - Optional - The start date for filtering transactions (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for filtering transactions (YYYY-MM-DD). ### Response #### Success Response (200) - **Array of Transaction objects** - **type** (string) - The type of transaction (e.g., 'debit', 'credit'). - **amount** (number) - The amount of the transaction. - **description** (string) - A description of the transaction. - **balance_before** (number) - The account balance before the transaction. - **balance_after** (number) - The account balance after the transaction. - **created_at** (string) - The timestamp when the transaction occurred. #### Response Example ```json [ { "type": "debit", "amount": 2.50, "description": "OTP message sent", "balance_before": 1003.00, "balance_after": 1000.50, "created_at": "2024-03-15T10:30:00Z" } ] ``` ``` -------------------------------- ### Quick Start: Send an SMS with semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Demonstrates how to quickly send an SMS using the SemaphoreClient. It requires an API key and specifies the recipient number, message content, and sender name. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); // Send an SMS const result = await client.messages.send({ number: '639171234567', message: 'Hello from Semaphore!', sendername: 'SEMAPHORE', }); console.log('Message ID:', result.message_id); ``` -------------------------------- ### Get Transaction History with Semaphore Client JS Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Fetches the transaction history for the account. Supports optional filtering by page, limit, start date, and end date for pagination and specific date ranges. ```typescript // Get all transactions const transactions = await client.account.transactions(); ``` ```typescript // Get with pagination and date range const filtered = await client.account.transactions({ page: 1, limit: 50, startDate: '2024-01-01', endDate: '2024-01-31', }); for (const tx of filtered) { console.log(`${tx.type}: ${tx.amount} credits - ${tx.description}`); } ``` -------------------------------- ### Account Info API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Get account information including credit balance. ```APIDOC ## GET /account/info ### Description Retrieves information about the account, including its name, status, and current credit balance. ### Method GET ### Endpoint /account/info ### Parameters No parameters required. ### Response #### Success Response (200) - **account_id** (number) - The unique identifier for the account. - **account_name** (string) - The name of the account. - **status** (string) - The current status of the account (e.g., 'active', 'inactive'). - **credit_balance** (string) - The available credit balance for the account. #### Response Example ```json { "account_id": 101, "account_name": "My Account", "status": "active", "credit_balance": "100.50" } ``` ``` -------------------------------- ### Account Transactions API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Get transaction history with optional filtering by page, limit, start date, and end date. ```APIDOC ## GET /account/transactions ### Description Retrieves the transaction history for the account. Supports filtering by pagination and date range. ### Method GET ### Endpoint /account/transactions ### Parameters #### Query Parameters - **page** (number) - Optional - Page number for pagination. - **limit** (number) - Optional - Number of results per page. - **startDate** (string) - Optional - Filter by start date (YYYY-MM-DD). - **endDate** (string) - Optional - Filter by end date (YYYY-MM-DD). ### Response #### Success Response (200) - **id** (number) - The unique identifier for the transaction. - **account_id** (number) - The account ID associated with the transaction. - **user_id** (number) - The user ID associated with the transaction. - **type** (string) - The type of transaction (e.g., 'credit', 'debit'). - **amount** (string) - The amount of the transaction. - **balance_before** (string) - The account balance before the transaction. - **balance_after** (string) - The account balance after the transaction. - **description** (string) - A description of the transaction. - **created_at** (string) - The timestamp when the transaction occurred. #### Response Example ```json [ { "id": 1, "account_id": 101, "user_id": 1, "type": "debit", "amount": "-5.00", "balance_before": "105.50", "balance_after": "100.50", "description": "Sent SMS message", "created_at": "2024-01-15T14:30:00Z" } ] ``` ``` -------------------------------- ### Get Account Information with Semaphore Client JS Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Retrieves account details, including the account name, status, and current credit balance. This function does not require any parameters. ```typescript const info = await client.account.info(); console.log('Account:', info.account_name); console.log('Status:', info.status); console.log('Balance:', info.credit_balance); ``` -------------------------------- ### Sender Names API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Get a list of approved sender names associated with the account. ```APIDOC ## GET /account/senderNames ### Description Retrieves a list of sender names that have been approved for use with the account. ### Method GET ### Endpoint /account/senderNames ### Parameters No parameters required. ### Response #### Success Response (200) - **name** (string) - The approved sender name. - **status** (string) - The status of the sender name (e.g., 'approved', 'pending'). - **created_at** (string) - The timestamp when the sender name was registered. #### Response Example ```json [ { "name": "MyApp", "status": "approved", "created_at": "2023-12-01T09:00:00Z" } ] ``` ``` -------------------------------- ### Get Approved Sender Names with Semaphore Client JS Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Retrieves a list of all sender names that have been approved for use with the Semaphore service. This function does not require any parameters. ```typescript const senderNames = await client.account.senderNames(); for (const sender of senderNames) { console.log(`${sender.name}: ${sender.status}`); } ``` -------------------------------- ### Initialize SemaphoreClient in TypeScript Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Demonstrates how to initialize the SemaphoreClient with an API key, either directly or via an environment variable. It also shows optional configuration for base URL, timeout, and retry logic. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; // Basic initialization const client = new SemaphoreClient({ apiKey: 'your-api-key' }); // Full configuration with all options const clientWithOptions = new SemaphoreClient({ apiKey: 'your-api-key', baseUrl: 'https://api.semaphore.co/api/v4', // Optional, this is the default timeout: 30000, // Request timeout in ms (default: 30000) onRetry: (attempt, delayMs) => { console.log(`Rate limited. Retry attempt ${attempt} in ${delayMs}ms`); }, }); // Using environment variable (SEMAPHORE_API_KEY) // export SEMAPHORE_API_KEY=your-api-key const clientFromEnv = new SemaphoreClient(); ``` -------------------------------- ### List Messages with semaphore-client-js Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Demonstrates how to retrieve sent messages, including options for filtering by date, status, network, or sender name, and pagination using `page` and `limit` parameters. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); // List all messages const messages = await client.messages.list(); // List with filters and pagination const filtered = await client.messages.list({ page: 1, limit: 50, status: 'Sent', startDate: '2024-01-01', endDate: '2024-01-31', network: 'Globe', sendername: 'SEMAPHORE', }); for (const msg of filtered) { console.log(`${msg.message_id}: ${msg.recipient} - ${msg.status}`); } ``` -------------------------------- ### Send OTP Message with Semaphore Client JS Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Demonstrates how to send One-Time Password (OTP) messages using the SemaphoreClient. Supports default 6-digit codes and custom lengths. Requires an API key. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); // Send OTP with default 6-digit code const response = await client.otp.send({ number: '639171234567', message: 'Your verification code is {otp}. Valid for 5 minutes.', sendername: 'MyApp', }); console.log('OTP Code:', response.code); // '123456' console.log('Message ID:', response.message_id); console.log('Recipient:', response.recipient); // Store the code for verification const generatedCode = response.code; // Send OTP with custom 4-digit code const shortOtp = await client.otp.send({ number: '639171234567', message: 'Your code: {otp}', sendername: 'MyApp', code_length: 4, }); console.log('4-digit OTP:', shortOtp.code); // '1234' ``` -------------------------------- ### Configure SemaphoreClient Instance Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Shows how to create a SemaphoreClient instance with various configuration options. This includes setting the API key, custom base URL, request timeout, and a retry callback function for handling rate limits. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key', // Required (or set SEMAPHORE_API_KEY env var) baseUrl: 'https://api.semaphore.co/api/v4', // Optional, this is the default timeout: 30000, // Optional, request timeout in ms (default: 30000) onRetry: (attempt, delayMs) => { console.log(`Retry attempt ${attempt} after ${delayMs}ms`); }, }); ``` -------------------------------- ### Send SMS Message with semaphore-client-js Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Shows how to send SMS messages to single or multiple recipients using the `client.messages.send()` method. It details the expected response structure for both scenarios. ```typescript import { SemaphoreClient } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); // Send to a single recipient const response = await client.messages.send({ number: '639171234567', message: 'Hello from Semaphore!', sendername: 'SEMAPHORE', }); console.log('Message ID:', response.message_id); // 12345 console.log('Status:', response.status); // 'Queued' console.log('Recipient:', response.recipient); // '639171234567' // Bulk send to multiple recipients (up to 1000) const bulkResponses = await client.messages.send({ number: ['639171234567', '639181234567', '639191234567'], message: 'Hello everyone!', sendername: 'SEMAPHORE', }); // Returns array of responses for (const msg of bulkResponses) { console.log(`Sent to ${msg.recipient}: ${msg.message_id}`); } ``` -------------------------------- ### Send OTP Message Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Send OTP messages via priority route with no rate limit. The API generates the OTP code and replaces the `{otp}` placeholder in your message. Each OTP costs 2 credits per 160 characters. ```APIDOC ## Send OTP Message ### Description Send OTP messages via priority route with no rate limit. The API generates the OTP code and replaces the `{otp}` placeholder in your message. Each OTP costs 2 credits per 160 characters. ### Method POST ### Endpoint /otp/send ### Parameters #### Request Body - **number** (string) - Required - The recipient's phone number. - **message** (string) - Required - The message template containing the `{otp}` placeholder. - **sendername** (string) - Required - The sender ID. - **code_length** (number) - Optional - The desired length of the OTP code (defaults to 6). ### Request Example ```json { "number": "639171234567", "message": "Your verification code is {otp}. Valid for 5 minutes.", "sendername": "MyApp", "code_length": 6 } ``` ### Response #### Success Response (200) - **code** (string) - The generated OTP code. - **message_id** (string) - The unique identifier for the sent message. - **recipient** (string) - The recipient's phone number. #### Response Example ```json { "code": "123456", "message_id": "some-message-id", "recipient": "639171234567" } ``` ``` -------------------------------- ### TypeScript Types for Semaphore Client JS Source: https://context7.com/rohjli/semaphore-client-js/llms.txt Illustrates how to leverage the exported TypeScript interfaces from the semaphore-client-js library for type-safe request building and response handling. No API key required for type definitions. ```typescript import type { SemaphoreClientOptions, SendMessageRequest, SendMessageResponse, BulkSendMessageResponse, MessageListRequest, Message, SendOtpRequest, SendOtpResponse, AccountInfo, Transaction, TransactionListRequest, SenderName, } from 'semaphore-client-js'; // Type-safe request building const sendParams: SendMessageRequest = { number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE', }; // Type-safe response handling function handleResponse(response: SendMessageResponse): void { console.log(`Message ${response.message_id} sent to ${response.recipient}`); } ``` -------------------------------- ### Configure SemaphoreClient using Environment Variable Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Demonstrates how to configure the SemaphoreClient by setting the API key via an environment variable. This avoids hardcoding the API key directly in the code. ```bash export SEMAPHORE_API_KEY=your-api-key ``` ```typescript // API key will be read from SEMAPHORE_API_KEY const client = new SemaphoreClient(); ``` -------------------------------- ### Error Handling Source: https://context7.com/rohjli/semaphore-client-js/llms.txt The library provides typed error classes for different failure scenarios. All errors extend `SemaphoreError` and include relevant context for debugging. ```APIDOC ## Error Handling ### Description The library provides typed error classes for different failure scenarios. All errors extend `SemaphoreError` and include relevant context for debugging. ### Error Types - **SemaphoreError**: Base class for all Semaphore errors. - **AuthenticationError**: For invalid API key (401). - **RateLimitError**: For rate limiting errors (429). - **ValidationError**: For invalid request parameters (400). - **TimeoutError**: For request timeouts. - **NetworkError**: For network connection failures. ### Example Usage ```typescript try { // API call that might fail } catch (error) { if (error instanceof RateLimitError) { console.log('Rate limited, retry after:', error.retryAfter, 'seconds'); } else if (error instanceof AuthenticationError) { console.log('Invalid API key'); } else if (error instanceof ValidationError) { console.log('Validation error:', error.message); console.log('Field:', error.field); } else if (error instanceof TimeoutError) { console.log('Request timed out after:', error.timeoutMs, 'ms'); } else if (error instanceof NetworkError) { console.log('Network error:', error.message); } else if (error instanceof SemaphoreError) { console.log('API error:', error.message); console.log('Status:', error.statusCode); } } ``` ``` -------------------------------- ### TypeScript Types Source: https://context7.com/rohjli/semaphore-client-js/llms.txt The library exports all TypeScript interfaces for request/response objects, enabling full type safety in your application. ```APIDOC ## TypeScript Types ### Description The library exports all TypeScript interfaces for request/response objects, enabling full type safety in your application. ### Available Types - **SemaphoreClientOptions**: Options for initializing the SemaphoreClient. - **SendMessageRequest**: Interface for sending a standard message. - **SendMessageResponse**: Interface for the response of sending a standard message. - **BulkSendMessageResponse**: Interface for the response of sending bulk messages. - **MessageListRequest**: Interface for requesting a list of messages. - **Message**: Interface representing a single message. - **SendOtpRequest**: Interface for sending an OTP message. - **SendOtpResponse**: Interface for the response of sending an OTP message. - **AccountInfo**: Interface for account information. - **Transaction**: Interface representing a single transaction. - **TransactionListRequest**: Interface for requesting a list of transactions. - **SenderName**: Interface representing an approved sender name. ### Example Usage ```typescript import type { SendMessageRequest, SendMessageResponse } from 'semaphore-client-js'; const sendParams: SendMessageRequest = { number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE' }; function handleResponse(response: SendMessageResponse): void { console.log(`Message ${response.message_id} sent to ${response.recipient}`); } ``` ``` -------------------------------- ### Configure Automatic Retry Callback in Semaphore Client JS Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Demonstrates how to configure the `onRetry` callback when initializing the SemaphoreClient. This callback is invoked when a rate-limited request (429 status code) is automatically retried, providing information about the attempt number and delay. ```typescript const client = new SemaphoreClient({ apiKey: 'your-api-key', onRetry: (attempt, delayMs) => { console.log(`Rate limited. Retry attempt ${attempt} in ${delayMs}ms`); }, }); ``` -------------------------------- ### Automatic Retry Mechanism Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Explains the automatic retry functionality for rate-limited requests and how to configure the `onRetry` callback. ```APIDOC ## Automatic Retry The Semaphore Client JS library automatically retries requests that receive a `429 RateLimitError` response. This retry mechanism employs exponential backoff to avoid overwhelming the server. You can monitor and customize the retry behavior using the `onRetry` callback function during client initialization. ### Configuring `onRetry` Callback To track or influence the retry process, provide a callback function to the `onRetry` option when creating a new `SemaphoreClient` instance. **Example:** ```typescript const client = new SemaphoreClient({ apiKey: 'your-api-key', onRetry: (attempt, delayMs) => { console.log(`Rate limited. Retry attempt ${attempt} in ${delayMs}ms`); }, }); ``` - **`attempt`**: The current retry attempt number (starts from 1). - **`delayMs`**: The delay in milliseconds before the next retry attempt. ``` -------------------------------- ### Handle Semaphore Client JS Errors Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Demonstrates how to import and use various error types provided by the semaphore-client-js library within a try-catch block for robust error handling. Includes specific checks for RateLimitError, AuthenticationError, ValidationError, TimeoutError, NetworkError, and general SemaphoreError. ```typescript import { SemaphoreClient, SemaphoreError, AuthenticationError, RateLimitError, ValidationError, NetworkError, TimeoutError, } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); try { await client.messages.send({ number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE', }); } catch (error) { if (error instanceof RateLimitError) { // Rate limited (429) - retry after delay console.log('Rate limited, retry after:', error.retryAfter, 'seconds'); } else if (error instanceof AuthenticationError) { // Invalid API key (401) console.log('Invalid API key'); } else if (error instanceof ValidationError) { // Invalid request parameters (400) console.log('Validation error:', error.message); console.log('Field:', error.field); } else if (error instanceof TimeoutError) { // Request timed out console.log('Request timed out after:', error.timeoutMs, 'ms'); } else if (error instanceof NetworkError) { // Network connection failed console.log('Network error:', error.message); console.log('Cause:', error.cause); } else if (error instanceof SemaphoreError) { // Other API errors (5xx, etc.) console.log('API error:', error.message); console.log('Status:', error.statusCode); } } ``` -------------------------------- ### OTP API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md This section details the API endpoint for sending One-Time Password (OTP) messages via a priority route with no rate limits. ```APIDOC ## POST /otp ### Description Send OTP messages via priority route with no rate limit. Each OTP message costs 2 credits per 160 characters. ### Method POST ### Endpoint /otp ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your Semaphore API key. #### Request Body - **number** (string) - Required - Recipient phone number. - **message** (string) - Required - OTP message content. - **sendername** (string) - Required - Approved sender name. ### Request Example ```json { "number": "639171234567", "message": "Your OTP is 123456.", "sendername": "SEMAPHORE" } ``` ### Response #### Success Response (200) - **message_id** (number) - The unique identifier for the sent OTP message. - **status** (string) - The status of the OTP message (e.g., 'Queued'). #### Response Example ```json { "message_id": 67890, "status": "Queued" } ``` ``` -------------------------------- ### Error Handling Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Details on the types of errors that can be thrown by the Semaphore Client JS library and how to handle them. ```APIDOC ## Error Handling ### Description The Semaphore Client JS library throws specific error types to indicate different failure scenarios. This section outlines the available error types and provides guidance on how to catch and handle them. ### Error Types - **SemaphoreError**: Base class for all Semaphore API errors. - **AuthenticationError**: Thrown for invalid API keys (HTTP 401). - **RateLimitError**: Thrown when the API rate limit is exceeded (HTTP 429). Contains a `retryAfter` property. - **ValidationError**: Thrown for invalid request parameters (HTTP 400). Contains `message` and `field` properties. - **TimeoutError**: Thrown when a request times out. Contains a `timeoutMs` property. - **NetworkError**: Thrown for network connection failures. Contains a `cause` property. ### Usage Example ```javascript import { SemaphoreClient, SemaphoreError, AuthenticationError, RateLimitError, ValidationError, NetworkError, TimeoutError } from 'semaphore-client-js'; const client = new SemaphoreClient({ apiKey: 'your-api-key' }); try { // Example API call that might fail await client.messages.send({ number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE', }); } catch (error) { if (error instanceof RateLimitError) { console.log('Rate limited, retry after:', error.retryAfter, 'seconds'); } else if (error instanceof AuthenticationError) { console.log('Invalid API key'); } else if (error instanceof ValidationError) { console.log('Validation error:', error.message); console.log('Field:', error.field); } else if (error instanceof TimeoutError) { console.log('Request timed out after:', error.timeoutMs, 'ms'); } else if (error instanceof NetworkError) { console.log('Network error:', error.message); console.log('Cause:', error.cause); } else if (error instanceof SemaphoreError) { console.log('API error:', error.message); console.log('Status:', error.statusCode); } else { console.log('An unexpected error occurred:', error); } } ``` ``` -------------------------------- ### SMS Credits System Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Details the credit system for sending SMS messages, including standard SMS, OTP SMS, long messages, and Unicode character limits. ```APIDOC ## SMS Credits Understanding the SMS credit system is crucial for managing message costs and delivery. ### Credit Allocation - **Standard SMS**: Each message costs **1 credit** per 160 ASCII characters. - **OTP SMS**: These messages, sent via a priority route, cost **2 credits** per 160 ASCII characters. ### Message Segmentation - **Long Messages**: Messages exceeding the standard character limit are automatically split into segments. Each segment is limited to **153 characters** to accommodate message headers. - **Unicode Characters**: For messages containing Unicode characters, the limit per segment is **70 characters** due to the increased byte size of these characters. ``` -------------------------------- ### OTP Send API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Send an OTP message. The API generates the OTP code and replaces the `{otp}` placeholder in your message. Supports custom code length. ```APIDOC ## POST /otp/send ### Description Sends an OTP message to a recipient. The OTP code is generated and inserted into the message template. ### Method POST ### Endpoint /otp/send ### Parameters #### Request Body - **number** (string) - Required - Recipient phone number - **message** (string) - Required - Message template with `{otp}` placeholder - **sendername** (string) - Required - Approved sender name - **code_length** (number) - Optional - OTP code length (default: 6) ### Request Example ```json { "number": "639171234567", "message": "Your verification code is {otp}", "sendername": "MyApp", "code_length": 4 } ``` ### Response #### Success Response (200) - **message_id** (number) - The ID of the sent message. - **code** (string) - The generated OTP code. - **user_id** (number) - The user ID associated with the message. - **user** (string) - The username. - **account_id** (number) - The account ID. - **account** (string) - The account name. - **recipient** (string) - The recipient's phone number. - **message** (string) - The final message sent. - **sender_name** (string) - The sender name used. - **network** (string) - The network provider. - **status** (string) - The status of the message. - **type** (string) - The type of message. - **source** (string) - The source of the message. - **created_at** (string) - The timestamp when the message was created. - **updated_at** (string) - The timestamp when the message was last updated. #### Response Example ```json { "message_id": 123456789, "code": "123456", "user_id": 1, "user": "example_user", "account_id": 101, "account": "My Account", "recipient": "639171234567", "message": "Your verification code is 123456", "sender_name": "MyApp", "network": "Globe", "status": "sent", "type": "otp", "source": "api", "created_at": "2024-01-01T10:00:00Z", "updated_at": "2024-01-01T10:00:05Z" } ``` ``` -------------------------------- ### Error Types Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md This section outlines the different error types that can be encountered when using the Semaphore Client JS library, along with their corresponding status codes and descriptions. ```APIDOC ## Error Types This section details the various error types the Semaphore Client JS library can produce, including their status codes and descriptions. ### Error Types Overview | Error Type | Status Code | Description | |---------------------|-------------|-------------------------------------------------| | `AuthenticationError` | 401 | Invalid or missing API key | | `RateLimitError` | 429 | Rate limit exceeded (120 req/min for standard SMS) | | `ValidationError` | 400 | Invalid request parameters | | `NetworkError` | - | Connection failure, DNS error | | `TimeoutError` | - | Request exceeded timeout | | `SemaphoreError` | 5xx | Server errors and other failures | ### Error Handling When an error occurs, the client will throw an error object corresponding to the type listed above. Developers should implement appropriate error handling logic to manage these scenarios. ``` -------------------------------- ### Messages API Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md This section details the API endpoints for managing SMS messages, including sending, listing, and retrieving message details. ```APIDOC ## POST /messages/send ### Description Send an SMS to one or more recipients. Supports single and bulk sending. ### Method POST ### Endpoint /messages/send ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your Semaphore API key. #### Request Body - **number** (string | string[]) - Required - Recipient number(s). Max 1000 for bulk. - **message** (string) - Required - Message content. - **sendername** (string) - Required - Approved sender name. ### Request Example ```json { "number": "639171234567", "message": "Hello from Semaphore!", "sendername": "SEMAPHORE" } ``` ### Response #### Success Response (200) - **message_id** (number) - The unique identifier for the sent message. - **user_id** (number) - The ID of the user. - **user** (string) - The username. - **account_id** (number) - The ID of the account. - **account** (string) - The account name. - **recipient** (string) - The recipient's phone number. - **message** (string) - The content of the message. - **sender_name** (string) - The sender name used. - **network** (string) - The network the message was sent to. - **status** (string) - The status of the message (e.g., 'Queued', 'Sent'). - **type** (string) - The type of message. - **source** (string) - The source of the message. - **created_at** (string) - The timestamp when the message was created. - **updated_at** (string) - The timestamp when the message was last updated. #### Response Example ```json { "message_id": 12345, "user_id": 1, "user": "example_user", "account_id": 10, "account": "example_account", "recipient": "639171234567", "message": "Hello!", "sender_name": "SEMAPHORE", "network": "Globe", "status": "Queued", "type": "SMS", "source": "API", "created_at": "2024-07-27T10:00:00Z", "updated_at": "2024-07-27T10:00:00Z" } ``` ## GET /messages ### Description List sent messages with optional filtering for pagination, date range, network, status, and sender name. ### Method GET ### Endpoint /messages ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your Semaphore API key. - **page** (number) - Optional - Page number for pagination. - **limit** (number) - Optional - Number of results per page. - **startDate** (string) - Optional - Filter by start date (YYYY-MM-DD). - **endDate** (string) - Optional - Filter by end date (YYYY-MM-DD). - **network** (string) - Optional - Filter by network. - **status** (string) - Optional - Filter by status. - **sendername** (string) - Optional - Filter by sender name. ### Response #### Success Response (200) Returns an array of message objects matching the filter criteria. #### Response Example ```json [ { "message_id": 12345, "recipient": "639171234567", "message": "Hello!", "sender_name": "SEMAPHORE", "status": "Sent", "created_at": "2024-07-27T10:00:00Z" } ] ``` ## GET /messages/{id} ### Description Retrieve a specific message by its unique ID. ### Method GET ### Endpoint /messages/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The unique identifier of the message. #### Query Parameters - **apiKey** (string) - Required - Your Semaphore API key. ### Response #### Success Response (200) - **message_id** (number) - The unique identifier for the sent message. - **user_id** (number) - The ID of the user. - **user** (string) - The username. - **account_id** (number) - The ID of the account. - **account** (string) - The account name. - **recipient** (string) - The recipient's phone number. - **message** (string) - The content of the message. - **sender_name** (string) - The sender name used. - **network** (string) - The network the message was sent to. - **status** (string) - The status of the message. - **type** (string) - The type of message. - **source** (string) - The source of the message. - **created_at** (string) - The timestamp when the message was created. - **updated_at** (string) - The timestamp when the message was last updated. #### Response Example ```json { "message_id": 12345, "user_id": 1, "user": "example_user", "account_id": 10, "account": "example_account", "recipient": "639171234567", "message": "Hello!", "sender_name": "SEMAPHORE", "network": "Globe", "status": "Sent", "type": "SMS", "source": "API", "created_at": "2024-07-27T10:00:00Z", "updated_at": "2024-07-27T10:05:00Z" } ``` ``` -------------------------------- ### Send Bulk SMS Messages with semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Sends SMS messages to multiple recipients simultaneously using the `client.messages.send` method with an array of numbers. It returns an array of responses, one for each recipient. ```typescript const responses = await client.messages.send({ number: ['639171234567', '639181234567', '639191234567'], message: 'Hello everyone!', sendername: 'SEMAPHORE', }); // Returns array of responses for (const response of responses) { console.log(`Sent to ${response.recipient}: ${response.message_id}`); } ``` -------------------------------- ### Send OTP Message with Semaphore Client JS Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Sends an OTP message to a recipient. The API generates the OTP code and inserts it into the provided message template. Supports custom OTP code length. ```typescript const response = await client.otp.send({ number: '639171234567', message: 'Your verification code is {otp}', sendername: 'MyApp', }); console.log('OTP code:', response.code); // '123456' console.log('Message ID:', response.message_id); ``` ```typescript const response = await client.otp.send({ number: '639171234567', message: 'Your code: {otp}', sendername: 'MyApp', code_length: 4, // Generate 4-digit code instead of default 6 }); ``` -------------------------------- ### List Sent Messages with Filters using semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Retrieves a list of sent SMS messages, with options to filter by page, limit, date range, network, status, and sender name. This allows for paginated and specific message retrieval. ```typescript // List all messages const messages = await client.messages.list(); // List with filters const filtered = await client.messages.list({ page: 1, limit: 50, status: 'Sent', startDate: '2024-01-01', endDate: '2024-01-31', }); ``` -------------------------------- ### Retrieve Specific Message by ID with semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Fetches details of a single SMS message using its unique ID. This method is useful for checking the status or content of a previously sent message. ```typescript const message = await client.messages.get(12345); console.log(message.status); // 'Sent' console.log(message.recipient); // '639171234567' console.log(message.message); // 'Hello!' ``` -------------------------------- ### Send Single SMS Message with semaphore-client-js Source: https://github.com/rohjli/semaphore-client-js/blob/main/README.md Sends an SMS message to a single recipient using the `client.messages.send` method. It returns details about the sent message, including its ID and status. ```typescript // Send to a single recipient const response = await client.messages.send({ number: '639171234567', message: 'Hello!', sendername: 'SEMAPHORE', }); console.log(response.message_id); // 12345 console.log(response.status); // 'Queued' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.