Twilio Integration
Twilio Integration connects your ChatBotKit bots with Twilio's SMS messaging infrastructure, enabling bidirectional text message conversations with users through standard phone numbers. This integration allows your bots to send and receive SMS messages, creating accessible conversational experiences that work on any mobile device without requiring app installations or internet connectivity.
When you create a Twilio integration, you establish a bridge between your ChatBotKit bot and Twilio's messaging services, allowing users to interact with your bot by sending text messages to a Twilio phone number. The integration handles message routing, conversation state management, and ensures seamless communication between SMS users and your AI bot.
Creating Twilio Integrations
Creating a Twilio integration establishes the connection between your ChatBotKit bot and Twilio's SMS messaging infrastructure, enabling your bot to send and receive text messages through a Twilio phone number.
To create a Twilio integration, you need to specify which bot will handle the conversations and configure session management options:
The API will return the integration ID that you'll use to configure your Twilio phone number webhook:
Required Parameters
botId: The ID of the bot that will handle SMS conversations. This bot's personality, instructions, and capabilities determine how it responds to incoming text messages from users.
Session Management
sessionDuration: Controls how long conversation context persists between messages. Specified in milliseconds, with a maximum of one month (2,592,000,000ms). When a user doesn't send a message within this duration, the conversation context resets, and their next message starts a fresh conversation.
Setting appropriate session duration is important for SMS conversations because text message exchanges often have natural pauses. A session duration of 30 minutes (1,800,000ms) works well for most customer service scenarios, while longer durations may be appropriate for ongoing support relationships.
If not specified, the platform uses default session management behavior appropriate for SMS interactions.
Contact Collection
contactCollection: When enabled, the integration automatically creates and maintains contact records for users who interact with your bot via SMS. This allows you to track conversation history, understand user engagement patterns, and maintain context across multiple conversation sessions.
Contact collection is particularly valuable for SMS integrations because it associates conversations with phone numbers, enabling you to:
- Track conversation history for individual users
- Maintain context across session boundaries
- Analyze engagement patterns by phone number
- Provide personalized experiences for returning users
After Creating the Integration
After creating a Twilio integration, you need to complete setup in your Twilio account to route incoming SMS messages to ChatBotKit. This involves:
Configuring Webhook URL: In your Twilio console, configure your phone number's messaging webhook to point to the ChatBotKit Twilio integration endpoint. The webhook URL format is provided in the integration configuration interface.
Setting Authentication: Twilio requires webhook authentication to ensure message security. You'll need to configure the authentication credentials provided by ChatBotKit in your Twilio phone number settings.
Testing Message Flow: Send a test SMS to your Twilio phone number to verify that messages are properly routed to your bot and that responses are delivered back to users.
The setup process ensures that when users send text messages to your Twilio phone number, those messages are forwarded to your ChatBotKit bot, which processes them and sends responses back through Twilio's SMS infrastructure.
Integration with Blueprints
Twilio integrations can be associated with blueprints for organized resource
management. When you include a blueprintId during creation, the integration
becomes part of that blueprint's resource collection, making it easier to
manage related bots, integrations, and messaging configurations together.
This is particularly useful when managing multiple Twilio integrations for different purposes or phone numbers, as you can organize them under blueprints for simplified management and deployment.
Use Cases
Twilio integrations enable powerful SMS-based conversational experiences:
Customer Support via SMS: Provide accessible customer support through text messages, allowing customers to get help without apps or internet connectivity.
Appointment Reminders and Scheduling: Enable users to confirm, reschedule, or cancel appointments through conversational SMS interactions.
Order Status and Notifications: Allow customers to check order status, track deliveries, or receive proactive notifications via text message.
Lead Qualification: Engage potential customers through SMS conversations, qualifying leads and gathering information through natural text exchanges.
Service Accessibility: Reach users who may not have reliable internet access or prefer SMS communication over other channels.
Two-Way Information Services: Provide information services that users can access by texting keywords or questions to a phone number.
Important Considerations
Message Costs: SMS messages incur charges from Twilio based on message volume and destination. Monitor usage to understand costs associated with your bot's SMS interactions.
Message Length Limits: SMS messages have character limits (typically 160 characters). Long bot responses may be split into multiple messages, which can affect user experience and costs.
Conversation Pacing: SMS conversations typically have slower pacing than chat interfaces. Design your bot's responses to work well with the asynchronous nature of text messaging.
Phone Number Management: Each Twilio integration requires a dedicated Twilio phone number configured with the appropriate webhook settings.
User Privacy: SMS conversations are associated with phone numbers, which are personally identifiable information. Ensure appropriate data handling and privacy practices.
Deleting Twilio Integrations
Permanently delete a Twilio integration when you no longer need SMS messaging functionality for a specific phone number or when decommissioning a service. Deleting an integration removes the configuration that routes SMS messages to your ChatBotKit bot, immediately stopping message processing for that integration.
Delete a Twilio integration by sending a POST request to the delete endpoint:
The API confirms the deletion by returning the ID of the removed integration:
What Happens When You Delete
Immediate Effect: The integration stops processing incoming SMS messages immediately after deletion. Any messages sent to the associated Twilio phone number will no longer be routed to your ChatBotKit bot.
Webhook Configuration: Your Twilio phone number's webhook configuration remains unchanged. You should update or remove the webhook URL in your Twilio console to avoid errors when messages are sent to the number.
Conversation History: Existing conversation history and contact records created through this integration are preserved in your account. Deletion only removes the integration configuration, not the conversation data it generated.
Bot and Resources: The bot and other resources (datasets, skillsets) used by this integration are not affected. Only the Twilio integration configuration is removed.
Before You Delete
Consider these points before deleting a Twilio integration:
Active Users: If users are currently engaging with your bot through SMS, deleting the integration will immediately terminate their ability to receive responses. Consider scheduling deletions during low-activity periods.
Twilio Configuration: You'll need to update or remove webhook configuration in your Twilio account separately. Deleting the ChatBotKit integration doesn't automatically update your Twilio settings.
Alternative Approaches: If you want to temporarily disable the integration, consider removing the webhook configuration in Twilio instead of deleting the integration entirely. This preserves your ChatBotKit configuration for potential future reactivation.
Common Use Cases for Deletion
Service Decommissioning: When permanently shutting down an SMS-based service or retiring a phone number.
Phone Number Changes: When migrating to a new phone number and need to remove the old integration before creating a new one.
Testing and Development: Cleaning up test integrations created during development and quality assurance processes.
Resource Management: Removing unused integrations to maintain a clean, organized account with only active services.
Fetching Twilio Integration Details
Retrieve detailed configuration and settings for a specific Twilio integration, including its associated bot, session management settings, and current webhook configuration. Fetching integration details is essential for understanding your current setup and preparing for configuration updates.
Fetch a Twilio integration by sending a POST request with the integration ID:
The API returns complete integration details:
Understanding the Response
Configuration Details: The response includes all configurable settings such as the bot handling conversations, session duration for conversation context, and contact collection preferences.
Resource Relationships: View which bot and blueprint are associated with this integration, helping you understand the integration's role in your broader ChatBotKit setup.
Metadata and Organization: Access custom metadata fields you've assigned for categorization and management purposes.
Timestamps: See when the integration was created and last modified, useful for audit trails and understanding configuration history.
Common Use Cases
Configuration Review: Before making updates, fetch current settings to understand what will change and plan modifications carefully.
Debugging and Troubleshooting: When investigating SMS messaging issues, fetch integration details to verify configuration matches expected settings.
Automation and Tooling: Programmatically retrieve integration configurations for monitoring, backup, or synchronization with external systems.
Audit and Compliance: Document current integration settings for compliance requirements or internal audit processes.
Setting Up Twilio Integrations
Perform initial setup and configuration tasks for a Twilio integration after creation. The setup endpoint prepares the integration for operation by verifying configuration, establishing connections, and ensuring all components are properly initialized.
Execute setup for a Twilio integration by sending a POST request:
The API confirms successful setup:
When to Run Setup
After Initial Creation: Run setup immediately after creating a new Twilio integration to ensure it's properly configured and ready to handle incoming SMS messages.
After Configuration Changes: If you've made significant changes to the integration configuration (such as changing the bot or updating webhook settings), running setup can help ensure all components are synchronized.
Troubleshooting: When experiencing issues with message delivery or bot responses, running setup can help reset and reconfigure the integration to resolve potential configuration problems.
What Setup Does
The setup process performs several important initialization tasks:
Configuration Verification: Validates that all required settings are properly configured, including bot association, session management settings, and resource links.
Connection Testing: Verifies that the integration can communicate with necessary ChatBotKit services and that webhook endpoints are properly configured.
Resource Initialization: Ensures that all resources referenced by the integration (bots, datasets, blueprints) are accessible and properly linked.
State Preparation: Prepares internal state management structures needed for conversation tracking and session management.
Response Format
The setup endpoint returns the integration ID upon successful completion, confirming that all setup tasks completed without errors. If setup encounters problems, the API returns detailed error information to help you diagnose and resolve configuration issues.
Setup Performance
Setup operations typically complete within a few seconds. The process runs synchronously, so the API response indicates that setup has fully completed. You can begin using the integration immediately after receiving a successful setup response.
Best Practices
Run After Creation: Always run setup immediately after creating a new integration to ensure it's ready for production use.
Monitor Setup Results: Check the setup response for any warnings or errors that might indicate configuration problems requiring attention.
Document Setup Timing: Track when setup was last performed for each integration to aid in troubleshooting and maintenance.
Updating Twilio Integrations
Modify an existing Twilio integration's configuration to change which bot handles conversations, adjust session management settings, or update organizational information. Updates take effect immediately and apply to all subsequent SMS interactions through the integration.
Update a Twilio integration by sending a POST request with the new configuration:
The API confirms the update by returning the integration ID:
Updatable Parameters
name and description: Update identification and documentation for the integration. Changes are immediately visible in the ChatBotKit interface and API responses.
botId: Switch which bot handles SMS conversations through this integration. This is useful when you want to change bot behavior, deploy a new bot version, or redirect traffic to a different conversational experience. The change takes effect immediately for new conversations.
sessionDuration: Adjust how long conversation context persists between messages. Increasing the duration helps maintain context for users who take longer breaks between messages. Decreasing it causes conversations to reset more quickly, which may be appropriate for transactional interactions.
contactCollection: Enable or disable automatic contact record creation for SMS interactions. Enabling this feature allows you to track conversation history and user engagement patterns.
blueprintId: Associate the integration with a different blueprint, or remove the blueprint association by setting it to null. This affects how the integration is organized and managed within your account.
meta: Add or modify custom metadata fields for categorization, filtering, and management purposes.
Update Behavior
Immediate Effect: Configuration changes apply immediately to new conversations and messages. Users who send messages after the update will experience the new configuration.
Active Conversations: Ongoing conversations continue using the configuration that was active when they started. Session context and conversation state are not affected by updates during an active session.
Webhook Configuration: Updates to your ChatBotKit integration don't require changes to your Twilio webhook configuration. The webhook URL and authentication remain the same.
Common Update Scenarios
Bot Deployment: Update the botId to deploy a new or improved version of your conversational bot to the SMS channel.
Session Tuning: Adjust sessionDuration based on observed user behavior and conversation patterns to optimize context retention.
Feature Enablement: Enable contactCollection after initial deployment to begin tracking user engagement and conversation history.
Organizational Changes: Update blueprintId when reorganizing resources or changing how integrations are grouped for management purposes.
Documentation Updates: Modify name and description to reflect current usage, purpose, or any operational changes to the service.
Best Practices
Test Before Production: When changing botId, test the new bot thoroughly before updating production integrations to ensure conversation quality.
Monitor After Changes: After updating critical configuration like botId or sessionDuration, monitor conversation metrics to verify the changes have the desired effect.
Document Changes: Use metadata or external documentation to track why configuration was changed, when, and by whom for audit and troubleshooting purposes.
Incremental Updates: When making multiple changes, consider updating one parameter at a time to isolate the impact of each change and make troubleshooting easier if issues arise.
Listing Twilio Integrations
Retrieve a paginated list of all your Twilio integrations to manage and monitor your SMS messaging channels. Listing integrations is essential for understanding your current Twilio setup, managing multiple phone number integrations, and accessing integration IDs needed for updates and configuration.
Retrieve your Twilio integrations by sending a GET request:
The API will return a list of your integrations with their configuration details:
Pagination
The list endpoint supports cursor-based pagination for efficient handling of large numbers of integrations:
take: Number of integrations to return per page (default and maximum vary by account). Start with smaller values and increase as needed.
order: Sort order for results, either "asc" (oldest first) or "desc" (newest first, default). Use "desc" to see your most recently created integrations first.
cursor: Pagination cursor returned from the previous request. Include this to fetch the next page of results, maintaining consistent pagination state.
Filtering by Blueprint
When working with blueprints that organize related resources, you can filter Twilio integrations by their associated blueprint:
This returns only the integrations associated with the specified blueprint, making it easy to manage integrations that belong to specific projects or organizational units.
Filtering by Metadata
Filter integrations using custom metadata fields you've assigned:
Metadata filtering enables organization-specific categorization schemes, allowing you to query integrations based on custom attributes like environment, region, customer, or any other organizational dimension you've defined.
Response Format
Each integration in the response includes:
id: The unique integration identifier, used for update, delete, and fetch operations.
name and description: The human-readable identification you provided during creation.
botId: The ID of the bot handling SMS conversations through this integration.
contactCollection: Whether the integration automatically creates contact records for SMS interactions.
sessionDuration: How long conversation context persists between messages (in milliseconds).
blueprintId: The blueprint this integration belongs to, if any.
meta: Any custom metadata fields you've assigned to the integration.
createdAt and updatedAt: Timestamps showing when the integration was created and last modified.
Streaming Response (JSONL)
For applications processing large numbers of integrations, the list endpoint
supports streaming responses in JSONL format. Request with Accept: application/jsonl
header to receive integrations as a stream of newline-delimited JSON objects,
enabling memory-efficient processing of large result sets without loading
everything into memory at once.