# Gateway

Bub was originally inspired by always-on agents such as OpenClaw and nanobot. Beyond terminal sessions, Bub can run as a long-lived gateway that listens for messages from chat platforms.

Run `bub gateway` to start all enabled message channels. Bub includes a built-in Telegram channel; other platforms can be added via community [plugins](https://hub.bub.build/).

## Start the Telegram gateway {#telegram}

:::note
Make sure Bub is installed and configured, and obtain a bot token from [@BotFather](https://t.me/BotFather).
:::

1. **Configure `.env`**

   Add your bot token and allowed user ID (look up your numeric ID via [@userinfobot](https://t.me/userinfobot)) to `.env` in your workspace root:

   ```bash title=".env"
   BUB_TELEGRAM_TOKEN=123456789:your-telegram-bot-token
   BUB_TELEGRAM_ALLOW_USERS=123456789
   ```

2. **Start the gateway**

   ```bash
   bub gateway
   ```

   Startup log output:

   ```text
   telegram.start allow_users_count=1 allow_chats_count=0 proxy_enabled=False
   telegram.start polling
   ```

3. **Test a private message**

   Try sending your bot a direct message on Telegram and wait a moment for a reply. If it does not respond, check [How replies are sent](#telegram-outbound) and [Troubleshooting](#troubleshooting).

The gateway requires at least one enabled channel. The Telegram channel is enabled automatically whenever `BUB_TELEGRAM_TOKEN` is non-empty.

## Configure Telegram {#configure-telegram}

### Access allowlists {#restrict-access}

Use `BUB_TELEGRAM_ALLOW_USERS` to restrict which users can message the bot, and `BUB_TELEGRAM_ALLOW_CHATS` to restrict which chats or groups are allowed (comma-separated; usernames are case-sensitive):

```bash
BUB_TELEGRAM_ALLOW_USERS=123456789,your_username
BUB_TELEGRAM_ALLOW_CHATS=-1001234567890,-1009876543210
```

| Allowlist variable | Pass condition | On failure |
| --- | --- | --- |
| `BUB_TELEGRAM_ALLOW_USERS` | Numeric user ID or username matches | Replies `Access denied.` |
| `BUB_TELEGRAM_ALLOW_CHATS` | Chat ID matches | Silently drops the message |

When both are set, both must match. **When both allowlists are empty, anyone on Telegram can use your bot** — always configure at least one before deploying publicly.

### Group chat triggers {#telegram-inbound}

Before adding the bot to a group, disable **Privacy Mode** in [@BotFather](https://t.me/BotFather); otherwise Telegram only delivers `/` slash commands to the bot.

To keep the bot from jumping into every casual conversation, Bub accepts group messages under these rules:

| Message type | Trigger condition |
| --- | --- |
| Non-command messages in private chats | Always accepted |
| Group text messages | Mentions `@<bot_username>`, contains `bub` (case-insensitive substring match, so `bubble` also matches), or replies to a bot message |
| Group images/files with captions | Same as group text messages |
| Group images/stickers/files without captions | Only when replying directly to a bot message |
| `/bub <text>` | Strips `/bub ` and passes the remaining text as the prompt |

Other group messages are ignored unless the group was triggered recently and is still within `BUB_ACTIVE_TIME_WINDOW` (see [Merge consecutive messages](#merge-consecutive-messages)).

### How replies are sent {#telegram-outbound}

In the Telegram channel, **ordinary messages** and **comma commands** use different outbound paths:

| Input type | `output_channel` | How replies are sent |
| --- | --- | --- |
| Ordinary message | `"null"` (disables automatic direct reply) | The model calls the built-in `telegram` skill to send replies, quote messages, or edit status |
| Comma command (e.g. `,help`) | `"telegram"` | Skips the model and sends tool output directly back to `chat_id` |

Why the split? In group chats and multi-step tasks, an Agent often needs to post a status update, edit it in place, or stay quiet when a message needs no reply. Routing ordinary messages through the built-in `telegram` skill gives the model full control over when and how to respond.

:::note
For ordinary messages, **the model must call the `telegram` skill for the user to receive a reply in Telegram**. While a Turn is running, the `typing...` indicator renews every 4 seconds to show that the background Turn is still active.
:::

Comma commands (such as `,tape.info`) skip the model and send their output directly: if the result is JSON with a `message` field, only `message` is sent; other non-empty text is sent as-is; empty output is ignored.

### Merge consecutive messages {#merge-consecutive-messages}

In chat apps, people often split one thought across several short messages (for example, sending "check this error" followed right away by a stack trace). To avoid wasting tokens and fragmenting context, the Telegram channel automatically merges consecutive messages arriving within a short window into a single Turn (joined by newlines):

| Environment variable | Default | Description |
| --- | --- | --- |
| `BUB_DEBOUNCE_SECONDS` | `1.0` | **Active message debounce**: wait timer reset by each active message (private chat or group message mentioning the bot) |
| `BUB_MAX_WAIT_SECONDS` | `10.0` | **Follow-up max wait**: maximum wait time when buffering unmentioned follow-up messages in a group |
| `BUB_ACTIVE_TIME_WINDOW` | `60.0` | **Active group window**: seconds after an active trigger during which unmentioned group messages join the current batch |

Direct commands starting with the command prefix (`,` by default) skip debouncing and run immediately.

### Proxy {#telegram-reference}

```bash
BUB_TELEGRAM_PROXY=http://127.0.0.1:7890
# socks5://<user>:<YOUR_PROXY_PASSWORD>@host:port is also supported
```

## Connect other platforms {#other-platforms}

Install community channel [plugins](https://hub.bub.build/), restart the gateway, and run `bub hooks` to verify the channel name appears under `provide_channels` (channels without configured credentials are skipped at startup):

| Platform | Channel name | Plugin |
| --- | --- | --- |
| Discord | `discord` | [`bub-discord`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-discord) |
| Slack | `slack` | [`bub-slack`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-slack) |
| WeChat | `wechat` | [`bub-wechat`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-wechat) |
| WeCom | `wecom` | [`bub-wecom`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-wecom) |
| Feishu | `feishu` | [`bub-feishu`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-feishu) |
| DingTalk | `dingtalk` | [`bub-dingtalk`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-dingtalk) |
| QQ | `qq` | [`bub-qq`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-qq) |

## Build a custom channel {#custom-channels}

If no community plugin exists for your platform, you can write your own by subclassing `Channel` and implementing `start`, `stop`, and `send`:

```python showLineNumbers collapse={1-6} {8, 30-37}
import asyncio

from bub.channels.base import Channel
from bub.channels.message import ChannelMessage

class MyChannel(Channel):
    name = "myapp"

    def __init__(self, on_receive, token: str) -> None:
        self._on_receive = on_receive
        self._token = token
        self._listener: asyncio.Task | None = None

    @property
    def enabled(self) -> bool:
        return bool(self._token)

    async def start(self, stop_event: asyncio.Event) -> None:
        # start must not block the event loop; spawn a background task
        self._listener = asyncio.create_task(self._listen(stop_event))

    async def stop(self) -> None:
        if self._listener is not None:
            self._listener.cancel()

    async def _listen(self, stop_event: asyncio.Event) -> None:
        while not stop_event.is_set():
            chat_id, text = await self._next_message()
            await self._on_receive(
                ChannelMessage(
                    session_id=f"myapp:{chat_id}",
                    channel=self.name,
                    chat_id=chat_id,
                    content=text,
                )
            )

    async def send(self, message: ChannelMessage) -> None:
        await self._post(message.chat_id, message.content)
```

Implementation notes:

- Call the `on_receive` callback passed by the framework for each inbound message.
- Format `session_id` as `<channel>:<chat_id>` to avoid cross-platform collisions.
- Return `False` from `enabled` when credentials are missing so the gateway skips the channel.
- Return `True` from `needs_debounce` if consecutive short messages should be batched.

Register the channel via the `provide_channels` hook:

```python
import os
from bub import hookimpl

@hookimpl
def provide_channels(message_handler):
    return [MyChannel(on_receive=message_handler, token=os.environ.get("MYAPP_TOKEN", ""))]
```

Start the gateway with `bub gateway --enable-channel myapp`.

## Run as a background service {#daemon}

If you want Bub to stay running in the background as a system service, install it with:

```bash
bub gateway --install

# Uninstall
# bub gateway --uninstall
```

| OS | Behavior |
| --- | --- |
| Linux | systemd user unit `bub-gateway.service`; run `loginctl enable-linger $USER` to keep it running after SSH logout |
| Windows | Scheduled task for the current user; starts at login and restarts on failure |
| macOS | `--install` is not supported; use `launchd`, `tmux`, or [Docker deployment](/docs/app/deploy/) |

`--install` records the current Python interpreter, workspace directory, and `--enable-channel` flags. Re-run `bub gateway --install` if you move the workspace or change virtual environments.

## Troubleshooting {#troubleshooting}

| Symptom | Possible cause | Fix |
| --- | --- | --- |
| `No channels are enabled` | No channel is enabled | Check your token and `.env` path; run `bub hooks` to verify channel plugins |
| No `telegram.start` in logs | `BUB_TELEGRAM_TOKEN` is empty | Confirm the token is set in the environment running `bub` |
| Private chat replies `Access denied.` | User is not in the allowlist | Add your numeric ID or username to `BUB_TELEGRAM_ALLOW_USERS` |
| No response in private chat | Chat ID is not in the allowlist | Add the chat ID to `BUB_TELEGRAM_ALLOW_CHATS` |
| No response in group chat | Privacy Mode is enabled or trigger rules were not met | Disable Privacy Mode in BotFather; @-mention the bot directly to test |
| `typing...` forever with no reply | Model did not call the `telegram` skill | See [How replies are sent](#telegram-outbound) |
| `409 Conflict` | Multiple gateway instances use the same bot token | Stop duplicate processes |
| Offline messages are skipped on restart | Backlog updates are discarded at startup | Expected behavior |