> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chatbotplatform.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Conversation Messages API

> Programmatic access to conversation history and message management

The Conversation Messages API allows you to programmatically access, create, and manage messages within conversations. This is essential for async replies, custom integrations, and conversation analytics.

## Overview

The API provides endpoints for:

* Listing conversations for a bot
* Retrieving conversation details
* Getting message history
* Sending messages to conversations
* Updating conversation metadata

## Authentication

All API requests require authentication using a Bearer token:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

Get your API key from the dashboard under **Settings → API Keys**.

Keep your API key secure. Never expose it in client-side code or public repositories.

## Base URL

```
https://api.chatbotplatform.io/v1
```

## Endpoints

### List Conversations

Get all conversations for a bot.

**Endpoint**: `GET /bots/{bot_id}/conversations`

**Parameters**:

| Parameter | Type | Description | Default |
| - | - | - | - |
| `limit` | integer | Number of conversations per page | 25 |
| `offset` | integer | Pagination offset | 0 |
| `status` | string | Filter by status: `active`, `archived` | all |
| `channel` | string | Filter by channel type | all |

> [accordion] List conversations
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/bots/bot_123/conversations \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/bots/bot_123/conversations', {
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY'
> >   }
> > });
> >
> > const { data, pagination } = await response.json();
> > console.log(`Found ${data.length} conversations`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > use Illuminate\Support\Facades\Http;
> >
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/bots/bot_123/conversations');
> >
> > $conversations = $response->json('data');
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > import requests
> >
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/bots/bot_123/conversations',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > data = response.json()
> > conversations = data['data']
> > print(f"Found {len(conversations)} conversations")
> > ```
>
> **Response**:
>
> ```json theme={null}
> {
>   "data": [
>     {
>       "id": "conv_abc123",
>       "bot_id": "bot_123",
>       "user": {
>         "id": "user_456",
>         "platform": "telegram",
>         "name": "John Doe"
>       },
>       "channel": {
>         "id": "chan_789",
>         "type": "telegram",
>         "name": "Telegram Channel"
>       },
>       "last_message_at": "2024-01-15T10:30:00Z",
>       "message_count": 15,
>       "created_at": "2024-01-14T09:00:00Z",
>       "updated_at": "2024-01-15T10:30:00Z"
>     }
>   ],
>   "pagination": {
>     "total": 100,
>     "limit": 25,
>     "offset": 0,
>     "has_more": true
>   }
> }
> ```

> [accordion] List with filters
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl "https://api.chatbotplatform.io/v1/bots/bot_123/conversations?channel=telegram&limit=50" \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const params = new URLSearchParams({
> >   channel: 'telegram',
> >   limit: '50',
> >   offset: '0'
> > });
> >
> > const response = await fetch(
> >   `https://api.chatbotplatform.io/v1/bots/bot_123/conversations?${params}`,
> >   {
> >     headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
> >   }
> > );
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/bots/bot_123/conversations', [
> >         'channel' => 'telegram',
> >         'limit' => 50,
> >         'offset' => 0
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/bots/bot_123/conversations',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     params={'channel': 'telegram', 'limit': 50, 'offset': 0}
> > )
> > ```

### Get Conversation

Retrieve a specific conversation with details.

**Endpoint**: `GET /conversations/{conversation_id}`

> [accordion] Get conversation details
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/conversations/conv_abc123 \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123', {
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY'
> >   }
> > });
> >
> > const conversation = await response.json();
> > console.log(`Conversation with ${conversation.user.name}`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/conv_abc123');
> >
> > $conversation = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > conversation = response.json()
> > print(f"Conversation with {conversation['user']['name']}")
> > ```
>
> **Response**:
>
> ```json theme={null}
> {
>   "id": "conv_abc123",
>   "bot_id": "bot_123",
>   "user": {
>     "id": "user_456",
>     "platform": "telegram",
>     "platform_user_id": "123456789",
>     "name": "John Doe",
>     "username": "johndoe",
>     "first_name": "John",
>     "last_name": "Doe"
>   },
>   "channel": {
>     "id": "chan_789",
>     "type": "telegram",
>     "name": "Telegram Channel"
>   },
>   "metadata": {
>     "chat_id": "123456789",
>     "is_group": false
>   },
>   "last_message_at": "2024-01-15T10:30:00Z",
>   "message_count": 15,
>   "created_at": "2024-01-14T09:00:00Z",
>   "updated_at": "2024-01-15T10:30:00Z"
> }
> ```

### List Messages

Get message history for a conversation.

**Endpoint**: `GET /conversations/{conversation_id}/messages`

**Parameters**:

| Parameter | Type | Description | Default |
| - | - | - | - |
| `limit` | integer | Number of messages per page | 50 |
| `offset` | integer | Pagination offset | 0 |
| `order` | string | `asc` (oldest first) or `desc` (newest first) | `asc` |

> [accordion] Get message history
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY"
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', {
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY'
> >   }
> > });
> >
> > const { data } = await response.json();
> > console.log(`${data.length} messages in conversation`);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->get('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages');
> >
> > $messages = $response->json('data');
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.get(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'}
> > )
> >
> > messages = response.json()['data']
> > print(f"{len(messages)} messages in conversation")
> > ```
>
> **Response**:
>
> ```json theme={null}
> {
>   "data": [
>     {
>       "id": "msg_123",
>       "conversation_id": "conv_abc123",
>       "role": "user",
>       "content": "What's the weather like?",
>       "metadata": {
>         "message_id": "456",
>         "platform": "telegram"
>       },
>       "created_at": "2024-01-15T10:30:00Z"
>     },
>     {
>       "id": "msg_124",
>       "conversation_id": "conv_abc123",
>       "role": "assistant",
>       "content": "The weather today is sunny with a high of 72°F.",
>       "metadata": {
>         "model": "gpt-4",
>         "tokens": 150
>       },
>       "created_at": "2024-01-15T10:30:05Z"
>     }
>   ],
>   "pagination": {
>     "total": 15,
>     "limit": 50,
>     "offset": 0,
>     "has_more": false
>   }
> }
> ```

> [accordion] Get paginated messages
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > // Get all messages with pagination
> > async function getAllMessages(conversationId) {
> >   const allMessages = [];
> >   let offset = 0;
> >   const limit = 100;
> >   let hasMore = true;
> >
> >   while (hasMore) {
> >     const response = await fetch(
> >       `https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages?limit=${limit}&offset=${offset}`,
> >       {
> >         headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
> >       }
> >     );
> >
> >     const { data, pagination } = await response.json();
> >     allMessages.push(...data);
> >
> >     hasMore = pagination.has_more;
> >     offset += limit;
> >   }
> >
> >   return allMessages;
> > }
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > def get_all_messages(conversation_id):
> >     all_messages = []
> >     offset = 0
> >     limit = 100
> >     has_more = True
> >
> >     while has_more:
> >         response = requests.get(
> >             f'https://api.chatbotplatform.io/v1/conversations/{conversation_id}/messages',
> >             headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >             params={'limit': limit, 'offset': offset}
> >         )
> >
> >         data = response.json()
> >         all_messages.extend(data['data'])
> >
> >         has_more = data['pagination']['has_more']
> >         offset += limit
> >
> >     return all_messages
> > ```

### Send Message

Send a message to a conversation (for async replies or custom integrations).

**Endpoint**: `POST /conversations/{conversation_id}/messages`

**Body Parameters**:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `content` | string | Yes | Message content |
| `role` | string | Yes | `user` or `assistant` |
| `metadata` | object | No | Custom metadata |

> [accordion] Send assistant message
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "content": "Here is your completed report.",
> >     "role": "assistant",
> >     "metadata": {
> >       "processing_time": 5000,
> >       "custom_field": "value"
> >     }
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', {
> >   method: 'POST',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     content: 'Here is your completed report.',
> >     role: 'assistant',
> >     metadata: {
> >       processing_time: 5000,
> >       custom_field: 'value'
> >     }
> >   })
> > });
> >
> > const message = await response.json();
> > console.log('Message sent:', message.id);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', [
> >         'content' => 'Here is your completed report.',
> >         'role' => 'assistant',
> >         'metadata' => [
> >             'processing_time' => 5000,
> >             'custom_field' => 'value'
> >         ]
> >     ]);
> >
> > $message = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.post(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'content': 'Here is your completed report.',
> >         'role': 'assistant',
> >         'metadata': {
> >             'processing_time': 5000,
> >             'custom_field': 'value'
> >         }
> >     }
> > )
> >
> > message = response.json()
> > print(f"Message sent: {message['id']}")
> > ```
>
> **Response**:
>
> ```json theme={null}
> {
>   "id": "msg_125",
>   "conversation_id": "conv_abc123",
>   "role": "assistant",
>   "content": "Here is your completed report.",
>   "metadata": {
>     "processing_time": 5000,
>     "custom_field": "value"
>   },
>   "created_at": "2024-01-15T10:35:00Z"
> }
> ```

> [accordion] Send user message (for testing)
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "content": "This is a test message",
> >     "role": "user"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > // Simulate a user message (for testing)
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', {
> >   method: 'POST',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     content: 'This is a test message',
> >     role: 'user'
> >   })
> > });
> > ```
>
> Sending user messages via API is typically for testing. In production, users send messages through channels (Telegram, Slack, etc.).

### Update Conversation

Update conversation metadata.

**Endpoint**: `PATCH /conversations/{conversation_id}`

**Body Parameters**:

| Parameter | Type | Description |
| - | - | - |
| `metadata` | object | Custom metadata to merge |
| `status` | string | `active` or `archived` |

> [accordion] Update conversation metadata
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X PATCH https://api.chatbotplatform.io/v1/conversations/conv_abc123 \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "metadata": {
> >       "customer_tier": "premium",
> >       "support_ticket": "TICKET-123"
> >     }
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123', {
> >   method: 'PATCH',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     metadata: {
> >       customer_tier: 'premium',
> >       support_ticket: 'TICKET-123'
> >     }
> >   })
> > });
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->patch('https://api.chatbotplatform.io/v1/conversations/conv_abc123', [
> >         'metadata' => [
> >             'customer_tier' => 'premium',
> >             'support_ticket' => 'TICKET-123'
> >         ]
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.patch(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'metadata': {
> >             'customer_tier': 'premium',
> >             'support_ticket': 'TICKET-123'
> >         }
> >     }
> > )
> > ```

> [accordion] Archive a conversation
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X PATCH https://api.chatbotplatform.io/v1/conversations/conv_abc123 \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "status": "archived"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123', {
> >   method: 'PATCH',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({ status: 'archived' })
> > });
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > Http::withToken('YOUR_API_KEY')
> >     ->patch('https://api.chatbotplatform.io/v1/conversations/conv_abc123', [
> >         'status' => 'archived'
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > requests.patch(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={'status': 'archived'}
> > )
> > ```

## Use Cases

### Async Message Delivery

Send a final response after long processing:

```javascript theme={null}
// After webhook returns immediate response
async function sendFinalResult(conversationId, result) {
  await fetch(`https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      content: `✅ Processing complete! ${result}`,
      role: 'assistant'
    })
  });
}
```

See [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md) for detailed guide.

### Conversation Analytics

Analyze conversation patterns:

```python theme={null}
def analyze_conversations(bot_id):
    # Get all conversations
    response = requests.get(
        f'https://api.chatbotplatform.io/v1/bots/{bot_id}/conversations',
        headers={'Authorization': f'Bearer {API_KEY}'},
        params={'limit': 1000}
    )

    conversations = response.json()['data']

    # Analyze
    total_messages = sum(c['message_count'] for c in conversations)
    avg_length = total_messages / len(conversations) if conversations else 0

    print(f"Total conversations: {len(conversations)}")
    print(f"Average messages per conversation: {avg_length:.1f}")
```

### Export Conversations

Export conversation history for backup or analysis:

```javascript theme={null}
async function exportConversation(conversationId) {
  const messages = await getAllMessages(conversationId);

  const csv = messages.map(m =>
    `${m.created_at},${m.role},${m.content.replace(/,/g, ';')}`
  ).join('\n');

  return `timestamp,role,content\n${csv}`;
}
```

### Custom Bot Behaviors

Implement custom logic based on conversation state:

```javascript theme={null}
async function customReply(conversationId, userMessage) {
  // Get conversation history
  const response = await fetch(
    `https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const { data: messages } = await response.json();

  // Custom logic based on history
  if (messages.length === 1) {
    // First message - send welcome
    await sendMessage(conversationId, "Welcome! How can I help you today?");
  } else if (messages.length > 20) {
    // Long conversation - offer to start fresh
    await sendMessage(conversationId, "Would you like to start a new conversation?");
  }
}
```

## Rate Limits

| Endpoint | Rate Limit |
| - | - |
| List conversations | 100 requests/minute |
| Get conversation | 200 requests/minute |
| List messages | 200 requests/minute |
| Send message | 60 requests/minute |
| Update conversation | 100 requests/minute |

Exceeding rate limits results in `429 Too Many Requests` responses. Implement exponential backoff for retries.

## Error Responses

| Status Code | Meaning | Action |
| - | - | - |
| `400` | Bad Request | Check request format |
| `401` | Unauthorized | Verify API key |
| `404` | Not Found | Check conversation ID |
| `429` | Rate Limited | Implement backoff |
| `500` | Server Error | Retry after delay |

**Example Error Response**:

```json theme={null}
{
  "error": "Conversation not found",
  "code": "conversation_not_found",
  "status": 404
}
```

## Best Practices

> [card] Cache API Keys
>
> Load API keys once, not per request

> [card] Handle Pagination
>
> Always handle pagination for large datasets

> [card] Implement Retries
>
> Use exponential backoff for failed requests

> [card] Validate IDs
>
> Always validate conversation IDs exist

Use idempotency keys when sending messages to prevent duplicates during retries.

> [card] [Complete API Reference](https://app.chatbotplatform.io/openapi)
>
> View the full API specification with all endpoints, parameters, and response schemas.

## Next Steps

> [card] [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md)
>
> Implement async message delivery

> [card] [Webhook Payload](https://docs.chatbotplatform.io/bots/integrations/webhook-payload.md)
>
> Understand webhook format

> [card] [Conversation History](https://docs.chatbotplatform.io/bots/conversations/history.md)
>
> Configure history settings


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.