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

# Pre-Hook Events

> Implement custom moderation and control workflows with real-time event interception and processing

Gain granular control over user actions with pre-hook events that allow you to intercept, validate, and modify user interactions before they're processed. Perfect for implementing custom moderation rules, content filtering, and access control policies.

> **[Real-time Interception](#how-it-works)**
>
> Intercept user actions in real-time before they're processed

> **[Custom Rules](#implementation-guide)**
>
> Build custom validation and moderation logic tailored to your needs

> **[Webhook Integration](#webhook-configuration)**
>
> Receive events via webhooks and respond with custom actions

> **[Event Catalog](#supported-events)**
>
> Complete list of interceptable events and their data

## Overview

Pre-hook events enable you to create sophisticated moderation and control systems by intercepting user actions before they're executed. This allows for:

> **Custom Moderation**
>
> * **Content Filtering**: Analyze and modify content before publication
> * **User Behavior Control**: Restrict access based on custom criteria
> * **Real-time Validation**: Validate data against business rules
> * **Automated Responses**: Implement graduated response systems

> **Advanced Use Cases**
>
> * **Spam Prevention**: Block suspicious posting patterns
> * **Content Enhancement**: Auto-correct or enrich user content
> * **Access Control**: Implement channel-specific permission systems
> * **Analytics Injection**: Add tracking data to user actions

> [!NOTE]
>
> **Enterprise Feature**: Pre-hook events are available for customers on the Max plan. Contact our sales team to upgrade your plan.

## How It Works

Pre-hook events create a validation layer between user actions and their execution:

```mermaid theme={null}
graph TB
    A[User Action] --> B[Pre-Hook Event Triggered]
    B --> C[Webhook Called]
    C --> D{Your Custom Logic}
    
    D -->|Allow| E[Action Proceeds]
    D -->|Deny| F[Action Blocked]
    D -->|Modify| G[Modified Action Proceeds]
    D -->|Timeout| H[Default Action Applied]
    
    E --> I[Normal Flow Continues]
    F --> J[Error Response to User]
    G --> I
    H --> K[Fallback Behavior]
    
    style E fill:#e8f5e8
    style F fill:#ffebee
    style G fill:#e3f2fd
    style H fill:#fff3e0
```

### Response Types

Your webhook endpoint must respond with one of these actions:

> **Allow**
>
> ```json theme={null}
> { "action": "allow" }
> ```
>
> Allow the action to proceed without modification.

> **Allow with Modification**
>
> ```json theme={null}
> {
>   "action": "allow",
>   "data": {
>     "modified_field": "new_value"
>   }
> }
> ```
>
> Allow the action but modify the data before processing.

> **Deny**
>
> ```json theme={null}
> {
>   "action": "deny",
>   "message": "Action denied: Custom reason"
> }
> ```
>
> Block the action and return an error message to the user.

## Getting Started

**1. Enable Pre-Hook Events**

Configure pre-hook events through the [Network Settings API](https://api-docs.amity.co/#/Network%20Setting/get_api_v3_network_settings_prehook).

**2. Set Up Webhook Endpoint**

Create an HTTPS endpoint to receive and process pre-hook events.

**3. Configure Event Types**

Specify which events you want to intercept and process.

**4. Test & Monitor**

Test your webhook with sample events and monitor response times.

### Configuration

**API Configuration**

```json Enable Pre-Hook Events theme={null}
PUT /api/v3/network/settings/prehook

{
  "enabled": true,
  "callbackUrl": "https://your-app.com/webhooks/prehook",
  "defaultAction": "allow",
  "events": [
    "message.shouldCreate",
    "message.shouldUpdate",
    "post.shouldCreate"
  ]
}
```

```json Get Current Configuration theme={null}
GET /api/v3/network/settings/prehook

Response:
{
  "enabled": true,
  "callbackUrl": "https://your-app.com/webhooks/prehook",
  "defaultAction": "allow",
  "timeout": 3000,
  "events": ["message.shouldCreate"]
}
```

**Webhook Security**

```javascript Signature Verification theme={null}
const crypto = require('crypto');

function verifySignature(payload, signature, secretKey) {
  const expectedSignature = crypto
    .createHmac('sha256', secretKey)
    .update(JSON.stringify(payload))
    .digest('hex');
  
  return signature === expectedSignature;
}

// Verify incoming webhook
if (!verifySignature(payload, headers['x-signature'], secretKey)) {
  return { status: 401, body: 'Invalid signature' };
}
```

```python Python Verification theme={null}
import hmac
import hashlib
import json

def verify_signature(payload, signature, secret_key):
  expected_signature = hmac.new(
    secret_key.encode(),
    json.dumps(payload).encode(),
    hashlib.sha256
  ).hexdigest()
  
  return signature == expected_signature
```

## Supported Events

> **Message Events**
>
> | Event | Triggered When | Available Data |
> | - | - | - |
> | `message.shouldCreate` | User sends a message | Message content, channel ID, sender |
> | `message.shouldUpdate` | User edits a message | Updated content, original message |
> | `message.shouldFlag` | User flags a message | Message data, flag reason |
> | `message.shouldUnflag` | User removes flag | Message data, flag count |
>
> **Example Payload:**
>
> ```json theme={null}
> {
>   "eventName": "message.shouldCreate",
>   "data": {
>     "text": "Hello world!",
>     "channelId": "ch_123",
>     "attachments": [],
>     "metadata": {}
>   },
>   "actor": {
>     "_id": "user_456",
>     "userId": "user_456"
>   }
> }
> ```

> **Channel Events**
>
> | Event | Triggered When | Available Data |
> | - | - | - |
> | `channel.shouldCreate` | User creates channel | Channel data, creator |
> | `channel.shouldJoin` | User joins channel | Channel ID, user data |
> | `channel.shouldLeave` | User leaves channel | Channel ID, user data |
> | `channel.shouldUpdate` | Channel is updated | Updated channel data |
>
> **Example Payload:**
>
> ```json theme={null}
> {
>   "eventName": "channel.shouldJoin",
>   "data": {
>     "channelId": "ch_123",
>     "channelType": "live",
>     "metadata": {}
>   },
>   "actor": {
>     "_id": "user_456",
>     "userId": "user_456"
>   }
> }
> ```

> **Post Events**
>
> | Event | Triggered When | Available Data |
> | - | - | - |
> | `post.shouldCreate` | User creates post | Post content, community |
> | `post.shouldUpdate` | User edits post | Updated content |
> | `post.shouldDelete` | User deletes post | Post ID, deletion reason |
> | `post.shouldFlag` | User flags post | Post data, flag details |
>
> **Example Payload:**
>
> ```json theme={null}
> {
>   "eventName": "post.shouldCreate",
>   "data": {
>     "text": "Check out this amazing feature!",
>     "communityId": "comm_789",
>     "attachments": [
>       {
>         "type": "image",
>         "url": "https://example.com/image.jpg"
>       }
>     ]
>   },
>   "actor": {
>     "_id": "user_456",
>     "userId": "user_456"
>   }
> }
> ```

## Best Practices

> **Performance & Reliability**
>
> * **Fast Response Times**: Keep webhook processing under 2 seconds
> * **Fail-Safe Design**: Default to "allow" on errors to prevent user disruption
> * **Async Processing**: For complex logic, respond quickly and process asynchronously
> * **Monitoring**: Track webhook response times and error rates
> * **Retry Logic**: Implement exponential backoff for external service calls

> **Security & Validation**
>
> * **Signature Verification**: Always verify webhook signatures
> * **HTTPS Only**: Use secure HTTPS endpoints for webhook URLs
> * **Input Validation**: Validate all incoming event data
> * **Rate Limiting**: Implement rate limiting on your webhook endpoint
> * **Logging**: Log all events for debugging and audit purposes

> **User Experience**
>
> * **Clear Error Messages**: Provide helpful feedback when denying actions
> * **Consistent Policies**: Apply rules consistently across all users
> * **Graceful Degradation**: Handle service outages gracefully
> * **Documentation**: Document your custom rules for transparency
> * **Appeal Process**: Provide ways for users to appeal automated decisions

## Troubleshooting

> **Common Issues**
>
> **Timeout Errors**
>
> * Ensure webhook responds within 3 seconds
> * Implement async processing for complex operations
> * Use caching for frequently accessed data
>
> **Invalid Signatures**
>
> * Verify webhook URL configuration
> * Check secret key configuration
> * Ensure payload is parsed correctly
>
> **Unexpected Behavior**
>
> * Check default action configuration
> * Verify event type filtering
> * Review webhook response format

> **Testing & Debugging**
>
> **Local Testing**
>
> ```bash theme={null}
> # Use ngrok for local webhook testing
> ngrok http 3000
>
> # Update webhook URL in console
> curl -X PUT "https://api.social.plus/api/v3/network/settings/prehook" \
>   -H "Authorization: Bearer YOUR_TOKEN" \
>   -d '{"callbackUrl": "https://your-ngrok-url.ngrok.io/webhook"}'
> ```
>
> **Monitoring Tools**
>
> * Set up alerts for webhook failures
> * Monitor response time metrics
> * Track action distribution (allow/deny/modify)
> * Use structured logging for better debugging

> [!WARNING]
>
> **Production Considerations**: Always test pre-hook events thoroughly in a staging environment before deploying to production. Failed or slow webhook responses can impact user experience.


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