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

# Telegram bots

> Connect your Telegram bot to Shoppex for notifications, broadcasts, and AI-powered customer support

## Quick start

Connect your Telegram bot and send your first notification in under 5 minutes.

<Steps>
  <Step title="Create a bot with BotFather">
    Open [@BotFather](https://t.me/BotFather) in Telegram, run `/newbot`, and copy the bot token.
  </Step>

  <Step title="Connect it to Shoppex">
    ```bash theme={"system"}
    curl -X POST https://api.shoppex.io/dev/v1/telegram/bots \
      -H "Authorization: Bearer YOUR_DEV_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"bot_token": "123456:AAExampleToken"}'
    ```
  </Step>

  <Step title="Share your deep link">
    The response includes a `deep_link_url`. Share it with customers so they can opt in to notifications through Telegram.
  </Step>

  <Step title="Send a broadcast">
    Once customers connect, you can send broadcasts, set up journeys, or enable the AI agent.
  </Step>
</Steps>

Your bot is now live. The sections below cover notifications, broadcasts, journeys, the inbox, and the AI agent.

## Bot response shape

When you connect a bot, Shoppex returns a grouped resource:

```json theme={"system"}
{
  "data": {
    "id": "9d40c284-4f39-4d2e-a9d5-56ea2e7d5bc7",
    "shop_id": "3c649ff2-0a87-42de-897a-c07fc2f9a79d",
    "identity": {
      "telegram_bot_id": "123456789",
      "username": "shoppex_demo_bot",
      "display_name": "Shoppex Demo Bot"
    },
    "verification": {
      "status": "VERIFIED",
      "last_verified_at": "2026-04-06T11:20:00.000Z",
      "last_error": null
    },
    "connection": {
      "webhook_url": "https://api.shoppex.io/telegram-webhook-url",
      "deep_link_url": "https://t.me/shoppex_demo_bot?start=shop:3c649ff2-0a87-42de-897a-c07fc2f9a79d",
      "merchant_deep_link_url": "https://t.me/shoppex_demo_bot?start=shop%3A3c649ff2-0a87-42de-897a-c07fc2f9a79d%2Cmanager%3Ausr_123%2Csig%3Aabc123"
    },
    "agent": {
      "enabled": false,
      "mode": "CUSTOMER_SALES",
      "has_api_key": false,
      "api_key_generated_at": null,
      "last_routed_at": null
    }
  }
}
```

## Customer linking

Customers connect to your shop through the bot deep link `https://t.me/<bot_username>?start=shop:<shop_id>`. Add context to the link for richer linking:

| Link format                                               | Use case                                             |
| --------------------------------------------------------- | ---------------------------------------------------- |
| `?start=shop:<shop_id>`                                   | Basic opt-in                                         |
| `?start=shop:<shop_id>,customer:<customer_id>`            | Link to an existing customer for order confirmations |
| `?start=shop:<shop_id>,email:<urlencoded_email>`          | Link guest checkouts by email                        |
| `?start=shop:<shop_id>,manager:<user_id>,sig:<signature>` | Merchant assistant mode (signed)                     |

The bot response includes the merchant deep link pre-built under `connection.merchant_deep_link_url`. It binds the Telegram chat to a Shoppex manager, so merchant-only agent flows route safely.

List linked users:

```bash theme={"system"}
curl "https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users?is_active=true&limit=25" \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

## Notifications

Shoppex sends Telegram messages automatically for order confirmations, restock alerts, and promotional broadcasts. Each user's `notification_preferences` object controls what they receive, and the defaults apply until you change them.

Update a single user:

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users/USER_ID/notifications \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "notification_preferences": {
      "enabled_types": ["ORDER_CONFIRMATION", "PRODUCT_RESTOCK"]
    }
  }'
```

Update multiple users at once:

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/users/bulk/notifications \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_ids": [
      "11111111-1111-4111-8111-111111111111",
      "22222222-2222-4222-8222-222222222222"
    ],
    "notification_preferences": {
      "enabled_types": ["PROMOTIONAL_OFFERS"]
    }
  }'
```

## Broadcasts

A broadcast sends a message to a filtered audience, right away or on a schedule. A broadcast request has three parts:

| Group      | What it controls                                                                                                      |
| ---------- | --------------------------------------------------------------------------------------------------------------------- |
| `content`  | The message body, parse mode, and inline keyboard buttons                                                             |
| `audience` | Filter by notification type, activity (`only_active_users`, `last_activity_after`), or saved segments (`segment_ids`) |
| `delivery` | When to send (`scheduled_for`) and the rate, up to 30 messages per second (`messages_per_second`)                     |

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": {
      "body": "<b>Restock alert</b>\nYour item is back in stock.",
      "parse_mode": "HTML",
      "inline_keyboard": [
        [{"text": "Open product", "url": "https://demo.myshoppex.io/product/prod_123"}]
      ]
    },
    "audience": {
      "notification_types": ["PRODUCT_RESTOCK"],
      "only_active_users": true
    },
    "delivery": {
      "messages_per_second": 15
    }
  }'
```

<Note>
  URL buttons are automatically wrapped in Shoppex tracking links, so you get click-through rates and revenue attribution for free.
</Note>

Broadcasts move through these states: `DRAFT → SCHEDULED → SENDING → COMPLETED / CANCELLED / FAILED`.

For product-specific restocks, use the dedicated endpoint. Shoppex builds the message from the product data:

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts/warehouse-restock \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "33333333-3333-4333-8333-333333333333",
    "variant_id": "44444444-4444-4444-8444-444444444444",
    "content": {"body": "Back in stock now", "parse_mode": "HTML"},
    "audience": {"only_active_users": true},
    "delivery": {"messages_per_second": 10}
  }'
```

### Saved segments

Save a repeated audience filter as a segment:

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/segments \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Active buyers",
    "description": "Customers active in the last 30 days",
    "filters": {
      "only_active_users": true,
      "linked_only": true,
      "notification_types": ["ORDER_CONFIRMATION"]
    }
  }'
```

Reference the saved segment in any broadcast with `audience.segment_ids: ["<segment_id>"]`. Manage segments with `GET`, `PUT`, and `DELETE` on `/dev/v1/telegram/bots/:botId/segments/:segmentId`.

### Analytics and click tracking

Shoppex tracks URL button clicks per broadcast and attributes completed orders back to the broadcast that drove them:

1. You send a broadcast with a product button.
2. Shoppex rewrites the URL to a tracking link.
3. The customer clicks, and Shoppex records the click before it redirects to the product page.
4. If the customer completes an order inside the attribution window, the revenue counts back to that broadcast.

```bash theme={"system"}
curl https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/broadcasts/BROADCAST_ID/analytics \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

The response `overview` object reports:

| Field                                     | Meaning                                          |
| ----------------------------------------- | ------------------------------------------------ |
| `delivered_count`, `failed_count`         | Messages delivered and messages that failed      |
| `unique_clicked_users`, `click_count`     | Distinct clickers and total clicks               |
| `click_through_rate`                      | Click-through rate as a percentage               |
| `attributed_orders`, `attributed_revenue` | Orders and revenue linked back to this broadcast |

Each entry in the `buttons` array reports `button_id`, `text`, `destination_url`, `unique_clicked_users`, and `click_count`.

Track delivery and bot-level performance with:

* `GET /dev/v1/telegram/bots/:botId/broadcasts` — list all broadcasts
* `GET /dev/v1/telegram/bots/:botId/broadcasts/:id` — a single broadcast
* `GET /dev/v1/telegram/bots/:botId/broadcasts/:id/stats` — delivery progress
* `GET /dev/v1/telegram/bots/:botId/analytics` — bot-level analytics

The broadcast response groups delivery progress under `delivery`: `sent_count`, `failed_count`, `progress_percentage`, `estimated_time_remaining_seconds`, and `failure_reasons`.

## Journeys

Journeys are event-driven follow-up flows, such as a post-purchase drip or an abandoned-cart reminder. Shoppex sends each message on its own schedule, so you do not send them by hand.

| Trigger                | When it fires                                            |
| ---------------------- | -------------------------------------------------------- |
| `ORDER_COMPLETED`      | After a successful order                                 |
| `ABANDONED_CART`       | When a customer starts checkout but does not complete it |
| `PAYMENT_REMINDER`     | Before a payment deadline                                |
| `SUBSCRIPTION_RENEWAL` | Before a subscription renews                             |
| `MANUAL`               | Triggered by your API call                               |

Example post-purchase follow-up:

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/journeys \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Post-purchase follow-up",
    "trigger": "ORDER_COMPLETED",
    "filters": {"only_active_users": true},
    "steps": [
      {
        "delay_minutes": 0,
        "content": {"body": "Thanks for your order.", "parse_mode": "HTML"}
      },
      {
        "delay_minutes": 1440,
        "content": {"body": "Need help with your order?", "parse_mode": "NONE"}
      }
    ]
  }'
```

This journey fires when a customer completes an order. It sends the first message immediately and queues the follow-up for 24 hours later. Test a journey before you turn it on with `POST /dev/v1/telegram/bots/:botId/journeys/:journeyId/test`.

## Support commands and inbox

The bot doubles as a two-way support channel.

Customer commands:

| Command     | What it does                             |
| ----------- | ---------------------------------------- |
| `/settings` | Opens the notification preference center |
| `/track`    | Tracks an order                          |
| `/buyagain` | Reorders the last purchase               |
| `/help`     | Opens the support flow                   |

Merchant inbox endpoints:

* `GET /dev/v1/telegram/bots/:botId/inbox` — list conversations
* `GET /dev/v1/telegram/bots/:botId/inbox/:conversationId` — read a conversation
* `POST /dev/v1/telegram/bots/:botId/inbox/:conversationId/reply` — send a reply
* `PUT /dev/v1/telegram/bots/:botId/inbox/:conversationId/status` — close or reopen

```bash theme={"system"}
curl -X POST https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/inbox/CONVERSATION_ID/reply \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message": "We are checking your order now.", "parse_mode": "HTML"}'
```

## AI agent

The AI agent routes inbound Telegram messages through Shoppex commerce tools: product search, order lookup, coupon creation, and payment links.

| Mode                 | Who it serves                         | What it can do                                                         |
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
| `CUSTOMER_SALES`     | Customers                             | Search products, look up orders, share payment links                   |
| `MERCHANT_ASSISTANT` | Merchants, through a signed deep link | Create coupons, check revenue, manage products                         |
| `BOTH`               | Both, on the same bot                 | Routes based on whether the chat is linked to a customer or a merchant |

Enable the agent:

```bash theme={"system"}
curl -X PUT https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/agent \
  -H "Authorization: Bearer YOUR_DEV_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agent_enabled": true, "agent_mode": "BOTH"}'
```

When you enable the agent, Shoppex creates a shop-scoped Dev API key for the bot. It stores inbound messages as inbox history, routes each message to the AI model, and sends the response back to Telegram.

Check usage:

```bash theme={"system"}
curl https://api.shoppex.io/dev/v1/telegram/bots/BOT_ID/agent/stats \
  -H "Authorization: Bearer YOUR_DEV_API_KEY"
```

The response reports `calls`, `completed_calls`, `failed_calls`, `rate_limited_calls`, `conversations`, `total_tokens`, `estimated_cost_usd`, `average_response_time_ms`, and `last_run_at`.

A customer asking "Do you have the hoodie in black?" gets a product search and a direct answer. A merchant saying "Create a 15% coupon for the hoodie" gets a coupon created through the Dev API. The `estimated_cost_usd` field tracks AI token costs, so there are no surprises on your bill.
