> ## 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.

# Webhook Payload Reference

> Complete webhook request and response format specification

This page provides a complete reference for the webhook payload format sent to your integration and the expected response format.

## Request Payload

When a user sends a message, your integration receives a POST request with this structure:

### Complete Example

```json theme={null}
{
  "messages": [
    {
      "role": "user",
      "content": "What's the weather like today?"
    },
    {
      "role": "assistant",
      "content": "I'll check the weather for you."
    },
    {
      "role": "user",
      "content": "Thanks!"
    }
  ],
  "conversation_id": "conv_abc123def456",
  "user": {
    "id": "user_789xyz",
    "platform": "telegram",
    "platform_user_id": "123456789",
    "name": "John Doe",
    "username": "johndoe",
    "first_name": "John",
    "last_name": "Doe"
  },
  "bot": {
    "id": "bot_456abc",
    "name": "Weather Bot",
    "description": "A helpful weather assistant"
  },
  "channel": {
    "id": "chan_xyz789",
    "type": "telegram",
    "name": "Telegram Channel"
  },
  "metadata": {
    "channel": "telegram",
    "chat_id": "123456789",
    "message_id": "456",
    "thread_id": null,
    "is_group": false,
    "group_name": null,
    "timestamp": "2024-01-15T10:30:00Z"
  }
}
```

## Payload Fields

### messages

Array of conversation messages following the OpenAI/Anthropic format.

**Type**: `Array<Message>`

**Message Object**:

```json theme={null}
{
  "role": "user" | "assistant" | "system",
  "content": "string"
}
```

**Roles**:

* `user`: Messages from the end user
* `assistant`: Previous responses from your bot
* `system`: System instructions (if configured)

**Context Window**: The number of messages included is controlled by your bot's `history_limit` setting (default: 10).

**Order**: Messages are ordered chronologically, oldest first.

### conversation\_id

Unique identifier for this conversation.

**Type**: `string`

**Format**: `conv_` followed by alphanumeric characters

**Example**: `"conv_abc123def456"`

**Usage**:

* Track conversations across messages
* Store user context or state
* Retrieve conversation history via API

### user

Information about the user sending the message.

**Type**: `object`

**Fields**:

| Field | Type | Description | Example |
| - | - | - | - |
| `id` | string | Internal user ID | `"user_789xyz"` |
| `platform` | string | Platform name | `"telegram"`, `"slack"`, `"discord"` |
| `platform_user_id` | string | Platform-specific user ID | `"123456789"` |
| `name` | string | User's display name | `"John Doe"` |
| `username` | string | Platform username | `"johndoe"` |
| `first_name` | string | User's first name | `"John"` |
| `last_name` | string | User's last name | `"Doe"` |

**Note**: Not all fields are available on all platforms. For example, Slack may not provide `username`.

### bot

Information about your bot.

**Type**: `object`

**Fields**:

| Field | Type | Description | Example |
| - | - | - | - |
| `id` | string | Bot ID | `"bot_456abc"` |
| `name` | string | Bot name | `"Weather Bot"` |
| `description` | string | Bot description | `"A helpful weather assistant"` |

**Usage**:

* Identify which bot received the message (if you manage multiple)
* Include bot name in responses
* Customize behavior per bot

### channel

Information about the channel that received the message.

**Type**: `object`

**Fields**:

| Field | Type | Description | Example |
| - | - | - | - |
| `id` | string | Channel ID | `"chan_xyz789"` |
| `type` | string | Platform type | `"telegram"`, `"slack"`, `"discord"` |
| `name` | string | Channel name | `"Telegram Channel"` |

### metadata

Platform-specific metadata and message context.

**Type**: `object`

**Common Fields**:

| Field | Type | Description | Example |
| - | - | - | - |
| `channel` | string | Platform name | `"telegram"` |
| `chat_id` | string | Chat/channel identifier | `"123456789"` |
| `message_id` | string | Platform message ID | `"456"` |
| `thread_id` | string \| null | Thread ID (Slack) | `"1234567890.123456"` |
| `is_group` | boolean | Is this a group chat? | `true` or `false` |
| `group_name` | string \| null | Group chat name | `"Support Team"` |
| `timestamp` | string | ISO 8601 timestamp | `"2024-01-15T10:30:00Z"` |

**Platform-Specific Metadata**:

**Telegram**:

```json theme={null}
{
  "chat_id": "123456789",
  "message_id": "456",
  "is_group": true,
  "group_name": "Customer Support",
  "chat_type": "group"
}
```

**Slack**:

```json theme={null}
{
  "channel_id": "C01234ABC",
  "thread_ts": "1234567890.123456",
  "message_ts": "1234567891.123456",
  "team_id": "T01234ABC",
  "is_thread": true
}
```

**Discord** (Coming Soon):

```json theme={null}
{
  "channel_id": "123456789012345678",
  "message_id": "987654321098765432",
  "guild_id": "111222333444555666",
  "guild_name": "My Server"
}
```

## Response Format

Your webhook must return JSON with a `content` field.

### Simple Response

The minimum required response:

```json theme={null}
{
  "content": "The weather today is sunny with a high of 72°F."
}
```

**Required**:

* `content` (string): The message to send to the user

### Response with Metadata

Include optional metadata for logging and analytics:

```json theme={null}
{
  "content": "The weather today is sunny with a high of 72°F.",
  "metadata": {
    "model": "gpt-4",
    "tokens": 150,
    "processing_time_ms": 1250,
    "temperature": 0.7,
    "finish_reason": "stop",
    "custom_field": "any_value"
  }
}
```

**Metadata fields are optional and can include**:

* `model`: AI model used
* `tokens`: Token count
* `processing_time_ms`: Processing duration
* Any custom fields for your analytics

**Note**: Metadata is stored but not sent to the user.

### Error Response

Return appropriate HTTP status codes for errors:

```json theme={null}
{
  "error": "Rate limit exceeded. Please try again in 60 seconds.",
  "code": "rate_limit",
  "retry_after": 60
}
```

**HTTP Status Codes**:

| Code | Meaning | When to Use |
| - | - | - |
| `200` | Success | Normal response |
| `400` | Bad Request | Invalid payload received |
| `401` | Unauthorized | Authentication failed |
| `429` | Rate Limited | Too many requests |
| `500` | Server Error | Internal error in your backend |
| `503` | Service Unavailable | Temporary outage |

Always return valid JSON. If your backend returns invalid JSON or HTML, the platform cannot process the response.

## Special Response Types

### Async Processing

For long-running operations, return an immediate acknowledgment:

```json theme={null}
{
  "content": "I'm processing your request. This may take a moment...",
  "async": true
}
```

Then send the final response using the Conversation Messages API (see [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md)).

### Empty Response

To acknowledge a message without responding:

```json theme={null}
{
  "content": ""
}
```

Or return `204 No Content` status with no body.

**Use cases**:

* Commands that don't need a response
* Silent processing
* Reaction-only interactions (future feature)

## Platform-Specific Considerations

### Telegram

**Character Limits**:

* Maximum message length: 4096 characters
* Messages longer than this will be truncated

**Markdown Support**:

```json theme={null}
{
  "content": "*Bold* _italic_ `code` [link](https://example.com)",
  "parse_mode": "Markdown"
}
```

**Media Support** (Coming Soon):

```json theme={null}
{
  "content": "Here's the image you requested",
  "attachments": [
    {
      "type": "photo",
      "url": "https://example.com/image.jpg"
    }
  ]
}
```

### Slack

**Character Limits**:

* Maximum message length: 40,000 characters

**Blocks and Attachments** (Future):

```json theme={null}
{
  "content": "Simple text",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "Rich *formatted* message"
      }
    }
  ]
}
```

**Thread Awareness**:

* Responses automatically sent to the same thread
* No special handling needed

### Discord

**Character Limits**:

* Maximum message length: 2000 characters

**Embed Support** (Coming Soon):

```json theme={null}
{
  "content": "Check out this embed",
  "embeds": [
    {
      "title": "Embed Title",
      "description": "Embed description",
      "color": 3447003
    }
  ]
}
```

## Example Integrations

### OpenAI Proxy

```javascript theme={null}
// Convert Chatbot Platform payload to OpenAI format
app.post('/webhook/openai', async (req, res) => {
  const { messages, user, conversation_id } = req.body;

  const openaiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: messages,
      user: conversation_id
    })
  });

  const data = await openaiResponse.json();

  res.json({
    content: data.choices[0].message.content,
    metadata: {
      model: data.model,
      tokens: data.usage.total_tokens,
      finish_reason: data.choices[0].finish_reason
    }
  });
});
```

### Anthropic Proxy

```python theme={null}
# Convert to Anthropic format
@app.route('/webhook/anthropic', methods=['POST'])
def anthropic_webhook():
    data = request.json
    messages = data['messages']

    # Separate system messages
    system_msg = next((m for m in messages if m['role'] == 'system'), None)
    chat_messages = [m for m in messages if m['role'] != 'system']

    response = anthropic_client.messages.create(
        model='claude-3-5-sonnet-20241022',
        max_tokens=1024,
        system=system_msg['content'] if system_msg else '',
        messages=chat_messages
    )

    return jsonify({
        'content': response.content[0].text,
        'metadata': {
            'model': response.model,
            'tokens': response.usage.input_tokens + response.usage.output_tokens,
            'stop_reason': response.stop_reason
        }
    })
```

### Custom Backend

```php theme={null}
// Custom Laravel integration
Route::post('/webhook/custom', function (Request $request) {
    $messages = $request->input('messages');
    $user = $request->input('user');
    $conversationId = $request->input('conversation_id');

    // Your custom logic
    $response = MyAI::generateResponse($messages, $user);

    return response()->json([
        'content' => $response->text,
        'metadata' => [
            'conversation_id' => $conversationId,
            'user_id' => $user['id'],
            'custom_metric' => $response->customMetric
        ]
    ]);
});
```

## Security

### Validating Requests

Verify requests come from Chatbot Platform:

**Option 1: API Key Header**

```javascript theme={null}
const apiKey = req.headers['x-api-key'];
if (apiKey !== process.env.EXPECTED_API_KEY) {
  return res.status(401).json({ error: 'Unauthorized' });
}
```

**Option 2: Webhook Signature** (Future)

```javascript theme={null}
const signature = req.headers['x-webhook-signature'];
const payload = JSON.stringify(req.body);
const expectedSignature = crypto
  .createHmac('sha256', process.env.WEBHOOK_SECRET)
  .update(payload)
  .digest('hex');

if (signature !== expectedSignature) {
  return res.status(401).json({ error: 'Invalid signature' });
}
```

### Best Practices

> [card] Use HTTPS
>
> Always use HTTPS endpoints to encrypt data in transit

> [card] Validate Input
>
> Sanitize and validate all incoming data

> [card] Rate Limiting
>
> Implement rate limiting on your webhook endpoint

> [card] Timeout Handling
>
> Return responses within configured timeout

## Testing

### Manual Testing with cURL

```bash theme={null}
curl -X POST https://your-webhook.com/chat \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "Hello!"}
    ],
    "conversation_id": "conv_test123",
    "user": {
      "id": "user_test",
      "platform": "telegram",
      "name": "Test User"
    },
    "bot": {
      "id": "bot_test",
      "name": "Test Bot"
    },
    "metadata": {
      "channel": "telegram",
      "chat_id": "123",
      "message_id": "456"
    }
  }'
```

### Expected Response

```json theme={null}
{
  "content": "Hello! How can I help you today?"
}
```

## Troubleshooting

### Invalid JSON Response

**Problem**: Bot sends error message to user

**Solution**:

* Ensure response is valid JSON
* Check `content` field is present and is a string
* Look for encoding issues (use UTF-8)
* Test with JSON validator

### Timeout Errors

**Problem**: Requests timeout before completion

**Solution**:

* Increase timeout in integration settings
* Optimize backend for faster responses
* Consider async processing for long operations
* Check network latency

### Missing Fields

**Problem**: Expected fields not in payload

**Solution**:

* Check platform support for field
* Verify channel is properly configured
* Review platform-specific limitations
* Handle missing fields gracefully

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

## Next Steps

> [card] [Webhook Setup](https://docs.chatbotplatform.io/bots/integrations/webhook-setup)
>
> Configure your webhook integration

> [card] [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md)
>
> Handle long-running operations

> [card] [Custom Headers](https://docs.chatbotplatform.io/bots/integrations/custom-headers)
>
> Add authentication headers


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