# Custom Channels

Connect any messaging platform or communication tool to DM Champ using custom channels. This lets you bring messages from platforms like website live chat widgets, email systems, CRMs, or any other service into your DM Champ inbox - and respond to them with your AI bot.

***

## What Are Custom Channels?

Custom channels extend DM Champ beyond its built-in messaging platforms ([WhatsApp](https://help.dmchamp.com/messaging-channels/whatsapp-business), [SMS](https://help.dmchamp.com/messaging-channels/sms), [Instagram](https://help.dmchamp.com/messaging-channels/instagram-dms), [Messenger](https://help.dmchamp.com/messaging-channels/facebook-messenger)). With custom channels, you can:

* **Receive messages** from any external platform into DM Champ's unified inbox.
* **Send replies** from DM Champ back to your external platform automatically.
* **Use the AI bot** to respond to messages from any source.
* **Track all conversations** alongside your other channels in a single inbox.

This is ideal for businesses that use specialized communication tools, have a custom-built platform, or want all customer messages in one place.

> **Note:** Custom channels require some technical setup. If you or your team are not comfortable with technical integrations, you may want to ask your web developer or IT team to help with this section.

***

## How It Works

Custom channels work by passing messages back and forth between your external platform and DM Champ using **webhooks** (automated messages sent between systems over the internet). Here is the flow:

```
Your Platform  ──(sends message to)──>  DM Champ
                                           |
                                       AI Bot responds
                                       Contact saved
                                       Message stored
                                           |
DM Champ  ──(sends reply to)──>  Your Platform
```

1. **Incoming messages:** Your external platform sends messages to a DM Champ web address (URL). Think of it as your platform "posting" a message to DM Champ's mailbox.
2. **Processing:** DM Champ creates or updates the contact, stores the message, and has the AI bot generate a response (if active).
3. **Outgoing messages:** When DM Champ sends a reply (whether from the AI bot or typed by you), it sends the message to a URL on your platform, where your system can deliver it to the end user.

***

## Setting Up Incoming Messages (Your Platform to DM Champ)

To send messages from your external platform into DM Champ, your platform needs to send data to the following URL. Your developer will recognize this as a standard POST request.

### Where to Send Messages

```
POST https://europe-central2-whatzai.cloudfunctions.net/incomingCustomChannelMessage?apiKey=YOUR_API_KEY
```

Replace `YOUR_API_KEY` with your DM Champ API key. You can find or generate your API key in **Settings** > **Account** > **API Key**.

### Message Format

Send the message data in the following format (JSON):

```json
{
  "customData": {
    "messageSid": "unique-message-id-123",
    "fromId": "user-456",
    "toId": "your-business-id",
    "body": "Hello, I have a question about your service.",
    "status": "received",
    "channel": "my-live-chat",
    "campaignId": "optional-campaign-id",
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "mediaUrl": null,
    "mediaContentType": null
  },
  "messageType": "text"
}
```

**What each part means:**

* `messageSid` - A unique ID for this specific message (your system creates this). Used to prevent the same message from being processed twice.
* `fromId` - Who sent the message (could be a user ID, email, or phone number from your system).
* `toId` - Your business identifier (can be any label you choose).
* `body` - The actual message text.
* `channel` - A label you choose to identify where the message came from (e.g., "website-chat", "email").

### Full Field Reference

| Field                                      | Required? | What It Does                                                                                                                    |
| ------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `customData.messageSid` or `customData.id` | Yes       | A unique ID for this message (prevents duplicates)                                                                              |
| `customData.fromId`                        | Yes       | Identifies who sent the message (e.g., a user ID, email, or phone number from your system)                                      |
| `customData.toId`                          | Yes       | Identifies the receiving side (your business). Can be any text you choose.                                                      |
| `customData.body`                          | Yes       | The actual message text. Cannot be empty.                                                                                       |
| `customData.status`                        | No        | Message status. Leave this out to use the default (`"received"`).                                                               |
| `customData.channel`                       | No        | A label for the source (e.g., `"live-chat"`, `"email"`, `"my-crm"`). Helps you identify where messages came from in your inbox. |
| `customData.campaignId`                    | No        | A DM Champ campaign ID. Use this to route the message to a specific AI bot configuration.                                       |
| `customData.firstName`                     | No        | Contact's first name. Included when creating a new contact record.                                                              |
| `customData.lastName`                      | No        | Contact's last name. Included when creating a new contact record.                                                               |
| `customData.email`                         | No        | Contact's email address. Included when creating a new contact record.                                                           |
| `customData.mediaUrl`                      | No        | A link to an attached file (image, video, audio, or document). Can also be a base64-encoded file (see below).                   |
| `customData.mediaContentType`              | No        | The file type (e.g., `"image/jpeg"`, `"video/mp4"`, `"audio/ogg"`, `"application/pdf"`). Required if you include `mediaUrl`.    |
| `messageType`                              | No        | Type of message. Leave out for regular text. Set to `"reaction"` for emoji reactions.                                           |

### What You Get Back

A successful request returns:

```json
{
  "success": true,
  "messageId": "1234567890"
}
```

If something goes wrong, you will get an error message explaining the issue:

```json
{
  "error": "Message body cannot be empty"
}
```

### Status Codes

These are the response codes your system may receive. If you are not familiar with HTTP status codes, your developer will understand these:

| Code  | What It Means                                                                                     |
| ----- | ------------------------------------------------------------------------------------------------- |
| `200` | Success - message received and being processed                                                    |
| `400` | Something is wrong with your request - check for missing required fields or an empty message body |
| `405` | Wrong request method - make sure you are using POST, not GET                                      |
| `500` | Something went wrong on DM Champ's side - try again in a few moments                              |

***

## Sending Media Attachments (Images, Videos, Files)

You can include file attachments (images, videos, audio, documents) with your messages. There are two ways to do this:

### Option 1: Link to a File

If the file is already hosted online, provide the URL (web address) where DM Champ can download it:

```json
{
  "customData": {
    "messageSid": "msg-789",
    "fromId": "user-456",
    "toId": "business-1",
    "body": "Here is a photo of the issue.",
    "channel": "support-portal",
    "mediaUrl": "https://example.com/uploads/photo.jpg",
    "mediaContentType": "image/jpeg"
  },
  "messageType": "text"
}
```

### Option 2: Embed the File Directly (Base64)

If the file is not hosted online, you can embed it directly in the message as encoded text (base64 format). This is common in technical integrations where your system generates files on the fly. DM Champ will automatically decode and store the file:

```json
{
  "customData": {
    "messageSid": "msg-790",
    "fromId": "user-456",
    "toId": "business-1",
    "body": "Screenshot attached.",
    "channel": "support-portal",
    "mediaUrl": "data:image/png;base64,iVBORw0KGgo...",
    "mediaContentType": "image/png"
  },
  "messageType": "text"
}
```

> **Note:** Embedding files directly makes the message data much larger. For big files, it is better to host the file online and send a link (Option 1) instead.

***

## Setting Up Outgoing Messages (DM Champ to Your Platform)

When DM Champ sends a reply on a custom channel (whether from the AI bot or typed by you), it automatically sends that reply to a URL on your platform so your system can deliver it to the end user.

### Tell DM Champ Where to Send Replies

1. Go to **Settings** in DM Champ.
2. Find the **Custom Channel Webhook** section.
3. Enter the URL on your platform where DM Champ should send outgoing messages. (Your developer will set up this URL to receive and process the replies.)
4. Click **Save**.

### What DM Champ Sends to Your Platform

When DM Champ sends a reply, your platform will receive the following data:

```json
{
  "contactId": "abc123",
  "messageId": "msg-456",
  "userId": "your-dm-champ-user-id",
  "body": "Thank you for your message! Here is the information you requested...",
  "toId": "user-456",
  "channel": "my-live-chat"
}
```

### What Each Field Means

| Field       | What It Contains                                                                               |
| ----------- | ---------------------------------------------------------------------------------------------- |
| `contactId` | DM Champ's internal ID for this contact                                                        |
| `messageId` | The unique ID of this message in DM Champ                                                      |
| `userId`    | Your DM Champ user ID                                                                          |
| `body`      | The reply text                                                                                 |
| `toId`      | The contact's ID on your platform (this matches the `fromId` you sent in the incoming message) |
| `channel`   | The custom channel label you assigned                                                          |

Your platform receives this data and uses it to deliver the reply to the end user through your own system.

### How DM Champ Tracks Delivery

After sending the reply to your platform, DM Champ updates the message status:

* **Sent** - Your platform received the message successfully.
* **Failed** - Your platform returned an error or could not be reached. DM Champ stores the error details with the message so you can troubleshoot.

***

## Sending Messages from Your System to DM Champ

In addition to receiving messages, you can also send outbound messages through a custom channel directly from your own system. This is useful when you want to start a conversation or send a proactive message.

### Where to Send

```
POST https://europe-central2-whatzai.cloudfunctions.net/v1/send_custom_channel_message?apiKey=YOUR_API_KEY
```

### Message Format

```json
{
  "customData": {
    "fromId": "user-456",
    "customChannel": "my-live-chat",
    "body": "Hello! How can I help you today?",
    "campaignId": "optional-campaign-id",
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com"
  }
}
```

### Required Fields

| Field                      | What It Does                                           |
| -------------------------- | ------------------------------------------------------ |
| `customData.fromId`        | The contact's ID on your platform                      |
| `customData.customChannel` | The name of your custom channel (e.g., "my-live-chat") |
| `customData.body`          | The message text to send                               |

The optional fields (`campaignId`, `firstName`, `lastName`, `email`) work the same as in incoming messages - they help DM Champ create or update the contact record.

### What You Get Back

```json
{
  "success": true,
  "messageId": "generated-message-id",
  "contactId": "dm-champ-contact-id",
  "message": "Message sent successfully"
}
```

***

## Real-World Examples

Here are some common ways businesses use custom channels:

### Website Live Chat

Connect a live chat widget on your website to DM Champ so your AI bot can answer visitor questions:

1. A visitor types a message in your website's chat widget.
2. Your chat widget sends the message to DM Champ.
3. DM Champ's AI bot generates a response.
4. The response is sent back to your chat widget, which displays it to the visitor.

**Why this is useful:** Your website visitors get instant, AI-powered answers to their questions without you needing to be online.

### Email

Route email conversations through DM Champ so your AI bot can respond to emails:

1. Set up a system that forwards incoming emails to DM Champ (using the email sender's address as the `fromId`, the email subject and body as the `body`, and `"email"` as the `channel`).
2. DM Champ's AI bot reads the email and generates a reply.
3. The reply is sent back to your email system, which sends it as a normal email response.

**Why this is useful:** Common email questions (pricing, hours, availability) get answered instantly by your AI bot.

### CRM Integration

Connect your existing CRM (customer relationship management) system to DM Champ:

1. When a lead sends a message through your CRM, forward it to DM Champ.
2. DM Champ's AI bot responds and tracks the conversation.
3. The AI response is sent back to your CRM for delivery.
4. The full conversation history is available in both DM Champ and your CRM.

**Why this is useful:** Your sales team gets AI-assisted responses to leads without leaving their CRM.

### Support Ticket System

Use DM Champ as an AI-powered first responder for customer support:

1. Your ticketing system forwards new support tickets to DM Champ.
2. The AI bot sends an initial response (e.g., acknowledging the ticket and asking clarifying questions).
3. The response is attached to the ticket in your support system.
4. Your support team can review what the AI said and take over when needed.

**Why this is useful:** Customers get an immediate acknowledgment and initial help, even outside business hours.

***

## Troubleshooting

### Messages Not Being Received by DM Champ

* Verify your API key is correct and active (check in **Settings > Account > API Key**).
* Make sure you are sending a POST request (not GET). Your developer will know the difference.
* Check that the `customData.body` field is not empty or whitespace-only.
* Verify the `customData.fromId` field is included.
* Read the response message for specific error details.

### DM Champ Replies Not Reaching Your Platform

* Make sure you have entered your platform's URL in **Settings > Custom Channel Webhook**.
* Verify that the URL is publicly accessible (not behind a login or firewall) and returns a success response.
* Only replies (outgoing messages) are sent to your URL - incoming messages do not trigger this.
* Check for error details on the message in your DM Champ inbox.

### Contact Not Being Created

* Make sure the `fromId` value is consistent for the same user across all their messages. DM Champ uses this value to identify contacts - if it changes between messages, DM Champ will create a new contact each time.
* Include `firstName`, `lastName`, and `email` in the first message from a new contact to create a complete contact record.

### Media Attachments Not Working

* For file links (URLs), make sure the file is publicly accessible (no login required to access it).
* Always include `mediaContentType` when you include `mediaUrl`.
* For embedded files (base64), verify the format is `data:MIME_TYPE;base64,ENCODED_DATA`.
* Make sure the file type you specify matches the actual file content.

***

## Best Practices

* **Use consistent `fromId` values.** Each user on your platform should always have the same `fromId`. This ensures DM Champ groups all their messages into a single conversation instead of creating duplicate contacts.
* **Choose a clear `channel` name.** Pick something descriptive like `"website-chat"`, `"email"`, or `"zendesk"` so you can easily tell where messages came from when viewing your inbox.
* **Include contact details** (`firstName`, `lastName`, `email`) in the first message from a new contact. This creates a complete, useful contact record right away.
* **Build in retry logic.** Have your platform retry sending messages if DM Champ does not respond on the first attempt (network hiccups happen).
* **Use unique `messageSid` values** for every message. This prevents the same message from being processed twice if your system sends it more than once.
* **Use `campaignId`** to route messages to different AI bots when you have multiple use cases (e.g., sales inquiries vs. support questions).
* **Test before going live.** Send test messages in both directions and verify that contacts, conversations, and AI responses all work correctly before launching to real users.
