Telegram is one of the most popular messaging platforms worldwide, with millions of active users. Integrating ChatBotKit with Telegram allows you to create intelligent conversational bots that can interact with users in real-time, providing automated support, information delivery, and engaging conversations directly within the Telegram app.
The Telegram integration enables your ChatBotKit bots to receive and respond to messages from Telegram users, supporting both individual chats and group conversations. With features like contact collection, session management, and attachment handling, you can build sophisticated bot experiences tailored to your specific use case.
Creating a Telegram Integration
Before creating a Telegram integration in ChatBotKit, you need to create a bot through Telegram's BotFather. Once you have your bot token from BotFather, you can create the integration to connect your ChatBotKit bot with Telegram.
To create a new Telegram integration, send a POST request with your bot token and configuration options:
POST /api/v1/integration/telegram/create Content-Type: application/json { "name": "Customer Support Bot", "description": "Telegram bot for customer support", "botId": "bot_xxxxx", "botToken": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", "contactCollection": true, "sessionDuration": 3600000, "attachments": false }http
The botToken is the authentication token provided by Telegram's BotFather
when you create your bot. This token is required and must be kept secure as
it provides full access to your Telegram bot's functionality.
Configuration Options
- name: A descriptive name for your integration
- description: Optional description for internal reference
- botId: Link to an existing ChatBotKit bot that will handle conversations
- blueprintId: Optional blueprint for advanced configuration
- botToken: Your Telegram bot token from BotFather (required)
- contactCollection: Enable to collect user contact information
- sessionDuration: Session timeout in milliseconds (max 30 days)
- attachments: Enable to allow users to send file attachments
Important: After creating the integration, you must call the setup endpoint to configure the webhook with Telegram. The integration will not be active until the webhook is properly configured.
Getting Your Bot Token
To obtain a bot token from Telegram:
- Open Telegram and search for
@BotFather - Start a conversation and send
/newbot - Follow the prompts to name your bot and choose a username
- BotFather will provide your bot token - save it securely
- Use this token when creating your ChatBotKit integration
For detailed setup instructions, refer to the Telegram Integration Guide.
Security Note: Never share your bot token publicly or commit it to version control. Anyone with access to your bot token can control your Telegram bot.
Deleting a Telegram Integration
Permanently remove a Telegram integration from your ChatBotKit account. This action disconnects your ChatBotKit bot from Telegram and stops all message processing for the associated bot. Deletion is immediate and cannot be undone.
To delete a Telegram integration, send a POST request:
POST /api/v1/integration/telegram/{telegramIntegrationId}/delete Content-Type: application/json {}http
The request body must be provided but can be empty. Replace {telegramIntegrationId}
with the ID of the integration you want to delete.
What Happens When You Delete
When you delete a Telegram integration:
-
Webhook Deactivation: The webhook connection with Telegram is immediately terminated, and your bot will stop receiving messages.
-
Integration Removal: The integration configuration is permanently removed from your ChatBotKit account.
-
Bot Retention: Your Telegram bot on Telegram's platform remains active. To fully deactivate it, you need to delete it through BotFather.
-
ChatBotKit Bot Retention: The connected ChatBotKit bot is not affected and remains available for use with other integrations.
-
Conversation History: Existing conversation data in ChatBotKit is preserved and can be accessed through the conversations API.
Before Deleting
Consider these steps before permanently deleting an integration:
-
Export Data: If you need conversation history or analytics, export them before deletion as you won't be able to access integration-specific data after removal.
-
Update Telegram Bot: If you're done with the bot entirely, delete it through BotFather on Telegram to prevent confusion for users who might still try to interact with it.
-
Notify Users: If your bot has active users, consider sending a final message informing them about the discontinuation of service.
-
Alternative Solutions: If you're experiencing issues, consider updating the configuration or temporarily disabling the integration instead of permanent deletion.
Warning: Deletion is permanent and immediate. There is no way to recover a deleted integration. You would need to create a new integration and reconfigure the webhook to restore Telegram connectivity.
Fetching a Telegram Integration
Retrieve the complete configuration details for a specific Telegram integration. This is useful when you need to review settings, verify configuration, or display integration details in your application's user interface.
To fetch a specific Telegram integration, send a GET request with the integration ID:
GET /api/v1/integration/telegram/{telegramIntegrationId}/fetchhttp
Replace {telegramIntegrationId} with your actual integration ID obtained
during creation or from the list endpoint.
Response Details
The response includes comprehensive information about the integration:
- Basic Information: ID, name, description, creation and update timestamps
- Resource Links: Connected bot ID and blueprint ID (if applicable)
- Configuration: Contact collection settings, session duration, attachments support
- Metadata: Custom metadata fields for application-specific data
Security Note: The bot token is never included in fetch responses for security reasons. The token is only required during creation and updates.
Common Use Cases
- Configuration Review: Verify integration settings before making updates
- Status Monitoring: Check when the integration was last modified
- UI Display: Show integration details in management dashboards
- Troubleshooting: Review configuration when investigating issues
Example response structure:
{ "id": "telegram_xxxxx", "name": "Customer Support Bot", "description": "Handles customer inquiries", "botId": "bot_xxxxx", "contactCollection": true, "sessionDuration": 3600000, "attachments": false, "createdAt": "2025-01-10T12:00:00Z", "updatedAt": "2025-01-10T12:00:00Z" }json
The endpoint requires proper authentication and will only return integrations that belong to your account. Attempting to fetch another user's integration will result in a not found or unauthorized error.
Setting Up the Telegram Webhook
The setup endpoint is a critical step that configures the webhook connection between Telegram and ChatBotKit. This must be called after creating or updating an integration before your bot can receive and process messages from Telegram users. The setup process automatically registers your ChatBotKit webhook URL with Telegram's servers.
To setup the webhook for your Telegram integration, send a POST request:
POST /api/v1/integration/telegram/{telegramIntegrationId}/setup Content-Type: application/json {}http
The request body must be provided but can be empty. The setup process is idempotent - calling it multiple times is safe and will only update the webhook if needed.
What Setup Does
When you call the setup endpoint, ChatBotKit performs several automated steps:
-
Webhook Verification: Checks if Telegram already has a webhook configured for your bot and whether it matches the expected ChatBotKit endpoint.
-
Webhook Registration: If no webhook exists or the current webhook is different, registers the ChatBotKit webhook URL with Telegram using your bot token.
-
Update Configuration: Configures Telegram to send
messageandbusiness_messageevents to ChatBotKit, ensuring your bot receives all relevant user interactions. -
Validation: Verifies the webhook was successfully registered by checking Telegram's webhook info endpoint.
When to Run Setup
You must run setup in these scenarios:
-
After Initial Creation: When you first create a Telegram integration, setup is required to activate the webhook.
-
After Updating Bot Token: If you change the bot token in the integration, setup must be run again to register the webhook with the new token.
-
After Webhook Changes: If you manually modify the webhook through Telegram's API or BotFather, run setup to restore ChatBotKit connectivity.
-
Troubleshooting: If your bot stops receiving messages, running setup can often resolve webhook configuration issues.
Understanding Webhook URLs
ChatBotKit automatically generates a unique webhook URL for each integration:
https://api.chatbotkit.com/api/v1/integration/telegram/{integrationId}/webhook
This URL is where Telegram will send all messages and events for your bot. You should never need to manually construct or modify this URL - the setup endpoint handles all webhook URL configuration automatically.
Troubleshooting Setup Issues
"Telegram Integration Error: Bot token is invalid": Verify your bot token
is correct. You can test it by calling Telegram's getMe API directly. The
token format should be {bot_id}:{random_string}.
"Telegram Integration Error: HTTPS url must be provided": This error indicates an internal issue with webhook URL generation. Contact support if you encounter this error.
"Telegram Integration Error: Certificate is invalid": Ensure you're using the official ChatBotKit API endpoint. Custom domains require proper SSL certificate configuration.
Setup succeeds but bot doesn't respond: Check that your connected ChatBotKit bot is properly configured and not in a disabled state. Also verify your bot token permissions allow receiving messages.
Webhook Security
Telegram webhooks are secured through several mechanisms:
-
HTTPS Only: Telegram only allows HTTPS webhook URLs, ensuring encrypted communication.
-
Token Authentication: Your bot token serves as authentication, and only Telegram servers with your token can send webhooks.
-
Update Filtering: ChatBotKit validates incoming webhooks to ensure they match the expected format and content before processing.
For detailed information about Telegram's webhook system, refer to the official Telegram Bot API documentation.
Updating a Telegram Integration
Modify the configuration of an existing Telegram integration to adjust settings, change the connected bot, or update operational parameters. Updates are applied immediately and affect how your integration processes incoming messages.
To update a Telegram integration, send a POST request with the updated configuration:
POST /api/v1/integration/telegram/{telegramIntegrationId}/update Content-Type: application/json { "name": "Updated Support Bot", "contactCollection": false, "sessionDuration": 7200000, "attachments": true }http
You can update any of the configuration options available during creation, including the bot token if you need to reconnect to a different Telegram bot.
Updatable Fields
- name: Change the display name for easier identification
- description: Update internal documentation
- botId: Switch to a different ChatBotKit bot
- blueprintId: Link or unlink from blueprints
- botToken: Replace with a new Telegram bot token
- contactCollection: Enable or disable contact collection
- sessionDuration: Adjust session timeout (milliseconds, max 30 days)
- attachments: Toggle file attachment support
- meta: Update custom metadata
Partial Updates
You only need to include the fields you want to change. Omitted fields will retain their current values. This allows for efficient partial updates without needing to send the entire configuration.
Important Considerations
Bot Token Changes: If you update the bot token, you must run the setup endpoint again to reconfigure the webhook with Telegram. The old webhook configuration will no longer be valid with the new token.
Session Duration: Changing session duration only affects new conversations. Existing sessions will continue with their original timeout settings until they expire naturally.
Contact Collection: Enabling contact collection on an existing integration will only apply to new conversations. Historical conversations are not affected.
After updating critical settings like the bot token, remember to call the setup endpoint to ensure the webhook is properly configured with Telegram's servers. Without this step, your integration may stop receiving messages.
Webhook Event Handling
The webhook endpoint is the receiver for all messages and events from Telegram. When users interact with your Telegram bot, Telegram sends these interactions to the webhook URL configured during setup. This endpoint processes incoming events and routes them to your ChatBotKit bot for intelligent response generation.
This endpoint is called automatically by Telegram's servers - you do not need to call it directly. However, understanding its behavior helps with integration troubleshooting and advanced customization scenarios.
Webhook URL Format
POST /api/v1/integration/telegram/{telegramIntegrationId}/webhook
Telegram sends POST requests to this URL with JSON payloads containing message and event data. The webhook is automatically configured when you call the setup endpoint.
Supported Event Types
The webhook processes these Telegram update types:
- message: Standard messages sent directly to your bot in private chats
- business_message: Messages sent through Telegram Business accounts
Other event types (edited messages, inline queries, callback queries) are currently not processed but may be acknowledged to prevent Telegram errors.
Message Processing Logic
When a message arrives, the webhook applies several filters:
Bot Message Filter: Messages sent by other bots are automatically ignored to prevent bot-to-bot loops and reduce unnecessary processing.
Group Chat Mentions: In group chats, the bot only responds when explicitly
mentioned using @botname. This prevents the bot from responding to every
message in the group and keeps conversations focused.
Command Filtering: Messages starting with / (Telegram commands) are
currently filtered out. This is because command handling often requires
specialized logic and may be enhanced in future updates.
Private Chats: In one-on-one conversations, all messages are processed without requiring mentions, providing a seamless chat experience.
Group Chat Behavior
To use your Telegram bot in group chats:
-
Add Bot to Group: Add your bot to the Telegram group using the group settings or directly through the bot's username.
-
Make Bot Admin: Set the bot as a group administrator to ensure it receives all messages. Without admin privileges, the bot may not receive certain message types.
-
Mention the Bot: Users must mention the bot using
@botnamefollowed by their message for the bot to respond. For example:@supportbot How do I reset my password?
This mention requirement prevents the bot from responding to unrelated conversations and allows multiple bots to coexist in the same group.
Event Processing Flow
When a valid message passes all filters:
-
Validation: The webhook validates the integration exists and extracts message details from the Telegram payload.
-
Queue Dispatch: The message is queued for asynchronous processing, ensuring fast webhook response times and preventing Telegram timeouts.
-
Bot Processing: The queued event is processed by your ChatBotKit bot, which generates an appropriate response using configured AI models.
-
Response Delivery: The bot's response is sent back to Telegram through the Telegram API, appearing as a message from your bot.
Debugging Webhook Issues
Bot not responding in private chats: Verify the webhook is properly setup by calling the setup endpoint. Check that your integration exists and the bot token is valid.
Bot not responding in groups: Ensure the bot is added to the group as an
administrator. Verify users are mentioning the bot correctly with @botname.
Messages delayed or missing: High message volumes can cause queueing. This is normal behavior. If delays persist, check your account's rate limits and processing capacity.
Command messages ignored: Messages starting with / are currently filtered.
If you need command support, consider using custom bot logic to handle
specific command patterns.
Telegram Business Support
The webhook supports Telegram Business messages, allowing businesses to use ChatBotKit bots for customer communication through Telegram's business features. Business messages are processed identically to regular messages with the same filtering and routing logic.
For more details about Telegram's webhook mechanism and message structure, see the Telegram Bot API documentation.
Listing Telegram Integrations
You can retrieve a list of all your Telegram integrations to manage multiple bots or review existing configurations. The list endpoint supports pagination and filtering to help you efficiently manage your integrations.
To list your Telegram integrations, send a GET request:
GET /api/v1/integration/telegram/listhttp
The response includes all your Telegram integrations with their configuration details, excluding sensitive information like bot tokens for security reasons.
Pagination Parameters
- cursor: For paginated results, use the cursor from the previous response
- order: Sort order -
asc(ascending) ordesc(descending, default) - take: Number of items to retrieve per page
Filtering Options
You can filter the list using query parameters:
- blueprintId: Filter integrations linked to a specific blueprint
- meta: Filter by custom metadata fields
Example with filtering:
GET /api/v1/integration/telegram/list?blueprintId=blueprint_xxxxx&order=asc&take=10http
Each integration in the response includes basic information (name, description, creation date), configuration options (contact collection, session duration, attachments), and resource links (bot ID, blueprint ID). The bot token is intentionally excluded from list responses for security purposes.
This endpoint is useful for building management interfaces, monitoring active integrations, or performing bulk operations across multiple Telegram bots.