# Telegram

> Set up an Aerostack bot on Telegram — create a bot via BotFather, configure webhook verification, and go live.

Connect your Aerostack bot to Telegram. Messages sent to your Telegram bot are forwarded to Aerostack via webhook, processed through the bot engine, and responses are sent back automatically.

---

## Prerequisites

- An Aerostack account with an existing bot (or create one during setup)
- A Telegram account

---

## Step 1: Create a Telegram Bot

1. Open Telegram and search for [@BotFather](https://t.me/BotFather)
2. Send `/newbot`
3. Choose a **display name** (e.g., "Acme Support")
4. Choose a **username** (must end in `bot`, e.g., `acme_support_bot`)
5. BotFather will respond with your **bot token**

The token looks like: `123456789:ABCdefGhIJKlmNoPQRsTUVwxyz`

Keep your bot token secret. Anyone with this token can control your Telegram bot. If compromised, use `/revoke` with BotFather to generate a new one.

---

## Step 2: Configure in Aerostack

### Via Dashboard

1. Navigate to **Bots** in the sidebar
2. Click on your bot (or create a new one with platform set to **Telegram**)
3. In the **Platform Configuration** section, enter:
   - **Bot Token** — the token from BotFather
   - **Webhook Secret** — any random string (e.g., `my-secret-abc123`)

### Via API

```bash
# Create a new bot
curl -X POST https://api.aerostack.dev/api/bots \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Telegram Support Bot",
    "platform": "telegram",
    "workspace_id": "YOUR_WORKSPACE_ID",
    "system_prompt": "You are a helpful customer support assistant.",
    "platform_config": {
      "bot_token": "123456789:ABCdefGhIJKlmNoPQRsTUVwxyz",
      "webhook_secret": "my-secret-abc123"
    }
  }'
```

Or update an existing bot's platform config:

```bash
curl -X PATCH https://api.aerostack.dev/api/bots/YOUR_BOT_ID \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "platform_config": {
      "bot_token": "123456789:ABCdefGhIJKlmNoPQRsTUVwxyz",
      "webhook_secret": "my-secret-abc123"
    }
  }'
```

---

## Step 3: Activate

Activating registers the webhook URL with Telegram automatically via the Bot API `setWebhook` method.

### Via Dashboard

Click the **Activate** button on your bot's detail page.

### Via API

```bash
curl -X POST https://api.aerostack.dev/api/bots/YOUR_BOT_ID/activate \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Response:

```json
{
  "status": "active",
  "webhook_url": "https://api.aerostack.dev/api/bots/webhook/telegram/bt_a1b2c3d4e5f6g7h8i9j0"
}
```

The webhook URL format is:

```
https://api.aerostack.dev/api/bots/webhook/telegram/:botId
```

Aerostack calls the Telegram `setWebhook` API for you during activation. You do not need to set the webhook URL manually. The webhook is configured with `allowed_updates: ['message', 'callback_query']`.

---

## Step 4: Test

Send a message to your Telegram bot. You should see a response within a few seconds.

You can also use the Aerostack test endpoint to verify the bot engine works independently of Telegram:

```bash
curl -X POST https://api.aerostack.dev/api/bots/YOUR_BOT_ID/test \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "message": "Hello, what can you do?" }'
```

---

## Platform Config Fields

| Field | Required | Description |
|-------|----------|-------------|
| `bot_token` | Yes | Token from BotFather |
| `webhook_secret` | Recommended | Secret token for webhook verification. Sent as `X-Telegram-Bot-Api-Secret-Token` header. |
| `allowed_chat_types` | No | Array of allowed chat types (e.g., `["private", "group"]`) |
| `respond_in_groups` | No | Whether to respond in group chats (default: depends on `group_trigger`) |
| `group_trigger` | No | When to respond in groups: `mention` (default), `reply`, or `always` |

---

## Webhook Verification

When `webhook_secret` is set, Aerostack verifies incoming webhooks by checking the `X-Telegram-Bot-Api-Secret-Token` header against your configured secret.

If `webhook_secret` is not set, Aerostack accepts all incoming webhooks without verification. This is acceptable for development but not recommended for production — anyone who discovers your webhook URL could send spoofed messages.

---

## Group Chat Behavior

By default, the bot responds in groups only when **mentioned** (e.g., `@your_bot_name`) or when a `/command` is used. You can change this with the `group_trigger` setting:

| Trigger | Behavior |
|---------|----------|
| `mention` (default) | Responds to @mentions and /commands only |
| `reply` | Responds to @mentions, /commands, and direct replies |
| `always` | Responds to every message in the group |

---

## Message Limits

Telegram enforces a **4096 character limit** per message. If the bot's response exceeds this, Aerostack automatically splits it into multiple messages at whitespace boundaries.

---

## Pausing and Deleting

**Pause:** Unregisters the Telegram webhook. The bot stops receiving messages but retains its configuration.

```bash
curl -X POST https://api.aerostack.dev/api/bots/YOUR_BOT_ID/pause \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

**Delete:** Unregisters the webhook (best effort) and deletes the bot, all conversations, messages, and analytics.

```bash
curl -X DELETE https://api.aerostack.dev/api/bots/YOUR_BOT_ID \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

## Troubleshooting

| Issue | Solution |
|-------|---------|
| Bot not responding | Check that status is `active` and webhook is registered. Verify your bot token is correct. |
| "Unauthorized" from Telegram | Your bot token may have been revoked. Use `/revoke` with BotFather to get a new one, then update your bot's platform config. |
| Duplicate responses | Ensure only one webhook is registered. Check that no other service is using the same bot token. |
| Bot responds in DMs but not groups | Set `group_trigger` to `reply` or `always` in your platform config. |
