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

# Custom channel

> Write an input channel that receives messages from your own service, or change a built-in connector such as Twilio, and register it under channels.

A channel is how the agent receives messages and sends replies. An input channel
receives messages from a service over HTTP and passes each one to the agent. The
built-in connectors cover Twilio, Slack, Telegram, and others. Write your own
when your service's webhook format is none of those, or subclass a built-in to
change one part of it.

## Before you start

Put your code in a package next to `agent.yml`: a folder named `addons/` with an
empty `__init__.py` file. Start `rasa` from the project root so the package can
be imported.

## Subclass `InputChannel`

Import `InputChannel`, `CollectingOutputChannel`, and the other types from
`rasa.api.channels.v1`. Implement `name`, `connect`, and `blueprint`.

`blueprint` returns a Sanic `Blueprint`, which holds the routes your channel
serves. Each incoming message goes to the agent through `on_new_message`.

```python addons/custom_channel.py theme={null}
from sanic import Blueprint, response
from sanic.request import Request
from sanic.response import HTTPResponse

from rasa.api.channels.v1 import (
    ChannelSettings,
    CollectingOutputChannel,
    InputChannel,
    OnNewMessageType,
    UserMessage,
)


class MyChannel(InputChannel):
    @classmethod
    def name(cls) -> str:
        """Return the name used in the URL path and as input_channel on each message."""
        return "my_channel"

    def connect(self, settings: ChannelSettings) -> None:
        """Read settings.params when Mantle creates the channel."""
        self.token = settings.params["token"]

    def blueprint(self, on_new_message: OnNewMessageType) -> Blueprint:
        """Build the Sanic blueprint that serves this channel's routes."""
        webhook = Blueprint("my_channel_webhook", __name__)

        @webhook.route("/webhook", methods=["POST"])
        async def receive(request: Request) -> HTTPResponse:
            """Check the bearer token, pass the message to the agent, and return its replies."""
            if request.headers.get("Authorization") != f"Bearer {self.token}":
                return response.json({"error": "unauthorized"}, status=401)

            body = request.json
            collector = CollectingOutputChannel()
            await on_new_message(
                UserMessage(
                    text=body["message"],
                    output_channel=collector,
                    sender_id=body["sender"],
                    input_channel=self.name(),
                )
            )
            return response.json(collector.messages)

        return webhook
```

This example replies by returning the messages in the HTTP response. It uses
`CollectingOutputChannel` for that, which is a built-in output channel. If your
service needs replies pushed to it instead, subclass `OutputChannel` and implement
`send_text_message`. Then pass that output channel in `UserMessage`.

The example checks a bearer token on each request. Reject requests that do not
carry it, as this one does, so anyone who knows the URL cannot send messages.

Register the class under `channels`, using its module path as the key. The values
under it arrive in `connect` as `settings.params`:

```yaml integrations.yml theme={null}
channels:
  addons.custom_channel.MyChannel:
    token: ${MY_CHANNEL_TOKEN}
```

By default, Rasa serves a channel's routes under `/webhooks/<name>/`, where
`<name>` is the value `name()` returns. With the example above, the endpoint is
`POST /webhooks/my_channel/webhook`.

| Method | Required | Purpose |
| - | - | - |
| `name()` | yes | Class method. Returns the name used in the URL path and as `input_channel` on each message |
| `connect(settings)` | yes | Read `settings.params` and set up your client |
| `blueprint(on_new_message)` | yes | Return a Sanic `Blueprint` with the channel's routes |
| `get_metadata(request)` | no | Return a dictionary attached to each message. The default returns `None` |

## Subclass a built-in connector

To change one part of a built-in connector and keep the rest, subclass it from
`rasa.api.channels.v1.twilio`. This example tags each message with the Twilio
number it arrived on, which helps when one agent serves several numbers:

```python addons/custom_twilio.py theme={null}
from typing import Any, Optional

from sanic.request import Request

from rasa.api.channels.v1.twilio import TwilioInput


class MyTwilioInput(TwilioInput):
    def get_metadata(self, request: Request) -> Optional[dict[str, Any]]:
        """Return the Twilio number the message arrived on. Called for each request."""
        form = request.form or {}
        return {"twilio_number": form.get("To")}
```

```yaml integrations.yml theme={null}
channels:
  addons.custom_twilio.MyTwilioInput:
    account_sid: ${TWILIO_ACCOUNT_SID}
    auth_token: ${TWILIO_AUTH_TOKEN}
    twilio_number: ${TWILIO_NUMBER}
    webhook_url: ${TWILIO_WEBHOOK_URL}
```

`webhook_url` is the public URL Twilio posts to. The signature check uses it, so
it must match the URL in your Twilio console. The check itself is inherited
unchanged. The keys are the ones the built-in Twilio connector reads. See
[`channels`](https://rasa.com/docs/mantle/reference/integrations-yml#channels) for the rules on each channel
entry.

## Versioning

The import `rasa.api.channels.v1` is the version. YAML names only the class. See
[Custom integrations: Versioning](https://rasa.com/docs/mantle/reference/custom-integrations.md#versioning).


## Related topics

- [Custom Connectors](https://rasa.com/docs/reference/channels/custom-connectors.md)
- [Custom integrations](https://rasa.com/docs/mantle/reference/custom-integrations.md)
- [Post user message from a custom channel](https://rasa.com/docs/reference/api/pro/http-api/channel-webhooks/post-user-message-from-a-custom-channel.md)
- [Rasa Pro Version Migration Guide](https://rasa.com/docs/reference/changelogs/rasa-pro-migration-guide.md)
- [responses.yml](https://rasa.com/docs/mantle/reference/responses-yml.md)


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